Terminal input information
How to Open a Terminal
Windows key +R key to run, enter CMD, and click OK
grammar
name = input("Please enter employee name:") # Enter dragon in terminal
print(name) # small dragon
print(type(name)) # <class 'str'>
age = input("Please enter employee age:") Enter 96 years in terminal
print(age) # 96,
print(type(age)) # <class 'str'>
Copy the code
Conversion of a string to a number
All input information is a string. Strings cannot be added or subtracted, but can be converted to numbers before operation
# string to number int(string)
age = input("Please enter employee age:") Enter 25 in terminal
print(int(age)*2) # 50
print(age*2) # 2525
print(type(int(age))) # <class 'int'>
# number to string STR (number)
name = input("Please enter employee name:") # Enter dragon in terminal
age=12
print(type(age)) # <class 'int'>
# print(name+" age +12) # print(name+" age +12
print(type(str(12))) # <class 'str'>
print(name+"The age of"+str(12)) # Xiao Long's age is 12
Copy the code
Print the print
# format output
name = input("Please enter your name:") # Terminal input dragon
sex = input("Please enter your gender:") # Terminal input male
age = int(input(Please enter your age:)) Enter 25
print(name+", welcome to login!) # Xiaolong, welcome to login!
print("%s, welcome to login!"%(name)) # Xiaolong, welcome to login!
# Xiaolong, gender: male, welcome to login
print("%s, gender: %s, welcome to login"%(name,sex)) # Xiaolong, gender: male, welcome to login
# Xiaolong, gender: male, age: 25, welcome to login
print("%s, Gender: %s, age: %d, welcome to login"%(name,sex,age)) # Xiaolong, gender: male, age: 25, welcome to login
pi = 3.1415926
print(pi) # 3.1415926
Format decimals to show that the total space is 10 places, with one place left after the decimal point, aligned to the right
print("%10.1f is the value of PI"%(pi)) # 3.1 is the value of PI
# format the decimal, display the total space of 10 digits, save one decimal point after the decimal point, aligned to the right, the left without a number of 0
print("%010.1f is the value of PI"%(pi)) # 00000003.1 is the value of PI
Format decimals to show that the total space is 10 digits, leaving one decimal point behind, aligned to the left
print("%-10.1f is the value of PI"%(pi)) # 3.1 is the value of PI
Format the decimal, showing the total space is 10 digits, reserving one decimal place after the decimal point, aligned to the right, showing the positive and negative sign
print("%+10.1f is the value of PI"%(pi)) # +3.1 is the value of PI
# format function
a = "Zhang SAN said to Li Si: {}, {}".format("It's a fine day today.".90)
Copy the code
statement
If is to determine what conditions are met and what code is to be executed, just like we are at a fork in the road, we want to go to which destination, then we will choose which road. The if statement will only go to one of these judgments, not multiple branches
ifBoolean expression: Executes code that meets this conditionelifBoolean expression: if the above condition is not met, execute the code if the condition is metelifBoolean expression: if the above condition is not met, execute the code if the condition is metelse: If none of the above conditions are met, execute the codeCopy the code
Single conditional judgment
# elif and else can be omitted
a = 9
if a == 9: # Check whether a is equal to 9
print(a) # if a = 9, print a; If not, the elif statement is executed
elif a >9: Check whether a is greater than 9
print(a) If a is greater than 9, print a; If not, the else statement is executed
else:
print("a<9") A < 9
# print 9 last
Copy the code
Multiple conditional judgment
And the and
# = 9 a or b = 9
if a == 9 or b == 9:
print(a)
print(b)
elif a >9:
print(a)
else:
print("a<9")
Copy the code
Or the or
# = 9 a or b = 9
if a == 9 or b == 9:
print(a)
print(b)
elif a >9:
print(a)
else:
print("a<9")
Copy the code
Practice:
The mileage | charge |
---|---|
The < = 3 kilometers | 20 yuan/km |
>3 km and <= 5 km | 15 yuan/km |
>5 km and <= 8 km | 12 yuan/km |
> 8 km | 10 yuan/km |
Get any mileage from the terminal, get the current mileage unit price
a = input("Please enter mileage:")
price = 0 Set the initial value 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: # If all the above conditions are not met, this condition will be judged
price = 10
print("The unit price for {} km is: {}".format(a,price))
Copy the code
Enter a mileage from the terminal and figure out the total fare for the taxi
a = input("Please enter mileage:")
if a.isalpha():
print("Input error")
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 for {} miles is: {}".format(a, sum))
Copy the code
The mileage | The total time | charge |
---|---|---|
The < = 3 kilometers | < = 1 hour | 20 yuan/km |
> 1 hour | 22 yuan/km | |
> 3 km | < = 1 hour | 15 yuan/km |
> 1 hour | 18 yuan/km |
Enter a mileage and the time spent driving from the terminal, then calculate the total fare of the taxi
# 1. Get the mileage and total time
route = float(input("Please enter the mileage:"))
hour = float(input("Please enter duration:"))
Initialize the total price
sum = 0
# 2. The judgment
The mileage is less than or equal to 3, and the length is less than or equal to 1
if route<=3 and hour<=1:
sum = 20*route
The mileage is less than or equal to 3, and the duration is greater than 1
elif route <= 3 and hour > 1:
sum = 22*route
The number of kilometers is greater than 3 and the length is less than or equal to 1
elif route > 3 and hour <= 1:
sum = 20*3 + (route-3) *15
The number of kilometers is greater than 3 and the length is greater than 1
else:
sum = 22*3 + (route-3) *18
print("{} km journey, {} hours, the total fare is {}".format(route,hour,sum))
Copy the code
Looping statements
Circular statements are very common in life, such as traffic lights, always changing color cycle; The ordering system is also a circular mechanism. Every time you input the number of diners, you can print the dining voucher.
The while loop
Boolean expression: a statement inside a loop (usually loops have exit conditions, but some scenarios do not, such as traffic lights).
# Cycle print from 1 to 10
i = 1 # give I an initial value of 1
while i < 11: # I < 11 will enter the loop
print(i) # print variable I
# I = I +1 Assign the value of I +1 to I
i += 1 # is the same thing as I = I + 1
Copy the code
The for loop
For I in range(10): Execute the code insideCopy the code
for i in range(10) :# loop from 0 to 9, not including 10
print(i)
a = "hello world" #a[2:10]
for i in range(2.10) :# loop from 2 to 9, not including 10
print(i)
for i in range(2.10.2) :# loop from 2 to 9, step size 2
print(i)
a = [1.2.3.4.5.12.3.12] List length len(a)
b = len(a)
for i in range(b):
print(a[i])
Copy the code
Use while loops and for loops respectively:
Find the factorial. Input any positive integer from the terminal and find the corresponding factorial. For example, input 4, factorial 4 * 3 * 2 * 1
usewhileCycle to achieve# 1. Get a positive integer from the terminal
n = int(input("Please enter a positive integer:"))
# 2. Sum = 1
sum = 1
# 3. The cycle
Initialize a loop variable I
i = 1
while i<=n:
sum *= i # is equivalent to sum = sum* I
i += 1
print("The factorial of {} is {}".format(n,sum)) usingforCycle to achieve# 1. Get a positive integer from the terminal
n = int(input("Please enter a positive integer:"))
For example, if you type 5, the for loop loops five times, from 1 to 5
Initialize the factorial result
sum = 1
for i in range(1,n+1) :sum *= i
print("The factorial of {} is {}".format(n,sum))
Copy the code
break
Execute break inside the loop to exit the entire loop
while True:
command = input("Please enter command :")
if command == 'exit':
break
print("Enter the command :{}".format(command))
print('End of program') When loops are nested within loops,break: Exits the loop, only the nearest loopwhile True:
print("First cycle")
while True:
n = input("For layer 2 loop, type command:")
if n == "exit":
break
Copy the code
continue
Exit the loop when the statement following the loop is not executed
while True:
command = input("Please enter command :")
if command == 'exit':
break
if command == 'cont':
continue
print("Enter the command :{}".format(command))
print('End of program')
continue: Exits the current loop and continues the next loopfor i in range(10) :if i == 3: # when I = 3, exit this loop, do not print 3, continue the next loop, execute I = 4, print
continue
print(i)
Copy the code
practice
Define a loop step 1: get input N from the terminal step 2: determine n =="exit", if so, exit the loop step 3: check n =="cont"If so, exit the current loop and enter the next loop step 4: print"Your input is:"
while True:
n = input("Please enter instructions:") Get terminal input
if n == "exit": # Determine if the input command is "exit", if so, go to the code inside
break # exit the loop
elif n == "cont":
continue # continue: Exits the current loop and enters the next loop
print("continue") Some code below # continue will not execute
else:
print("Your input is: {}".format(n))
print("111111")
Copy the code
The list of
Use [] or list(), separated by commas. 3. Each element in the list can be of a different type, and there is no length limitCopy the code
methods | function | note |
---|---|---|
List to add | name.append(a) | Append to the last element |
name.insert(subscript a) | Insert function, to enter the subscript position, according to the subscript position to add elements. An error is reported without subscript position | |
name.extend(list) | The extend function begins by separating two lists and concatenating their elements together | |
A list of changes | Name [subscript]= new name | |
Check the list | if temp in name: if temp not in name: | |
The list of deleted | Del name[subscript] | Del, deletes elements by index |
name.pop(a) | The pop function deletes the element in the list according to index. | |
name.remove(” value “) | The remove function, the input value, will use that value to remove the first value in the list | |
List ordering | name.sort(a) | Sort, sort from smallest to largest |
name.sort(reverse=True) | Sort from largest to smallest |
tuples
Tuples can be created using () or tuple(), separated by commas. 3. Parentheses can be used or not, but must be separated by commasCopy the code
Several forms of tuples:
a = (1.)There is only one element, must be a comma
a = 1.The # parentheses can be removed
a = 1.2.3.14.'hello'
Copy the code
The dictionary
2. Use braces {} or dict(). Keys and values are linked by colons, and multiple key-value pairs are separated by commas. Format: {key: value, key: value... } 3, can be based on the contents of the key index value, there is no length restriction feature: the key is unique, no two elements can have the same keyCopy the code
New/modify dictionary elements
info = {"name" : "hxx"."age" : "18"}
# if the key does not exist in the dictionary, the key is added
info["sex"] = "Male"
print(info) # {'name': 'HXX ', 'age': '18', 'sex':' male '}
# if there is a key in the dictionary, change it
info["age"] = "25"
print(info) # {'name': 'HXX ', 'age': '25', 'sex':' male '}
Copy the code
Delete dictionary elements
info = {'name': 'hxx'.'age': '25'.'sex': 'male'}
# dictionary, pop, del functions, need to enter the key, to delete the key pair. If the deleted key does not exist, an error message is displayed
info.pop("age")
print(info) # {'name': 'HXX ', 'sex':' male '}
del info["sex"]
print(info) # {'name': 'hxx'}
Copy the code
Empty dictionary
info = {'name': 'hxx'}
info.clear()
print(info) # {}
Copy the code
Merge the dictionary
dic = {"name" : "hss"."age" : "24"}
new = {"hobby" : "basketball"}
dic.update(new)
print(dic) # {'name': 'hss', 'age': '24', 'hobby': 'basketball'}
Copy the code
Get the number of dictionaries
dic = {'name': 'hss'.'age': '24'.'hobby': 'basketball'}
Len function to get the number of dictionaries
print(len(dic)) # 3
Copy the code
Items, keys, values functions
dic = {"name" : "hss"."age" : "24"."sex" : "Male"}
The items function retrieves all the key pairs in the dictionary. Use tuples to concatenate all the dictionary's key pairs into the list.
print(dic.items()) # dict_items ([(' name ', '(HSS), (' age', '24'), (' sex 'and' male ')])
The keys function retrieves all keys in the dictionary
print(dic.keys()) # (['name', 'age', 'sex'])
# dictionary, values function, get all the values in the dictionary
print(dic.values()) # dict_values([' HSS ', '24', 'male '])
Copy the code
Iterate over the dictionary element
dic = {"name" : "hss"."age" : "24"."sex" : "Male"}
for key,val in dic.items():
print("Key is {},value is {}".format(key,val))
# key = name,value = HSS
# key = age and value = 24
# key = sex,value = male
Select keys from dictionary
for key in dic.keys():
print(key)
# name
# age
# sex
Select values from the dictionary
for val in dic.values():
print(val)
# hss
# 24
# male
Copy the code
A collection of
1, 2, collection is the disorder of multiple elements combination set between elements is unordered, each element only, there is no the same elements (applied to the data to weight, that is, collection types all elements not repeat) 3, collection element cannot be changed, can't be a variable data type 4, to set up the collection types with {} or set (), separated by commas between elements Note: To create an empty collection type, you must use set()Copy the code
Merge collections or add lists, dictionaries, tuples
The collection is automatically de-duplicated and the collection is in no order
se = { 2.3."1".2.3.4}
print(se) # {2, 3, 4, '1'}
# Duplicate elements are removed when merged or added
se2 = {"hhh"."1"} # set
se.update(se2) Update function, can merge sets
print(se) # {2, 3, 4, '1', 'hhh'}
#
se3 = [9.0] # list
se.update(se3) Add a list to the collection
print(se) # {0, 2, 3, 4, '1', 'hhh', 9}
#
se4 = {"zidian" :"age"} # dictionary
se.update(se4) Add a dictionary to the set. Add a key to the set
print(se) # {0, 2, 3, 4, '1', 'hhh', 9, 'zidian'}
#
se5 = ("yuan".88) # tuples
se.update(se5) Add a tuple to the set
print(se) # {0, 2, 3, 4, '1', 9, 'yuan', 'hhh', 88, 'zidian'}
Copy the code
Delete an element from the collection
se = {0.2.3.4.'1'.9.'yuan'.'hhh'.88.'zidian'}
# set, remove function, input key, delete this key. If the key is not in the set, an error will be reported
se.remove(0)
print(se) # {2, 3, 4, 9, '1', 'zidian', 'hhh', 88, 'yuan'}
Discard function, enter key, delete this key. If the input key is not in the set, no error will be reported
se.discard(99)
print(se) # {2, 3, 4, 9, '1', 'zidian', 'hhh', 88, 'yuan'}
Copy the code
Traverse the collection
jihe = {"name"."age"."sex"}
for item in jihe:
print(item)
# name
# sex
# age
Copy the code
Set, list, tuple conversion
# Element decrement
l1 =[1.2.3.1.2.3] # list
s = set(l1) # list to collection
lis =list(s) # set list
print(lis) # [1, 2, 3]
t = (1.2.3.1.3) # tuples
se = set(t) # tuple to set
tu =tuple(s) # set tuples
print(tu) # (1, 2, 3)
#for loop deweight
a = [1.2.3.4.1.1.2.3]
kong =[]
for i in a:
if i in kong:
kong.pop(i)
else:
kong.append(i)
print(kong) # [1, 4, 2, 3]
Copy the code
Mutable and immutable types
Immutable types: strings, Numbers, the tuple tuple, these variables if the value changes, assign values to the other before the value of the variable will not change, because the values change address after the change Variable types: dictionary, collection, list, these variables if the value changes, assign values to the other before the value of a variable will change, because the point is the same addressCopy the code
# Numbers
a = 1
b = a
print(id(a)) # 140341948901680
print(id(b)) # 140341948901680
a = 2
print(id(a)) # 140341948901712
# dictionary
dic = {"name":"Zhang"}
dic1 = dic
print(id(dic)) # 140476032712512
print(id(dic1)) # 140476032712512
dic["hobbit"] = "Play"
print(id(dic)) # 140476032712512
Copy the code