[Python programming from entry to practice] if statement, dictionary, while circulation

Chapter V .if statement

if, else similar for circulation, should be added back:

5.1 and or logical operators

car = "BMW"
print(car == "bmw") # 输出 False
print(car.lower() == "bmw") # 输出 True

if car == "1":
    print("Yes")
else:
    print("No")

age_0 = 22
age_1 = 18
if age_0 > 21 and age_1 > 21:
    print("Both > 21")
else:
    print("Someone <= 21")

if (age_0 > 21) or (age_1 > 21): # 可以加括号增强可读性
    print("Someone > 21")
else:
    print("Both <= 21")

5.2 in check whether a value is in the list

requested_toppings = ['mushrooms', 'onions', 'pineapple']
print('mushrooms' in requested_toppings) # 输出 True

By the same token not in Checks whether a value not in the list

banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
    print(user.title() + ", you can post a response if you wish")
# 输出 Marie, you can post a response if you wish

Purpose: In a map program, you may need to check the location of the user submitted is included in the list of known locations; the end user of the registration process, you may need to check if he provides the user name included in the list of user names, and usually first the user name into all lowercase and then to compare

5.3 if-elif-else structure

Python is behind if-elif-else to adding:

C ++ is behind if-else if-else structure plus{}

digit = 12
if digit < 4:
    print("Your admission cost is $0.")
elif digit < 18:
    print("Your admission cost is $5.")
else:
    print("Your admission cost is $10.")

else is an all-encompassing statement, as long as the condition is not satisfied if any test or elif, where code will be executed, so if you know the conditions of the end to be tested, should consider using a code block instead of elif else block. So we can be sure only when the appropriate conditions are met, your code will execute

Example :

# 披萨店点披萨
# requested_toppings = []
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
if requested_toppings:  # 列表非空时执行
    for requested_topping in requested_toppings:
        if requested_topping == 'green peppers':
            print("Sorry, we are out of green peppers right now.")
        else:
            print("Adding " + requested_topping + ".")
    print("\nFinished making your pizza!")
else:
    print("Are you sure you want a plain pizza?")

Export

Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.

Finished making your pizza!


Chapter VI. Dictionary

6.1 using the dictionary {:,:}

Use a dictionary allows us to simulate real-world situations in college, a person such as creating a representation of the dictionary, you can then store information: name, age, address, occupation, and to describe any aspect

In Python dictionary is a series 键-值of (similar to the map C ++), any python objects can be used as the value of the dictionary

Access the dictionary values: Specifies the dictionary name and put the key in square brackets

# 使用字典
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['points']) # 输出5

Add key - the value of the
dictionary is a dynamic structure, where at any time add key - value pairs
Python not care key - the value of the order of addition, but only concerned with the relationship between the key and value

alien_0 = {'color': 'green', 'points': 5}
print(alien_0['points']) # 输出5

alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0) # 输出 {'color': 'green', 'points': 5, 'x_position': 0, 'y_position': 25}

6.2 Delete key - value pairs del

When using del, you need to specify the name of the dictionary and you want to delete key

alien_0 = {'color': 'green', 'points': 5}
del alien_0['points']
print(alien_0)  # 输出 {'color': 'green'}

6.3 Dictionary of similar objects of

# 由类似对象组成的字典
favorite_languages = {
    'jeny': 'Python',
    'sarah': 'c',
    'wilson': 'c++'
}
# 较长的print语句可分成多行
print("Wilson's favorite language is " +
      favorite_languages['wilson'].title()
      + ".")
# 输出 Wilson's favorite language is C++.

6.4 traversing dictionary items ()

Python dictionary traversal each key - value pair, and the key is present in the variable name, the value in the presence of a variable language

items () Returns a key - value pair list

# 遍历字典
favorite_languages = {
    'kevin': 'java',
    'jeny': 'python',
    'sarah': 'c',
    'wilson': 'c++',
}

for name, language in favorite_languages.items():
    print(name.title() + "'s favorite language is " 
    + language.title() + ".")

6.4.1 traverse the dictionary all the keys keys () or default

Default loop over the keys while traversing the dictionary, so the following for name in favorite_languages.keys():into for name in favorite_languages:effect is the same

favorite_languages = {
    'kevin': 'Java',
    'jeny': 'Python',
    'sarah': 'c',
    'wilson': 'c++',
}

for name in favorite_languages.keys():
    print(name.title())

Method keys () returns dict_keys ([]) list

print(favorite_languages.keys())  
# 输出 dict_keys(['kevin', 'jeny', 'sarah', 'wilson'])

6.4.2 sequentially through all keys in the dictionary sorted ()

The method for sorted ()

favorite_languages = {
   'kevin': 'Java',
   'jeny': 'Python',
   'sarah': 'c',
   'wilson': 'c++',
}

for name in sorted(favorite_languages.keys()):
   print(name.title()) 

Export

Jeny
Kevin
Sarah
Wilson

All values ​​values ​​6.4.3 traversing dictionary ()

favorite_languages = {
    'kevin': 'java',
    'jeny': 'python',
    'sarah': 'c',
    'wilson': 'c',
}

for language in favorite_languages.values(): # value可能重复
    print(language.title())

print("\nUsing set to remove duplicate values")
# 用set去重
for language in set(favorite_languages.values()): 
    print(language.title())

Usage 6.5 set {}

Similar dict and set, a set key is set, but not stored value. Since the key can not be repeated, so that, in the set, no duplicate key.

No repetition is set unordered collection of elements

To create a set, you need to provide a list as a set of inputs:

set by add () and remove () methods deletions element

# set用法
arr = [1, 2, 2, 3, 3]
print(set(arr))  # 输出 {1, 2, 3}
b = set([1, 2, 2])
print(b)  # 输出 {1, 2}

b.add(7)
print(b)  # 输出 {1, 2, 7}
b.remove(7)
print(b)  # 输出 {1, 2}

Into the set list method

b = set([1, 2, 2])
print(b)  # 输出 {1, 2}
tt = list(b)
print(tt)  # 输出 [1, 2]

6.6 Nesting

Sometimes we need a series of dictionaries stored in the list, or the list as the value stored in the dictionary, these have become nesting

Dictionary contains a variety of information such as alien_0 an alien, but not at the same time the information is stored aliens. At this point we can create a list of aliens

# 创建一个用于存储外星人的空列表
aliens = []

# 创建30个绿色的外星人
for alien_number in range(30):
    new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
    aliens.append(new_alien)

for alien in aliens[0:3]:
    if (alien['color'] == 'green'):
        alien['color'] = 'red'
        alien['points'] = 15
        alien['speed'] = 'fast'

for alien in aliens[0:5]:
    print(alien)

print("...")

Export

{'color': 'red', 'points': 15, 'speed': 'fast'}
{'color': 'red', 'points': 15, 'speed': 'fast'}
{'color': 'red', 'points': 15, 'speed': 'fast'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
{'color': 'green', 'points': 5, 'speed': 'slow'}
...

We often need to list the list contains a large number of dictionaries, such as when doing the site, you need to create a dictionary for each user, and these are stored in a dictionary of named users


Chapter VII user input and while loops

7.1 input () function to get the string input

Function input () let the program pauses, waiting for the user to enter some text. After obtaining user input, Python will store it in a variable, in order to facilitate your use

Input () function takes one parameter: the user in order to display prompts or instructions
corresponding to built a line print () but does not wrap

prompt = "If you tell us who you are, we can personalize the messages you see."
prompt += "\nWhat is your first name? "

name = input(prompt)
print("\nHello, " + name.title() + "!")

Export

If you tell us who you are, we can personalize the messages you see.
What is your first name? wilson79

Hello, Wilson79!

Note: If you are using Python2.7, please use raw_input () rather than input () to get input

7.2 function int () string to numeric

Input () function will be interpreted as a user input character string
function int () numeric string to the value

age = input("How old are you? ")
age = int(age) # '22' to 22

Function float () the string to floating point number

time = '2.3'
time = float(time)

7.3 while loop

Programs you use every day is likely to contain a while loop, such as games use a while loop to ensure that the players want to play continuously running at the time, and stop running when the player want to quit; terminal press control + c terminates the run

Example: let the user choose when to quit

# while循环
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "

message = ""
while message != 'quit':
    message = input(prompt)
    if (message != 'quit'):
        print(message)

7.3.1 use the logo

In the game, a variety of events may lead to the end of the game, as players do not have a ship or to protect the city were destroyed.
In the program requires a lot of conditions are met before continuing to run, you can define a variable to determine whether the entire program is active. This variable become the symbol
used to represent True or False status changes

7.3.2 break和continue

Usage is similar to C ++ and

while loop to ensure that there is at least one such program in place to make or break the loop condition is False

When the contents of the output to the sublime text out.txt, if the cycle is dead, it will cause the current txt will be very large, taking up a lot of memory, so to promptly terminate the program

7.3.3 user input filled dictionary

Create a survey, prompted to enter the name of the respondent's answer and wherein each execution cycle

# 使用用户输入来填充字典
responses = {}

# 设置一个标志,判断调查是否继续
polling_active = True

while polling_active:
    name = input("\nWhat is your name? ")
    response = input("Which mountain would you like to climb someday? ")

    # 将答案存到字典中
    responses[name] = response

    # 看看是否还有人要接受调查
    repeat = input("Would you like to let another person respond? (yes / no) ")
    if (repeat == 'no'):
        break

print("\n--- Poll Results ---")
for name, response in responses.items():
    print(name.title() + " would like to climb " + response.title() + ".")

Export


What is your name? Eric
Which mountain would you like to climb someday? Denali
Would you like to let another person respond? (yes / no) yes

What is your name? Lynn
Which mountain would you like to climb someday? evil's thumbd
Would you like to let another person respond? (yes / no) no

--- Poll Results ---
Eric would like to climb Denali.
Lynn would like to climb Evil'S Thumbd.


Written in the last : my blog mainly on the field of computer science summarized knowledge of thinking, and review, to write each blog it is easy to understand my goal, sharing technology and knowledge is a pleasure , and I welcome everyone together with the exchange of learning, there can be no question in the comments area, but also look forward to in-depth exchanges with your (^ ∀ ^ ●)

Published 232 original articles · won praise 80 · views 90000 +

Guess you like

Origin blog.csdn.net/qq_43827595/article/details/104293771