#Define a variable just to use its value later
#Programming is all dealing with memory
name='Zhang San'
print(name)
#If there are single quotes in the variable, double quotes should be used, for example: name="let's go"
#If there are double quotation marks in the variable, single quotation marks should be used, for example: name='Zhang San looks "very handsome"!'
#If there are single quotes and double quotes in the variable, use triple quotes, for example: content = "'let's go,"lucy" '''
age = 10 #int type
name = 'Xiaobai' #string type string
score = 53.36 float, float
Built-in function: type #View variable type
print(type(age))
1. Conditional judgment if else
For example: determine age
age = input( ' Please enter your age: ' ) # The input value accepted by input is of string type age = int(age) # Type coercion, converted to Int type if age<18: print ( ' Minor ' ) else: print ( ' Adult ' )
For example: Judgment of excellent, good, pass
score = input( ' Please enter your score: ' ) score = int(score) if score >=90: print ( ' excellent ' ) elif score >=75 and score<90: print ( ' good ' ) elif score >=60 and score<75: print ( ' pass ' ) else: print ( ' Failed ' )
practise:
#generates a number 10
#Enter a number, if the input is small, the prompt is small; if the input is large, it will prompt him that the input is large
import random num = random.randint (1,10 ) for i in rang(5): #Guess 5 times new_num = input( ' Please enter the number you want: ' ) new_num = int(new_num) if new_num>num: print ( ' input is too large ' ) elif new_num <num: print ( ' input is too small ' ) else: print ( ' Congratulations on guessing correctly ' )
2. Loop (or iteration, traversal)
#for
#while must have a counter
#do one thing repeatedly
Example: while loop
count = 0 #define the counter
while count<10:
print('Hello world')
count = count + 1 #There must be a counter, and the counter must be increased, otherwise it will be an infinite loop
#loop body, when the loop is repeated, the things in the loop body are executed repeatedly
Circular exercise:
#7 Chances to Guess the Number
import random num = random.randint (1,100 ) count = 0 while count < 7: guess = input( ' Please enter the number you want to guess: ' ) guess = int(guess) if guess<num: print ( ' big guess ' ) elif guess > num: print ( ' Guess is too small ' ) else : print ( ' Congratulations, you guessed it right ' ) break #Guess it right, exit the loop count = count + 1
#loop body: when looping, the things in the loop body are repeatedly executed
#break When a break is encountered in the loop, the loop ends immediately, but whether the loop is finished
#continue If you encounter continue in the loop, then end the loop and continue to the next loop
while:....
else: the operation to be done after the normal end of the loop
for loop:
for i in range(4): # Loop 4 times, the for loop automatically adds 1 loop, no counter is needed, the default starts from 0
print (i) #0,1,2,3
print(‘hello’)