Python basics,
1. Output statement
1 # directly output 2 print ('xxx ') 3 # define variable 4 name = 'afant' 5 age = 17 6 # format output 7 # method 1 8 print ('name = ', name, 'Age =', age) 9 # method 210 print ('name = % s, age = % s' % (name, age) 11 # Method 312 print ('name = {name }, age = {age }'. format (name = name, age = age ))2. Notes
1 # single line comment 2 ''' 3 multiple lines comment 4 multiple lines comment 5 multiple lines comment 6 '''
3. type, type conversion
1 # view variable type 2 print (type (1) 3 print (type (name) 4 print (type (True )) 5 # type conversion 6 print (str (123) # convert to string 7 print (int ('123') # convert to int
Int float bool str4. user input
1 # user input, formatted output 2 name = input ('enter name: ') 3 age = int (input ('enter age :')) 4 address = input ('enter address: ') 5 info = ''' User: {name} 6 name: {name} 7 age: {age} 8 address: {address} 9 '''. format (name = name, age = age, address = address) 10 info2 = ''' User: % s11 name: % s12 age: % s13 address: % s14 ''' % (name, name, age, address) 15 print (info) 16 print (info2)5. Format
Name = 'xxx' age = 111 salary = 8888.2222 print ('name = % s, age = % d, sclary = %. 2f '% (name, age, salary) ''' %. 2f take two decimal places % d integer % s string (any value )'''6. if... else
age = int(input("age:"))if age == 18: print('age:18')elif age == 16: print('age:16')else: print("age:%s" % (age))7....
# If the for statement is not terminated by break, elsefor I in range (10): print (I) else: print ('...') will be executed after the for statement is executed ('...')8. while ....
I = 0 # When while is interrupted, else code will not be executed fast while True: I = I + 1 print (I) if I = 1000: breakelse: print ("end ") # When the while condition is not satisfied, execute elsewhile I <0: I = I-1 else: print ('while condition termination ')