current position:Home>【Python】2. Logic control statement, list, tuple, dictionary

【Python】2. Logic control statement, list, tuple, dictionary

2022-02-02 06:21:10 Love nuggets, love learning

Terminal input information

How to open the terminal

windows key +R Key on run , Input cmd, Click ok

grammar

name = input(" Please enter the employee's name :")        #  Input in terminal   Dragons 
print(name)                          #  Dragons 
print(type(name))                    # <class 'str'>

age = input(" Please enter the employee's age :")         #  Input in terminal  96 year 
print(age)                           # 96 year 
print(type(age))                     # <class 'str'>

 Copy code 

The mutual conversion of strings and numbers

All input information is a string , String cannot be added or subtracted , It can be converted into numbers before operation

# String to number  int( character string )
age = input(" Please enter the employee's age :")             #  Input in terminal  25
print(int(age)*2)                        # 50
print(age*2)                             # 2525
print(type(int(age)))                    # <class 'int'>

# Number to string  str( Numbers )
name = input(" Please enter the employee's name :")            #  Input in terminal   Dragons 
age=12                                   
print(type(age))                          # <class 'int'>
# print(name+" My age is "+12) #  Will report a mistake 
print(type(str(12)))                      # <class 'str'>
print(name+" My age is "+str(12))              #  Bruce Lee's age is 12

 Copy code 

Print print

# Format output 
name = input(" Please enter your name :")               #  The input terminal   Dragons 
sex = input(" Please enter your gender :")                #  The input terminal   male 
age = int(input(" Please enter your age :"))           #  The input terminal  25
print(name+", Welcome to login !")                    #  Dragons , Welcome to login !
print("%s, Welcome to login !"%(name))                #  Dragons , Welcome to login !

#  Dragons , Gender : male , Welcome to login 
print("%s, Gender :%s, Welcome to login "%(name,sex))       #  Dragons , Gender : male , Welcome to login 

#  Dragons , Gender : male , Age :25, Welcome to login 
print("%s, Gender :%s, Age :%d, Welcome to login "%(name,sex,age))    #  Dragons , Gender : male , Age :25, Welcome to login 

pi = 3.1415926
print(pi)                # 3.1415926
#  Format decimal , The total display space is 10 position , Keep one place after the decimal point , Align right 
print("%10.1f by pi Value "%(pi))                  # 3.1 by pi Value 

#  Format decimal , The total display space is 10 position , Keep one place after the decimal point , Align right , There is no display of numbers on the left 0
print("%010.1f by pi Value "%(pi))                  # 00000003.1 by pi Value 

#  Format decimal , The total display space is 10 position , Keep one place after the decimal point , Align left 
print("%-10.1f by pi Value "%(pi))                  # 3.1  by pi Value 

#  Format decimal , The total display space is 10 position , Keep one place after the decimal point , Align right , Show the sign 
print("%+10.1f by pi Value "%(pi))                  # +3.1 by pi Value 
# format  function 
a = " Zhang San tells Li Si :{},{}".format(" It's a lovely day ",90)

 Copy code 

Judgment statement

if Is to judge what conditions are met , Execute what code , It's like we're at a fork in the road , Which destination are we going to , We will choose which way to go .if The statement will only go to a judgment in it at most , It doesn't take many branches

if  Boolean expression :
     If this condition is met, execute the code 
elif  Boolean expression :
       The above conditions do not meet , Meet this condition , Execute code 
elif  Boolean expression :
       The above conditions do not meet , Meet this condition , Execute code 
else:
       None of the above conditions meet , Execute code 

 Copy code 

Single conditional judgment

# elif  and  else  Omission 
a = 9
if a == 9:                     #  Judge  a  Is it equal to 9
    print(a)                   #  If  a  be equal to  9, Then print  a; If not , execute elif sentence 
elif a >9:                     #  Judge  a  Is it greater than 9
    print(a)                   #  If  a  Greater than  9 , Then print  a; If not , execute else sentence 
else:
    print("a<9")               #  None of the above conditions meet , Print directly  a < 9
#  Here's the last print  9 
 Copy code 

Multi condition judgment

also and

# a=9 or b=9
if a == 9 or b == 9:
    print(a)
    print(b)
elif a >9:
    print(a)
else:
    print("a<9")
 Copy code 

or or

# a=9 or b=9
if a == 9 or b == 9:
    print(a)
    print(b)
elif a >9:
    print(a)
else:
    print("a<9")
 Copy code 

practice :

The mileage charge
<= 3 km 20 element / Every kilometer
>3 km And <= 5 km 15 element / Every kilometer
>5 km And <= 8 km 12 element / Every kilometer
>8 km 10 element / Every kilometer
#  Get any mileage from the terminal , Get the current mileage unit price 
a = input(" Please enter mileage :")
price = 0  #  Initially set to 0
if int(a) <= 3:
    price = 20
elif int(a) <= 5:  #elif: else if abbreviation 
    price = 15
elif int(a) <= 8:
    price = 12
else:   #  None of the above conditions are met , Will come to this condition to judge 
    price = 10

print("{} The unit price per kilometer is :{}".format(a,price))

 Copy code 
#  Enter a mileage from the terminal , Then find the total price of a taxi 
a = input(" Please enter mileage :")
if a.isalpha():
    print(" Incorrect input ")
else:
    a = eval(a)
    print(type(a))
    sum = 0
    if isinstance(a, float) or isinstance(a, int):
        if 0 < a <= 3:
            sum = 20 * a
        elif a <= 5:
            sum = 20 * 3 + (a - 3) * 15
        elif a <= 8:
            sum = 20 * 3 + 15 * 2 + (a - 5) * 12
        else:
            sum = 20 * 3 + 15 * 2 + 12 * 3 + (a - 8) * 10

        print("{} The total price of mileage is :{}".format(a, sum))

 Copy code 
The mileage Total time charge
<= 3 km <= 1 Hours 20 element / Every kilometer
> 1 Hours 22 element / Every kilometer
>3 km <= 1 Hours 15 element / Every kilometer
> 1 Hours 18 element / Every kilometer
#  Input a mileage and driving time from the terminal , Then find the total price of a taxi 

# 1.  Get kilometers and total duration 
route = float(input(" Please enter the number of kilometers :"))
hour = float(input(" Please enter the duration :"))

#  Initialize the total price 
sum = 0

# 2.  Judge 
# 2.1  Kilometers less than or equal to 3, The duration is less than or equal to 1
if route<=3 and hour<=1:
    sum = 20*route
# 2.2  Kilometers less than or equal to 3, The time is longer than 1
elif route <= 3 and hour > 1:
    sum = 22*route
# 2.3  The number of kilometers is greater than 3, The duration is less than or equal to 1
elif route > 3 and hour <= 1:
    sum = 20*3 + (route-3)*15
# 2.4  The number of kilometers is greater than 3, The time is longer than 1
else:
    sum = 22*3 + (route-3)*18
print("{} kilometers ,{} Hours , The total price of the fare is {}".format(route,hour,sum))

 Copy code 

Loop statement

Circular statements are very common in life , Like traffic lights , Has been changing colors in a cycle ; The ordering system is also a circular mechanism , Each time you enter the number of diners, you can print the dining voucher .

while loop

''' while  Boolean expression :  Statement in loop ( General loops have exit conditions , Some scenarios have no exit conditions , Like traffic lights ) '''
# Loop printing from 1 To 10
i = 1 #  give i Initial value 1
while i < 11:    	# i < 11 Will enter the cycle 
    print(i)     	#  Print variables i
    # i = i + 1  hold i+1 The value of is assigned to i
    i += 1  	 	#  Equivalent to  i = i + 1 

 Copy code 

for loop

for i in range(10):
     Execute the code inside 
 Copy code 
for i in range(10):  #  Cycle from 0 To 9, It doesn't contain 10
    print(i)

a = "hello world"       #a[2:10]
for i in range(2,10):   #  Cycle from 2 To 9, It doesn't contain 10
    print(i)

for i in range(2,10,2):   #  Cycle from 2 To 9, In steps of 2
    print(i)

a = [1,2,3,4,5,12,3,12]  # a[0]  List length len(a)
b = len(a)
for i in range(b):
    print(a[i]) 

 Copy code 

Use them separately while Circulation and for loop :

Find the factorial , Input any positive integer from the terminal , Find the corresponding factorial , Such as input 4, Factorial 4 * 3 * 2 * 1

 Use while Cycle to achieve 
# 1.  Get a positive integer from the terminal 
n = int(input(" Please enter a positive integer :"))
# 2.  The result of initializing factorials  sum = 1
sum = 1
# 3.  loop 
#  Initialize a loop variable i
i = 1
while i<=n:
    sum *= i #  Equivalent to sum = sum*i
    i += 1
print("{} The factorial of is {}".format(n,sum))


 Use for Cycle to achieve 
# 1.  Get a positive integer from the terminal 
n = int(input(" Please enter a positive integer :"))
# 2. for loop   Such as input 5,for A cycle is a cycle 5 Time , from 1 To 5
#  Initialize factorial result 
sum = 1
for i in range(1,n+1):
    sum *= i
print("{} The factorial of is :{}".format(n,sum))

 Copy code 

break

Execute in a loop break, Means to exit the whole cycle

while True:
    command = input(" Please enter a command :")
    if command == 'exit':
        break
    print(" The command entered is :{}".format(command))

print(' Program end ')

 When a loop is nested in a loop ,break: Exit loop , You can only jump out of the nearest loop 
while True:
    print(" Layer 1 cycle ")
    while True:
        n = input(" The second cycle , Please enter a command :")
        if n == "exit":
            break

 Copy code 

continue

Exit the current cycle , When the statement after a loop does not execute

while True:
    command = input(" Please enter a command :")
    if command == 'exit':
        break
    if command == 'cont':
        continue
    print(" The command entered is :{}".format(command))

print(' Program end ')


continue:  Exit the current cycle , So let's go to the next loop 
for i in range(10):
    if i == 3:          #  When  i = 3 when , Exit this cycle , Do not print out 3, So let's go to the next loop , perform i = 4, Print 
        continue
    print(i)
 Copy code 

practice

 Define a cycle 
 First step : Get input from the terminal n
 The second step :  Judge n == "exit",  If it is , Then exit the loop 
 The third step :  Judge n == "cont",  If it is , Exit the current loop , Enter next cycle 
 Step four :  Print " The command you entered is :"


while True:
    n = input(" Please enter the command :")       #  Get terminal input 
    if n == "exit":              #  Judge whether the input instruction is "exit", If it is , Just go inside the code 
        break                  #  Exit the whole cycle 
    elif n == "cont":
        continue              # continue:  Exit the current loop , Enter next cycle 
        print("continue")   # continue Some of the following code will not execute 
    else:
        print(" The command you entered is :{}".format(n))
    print("111111")

 Copy code 

list

1、 Can be modified at will 
2、 Use [] or list() To create , Elements are separated by commas 
3、 The elements in the list can be of different types , There is no length limit 
 Copy code 
Method function remarks
The list goes up name.append(a) append function , Add... To the last element
name.insert( Subscript ,a) insert function , To enter the subscript position , Add new elements according to the subscript position . No subscript position will report an error
name.extend( list ) extend function , First, take the two lists apart , Put the elements of the two lists together
Change the list to name[ Subscript ]=" New name "
Check the list if temp in name: if temp not in name:
List deletion del name[ Subscript ] del , Delete elements according to index
name.pop() pop function , According to index To delete the elements in the list (pop It's not in it index, Delete the last... By default )
name.remove(" value ") remove function , The input values , According to this value , To remove the first value in the list
Sort the list name.sort() sort function , Sort from small to large
name.sort(reverse=True) Sort from large to small

Tuples

1、 Tuples cannot be modified once they are created 
2、 Use () perhaps tuple() To create , The elements are separated by commas 
3、 Brackets can be used or not , But it must be separated by commas 
 Copy code 

Several forms of tuples :

a = (1,) # There's only one element , You have to add a comma 
a = 1, # Brackets can be removed 
a = 1, 2, 3.14, 'hello'
 Copy code 

Dictionaries

1、 Is a set of key value pairs , There is no order between key value pairs and cannot be repeated 
2、 Use braces {} perhaps dict() establish , Keys and values are linked by colons , Multiple key value pairs are separated by commas . Format :{ key : value , key : value ...}
3、 According to   key   Indexes   Value content , There is no length limit 
 characteristic : The key is the only , It's impossible for two elements to have the same key 
 Copy code 

newly added / Modify dictionary elements

info = {"name" : "hxx", "age" : "18"}
#  When this is not in the dictionary key when , Add for 
info["sex"] = " male "          
print(info)         # {'name': 'hxx', 'age': '18', 'sex': ' male '}
#  When there's this in the dictionary key when , To modify 
info["age"] = "25"          
print(info)         # {'name': 'hxx', 'age': '25', 'sex': ' male '}
 Copy code 

Delete dictionary elements

info = {'name': 'hxx', 'age': '25', 'sex': ' male '}
#  Dictionaries ,pop、del function , Need to enter key, To delete key value pairs .  If you delete key If it doesn't exist, it will report an error 
info.pop("age")             
print(info)             # {'name': 'hxx', 'sex': ' male '}
del info["sex"]
print(info)             # {'name': 'hxx'}
 Copy code 

Empty dictionary

info = {'name': 'hxx'}
info.clear()
print(info)            # {}
 Copy code 

Merge dictionaries

dic = {"name" : "hss", "age" : "24"}
new = {"hobby" : "basketball"}
dic.update(new)
print(dic)              # {'name': 'hss', 'age': '24', 'hobby': 'basketball'}
 Copy code 

Get the number of dictionaries

dic = {'name': 'hss', 'age': '24', 'hobby': 'basketball'}
#  Dictionaries ,len function , Get the number of dictionaries 
print(len(dic))            # 3
 Copy code 

items,keys,values function

dic = {"name" : "hss", "age" : "24", "sex" : " male "}
#  Dictionaries ,items function ,  Get all the key value pairs in the dictionary .  Join all the key value pairs in the dictionary with tuples , Put it on the list .
print(dic.items())     # dict_items([('name', 'hss'), ('age', '24'), ('sex', ' male ')])

#  Dictionaries ,keys function ,  Get all the... In the dictionary key
print(dic.keys())      # (['name', 'age', 'sex'])

#  Dictionaries ,values function ,  Get all the values in the dictionary 
print(dic.values())    # dict_values(['hss', '24', ' male '])
 Copy code 

Traverse dictionary elements

dic = {"name" : "hss", "age" : "24", "sex" : " male "}

for key,val in dic.items():
    print("key by {},value by {}".format(key,val))
# key by name,value by hss
# key by age,value by 24
# key by sex,value For male 

#  Traverse the... In the query dictionary keys
for key in dic.keys():
    print(key)
# name
# age
# sex
#  Traverse the... In the query dictionary values
for val in dic.values():
    print(val)
# hss
# 24
#  male 

 Copy code 

copyright notice
author[Love nuggets, love learning],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202020621070683.html

Random recommended