Python Programming: learning notes from introduction to practice Chapter 5 ~ Chapter 7
25 note that the result of a Boolean expression is either True or False
Capitalize the first letter
26.if statement
for car in cars: if car == 'bmw' : print(car.upper()) else: print(car.title())
Use and to check multiple conditions (and is equivalent to & &)
Use or to check multiple conditions (or is equivalent to |)
To improve readability, place each test in a separate pair of parentheses
as
(age_0 >=21)and(age_1>=21)
Check whether a specific value is included in the list
'mushrooms' in rquested_toppings
Check whether a specific value is not included in the list
'mushrooms' not in rquested_toppings
If conditional_test : do something
Note if_elif_else structure, multiple elif code blocks can be used
When using a list name in a conditional expression in an IF statement, Python returns True if the list contains at least one element and False if the list is empty
27. Dictionary
In Python, a dictionary is a series of key value pairs. Each key is associated with each value, and you can use the key to access the value associated with it. The values associated with keys can be numbers, strings, lists, or even dictionaries, and any Python object can be used as a dictionary value
In Python, dictionaries are represented by a series of key value pairs placed in curly braces {}
Key value pairs are two associated values. When you specify a key, Python returns the value associated with it. Keys and values are separated by colons, and key value pairs are separated by commas
aline_0={'color':'green' , 'points':5} print(aline_0['color'] print(aline_0['points']) aline_0['x_position']=0 #Add key value pair alien_0['y_position']=25 print(alien_0) #At this time, it will be printed as {color ':' green ',' points': 5, 'y_position': 25, 'x_position': 0} #Python does not care about the order in which key value pairs are added, but only about the relationship between key value pairs del alien_0['points'] #Delete the key value pair with del statement, and the key value pair disappears forever
28. Traverse key value pairs
user_0={'username':'efermi' , 'first':'enrico' ,'last':'fermi'} for key,value in user_0.items(): print("\nKey: "+key) print('value: "+value)
The dictionary name and method items() return a list of key value pairs
Traverse all keys in the dictionary
for name in user_0.keys(): #The variable name after for is optional for name in user_0: #The effect is the same as the previous line of code, but it is easier to understand the display using the method keys()
Traverse all values in the dictionary
for value in user_0.values():
29 set
f
avorite_languages={ 'jen':'python','sarah':'c','phil':python'} for language in set(favorite_langugaes.values()): print(language.title())
By calling set() on a list containing duplicate elements, Python can find the unique elements in the list and use them to create a collection
30 nesting
List nested dictionary
alien_0={'color':'green','points':5} alien_1={'color':'yellow','points':10} aliens={alien_0,alien_1} for alien in aliens: print(alien) aliens=[] #Create thirty green aliens for alien_number in range(0,30) : new_alien={'color':'green','points':5,'speed':'slow'} aliens.append(new_alien) #Show the first five aliens for alien in aliens[ :5] print(alien)
Store list in dictionary
pizza={'crust':'thick','toppings':['mushrooms','extra cheese']}
Whenever you need to associate a key to multiple values in the dictionary, you can nest a list in the dictionary
Store dictionary in dictionary
users={ 'asinstein':{ 'first':'albert', 'last':'einstein' }, 'mcurie':{ 'first':'marie', 'last':'curie' } }
31 user input
message=input("Tell me something,and I will repeat it back to you: ") print(message)
Sometimes the prompt may exceed one line. In this case, you can store the prompt in a variable and pass the variable to the function input()
32 get numeric input using int()
When using the function input(), Python interprets user input as a string
age=input("How old are you?") age=int(age)
33.while loop
current_num=1 while current_num<=5 : print(current_num) current_num+=1 #Output result printing 1 ~ 5
In a program that requires many conditions to be met before it can continue to run, a variable can be defined to judge whether the whole program is active. This variable is called a flag
prompt="\nTell me something,and I will repeat it back to you: " prompt+="\nEnter 'quit' to end the program" active=True #active here is the flag while active : message=input(prompt) if message=='quit' : active=False else: print(message)
You can use the break statement in any Python loop. For example, you can use the break statement to exit a for loop that traverses a list or dictionary
continue Statement
current_num=0 while current_num<10 : current_num+=1 if current_num%2==0 : continue print(current_num) #The result prints all odd numbers between 1 and 10
If the program falls into an infinite loop, you can press Ctrl+C or close the terminal window displaying the program output
The for loop is an effective way to traverse the list, but the list should not be modified in the for loop, otherwise it will make it difficult for Python to track the elements in it. To modify the list while traversing it, use the while loop
Move elements between lists
unconfirmed_users=['alice','brian',candace'] confirmed_users=[] while unconfirmed_users : current_user=unconfirmed_users.pop() print("Verifying user: "+current_user.title()) confirmed_users.append(current_user)
Deletes all list elements that contain a specific value
In Chapter 3, the function remove() is used to delete a specific value in the list. This is feasible because the value to be deleted only appears once in the list
pets=['dog','cat','dog','goldfish','cat','cat'] while 'cat' in pets: pets.remove('cat')
Use user input to populate the dictionary
resonses={} #Set a flag indicating whether the investigation continues polling_active=True while polling_active: name=input("\nWhat is your name?") respnse=input("\nWhich mountain would you like to climb?") responses[name]=response repeat=input("Would you like to let another person respond?(yes/no)") if repeat=='no': polling_active=False
Please give me more advice, thank you for watching!