1. Python conditional judgment: if and Else
Arithmetic operators can be used in conditional judgments
equals: = =
Not equal to:! =
Greater than:>
Less than:<
Greater than or equal to: >=
Less than equals: <=
Example 1:
Username=input (' Please enter user name: ')
Passwd=input (' Please enter password: ')
If username = = ' mpp ' and passwd = = ' 123 ':
Print (' Login successful ')
Else
Print (' User name or password error ')
Example 2:if can be nested if, or you can use Elif
Score=int (Input (' Please enter exam results: '))
If score < 60:
Print (' fail ')
If score < 30:
Print (' Little idiot ')
Else
Print (' to work ')
Elif score >= and score < 80:
Print (' good ')
Else
Print (' excellent ')
2.while Cycle
The loop is repeating to do one thing
Need to set a cycle end condition
With a while loop, you have to have a counter
Continue end this cycle and proceed to the next cycle
Break End Loop
Example 1:
Count = 0# must be added to the counter
While Count < 5:
Print (' HHH ')
Count=count+1
else: #循环正常结束之后执行的
Print (' End of Loop ')
Use of the example 2:break
The result of the execution in the picture is output only once, because break ends the loop
3.for Loop: Guess the number game
Import Random
Random_num=random.randint (1,100)
For I in range (3):
Num=int (Input (' Please enter a number: '))
If num > Random_num:
Print (' You guessed the number is too big ')
Elif Num < random_num:
Print (' You guessed the number is too small ')
Else
Print (' Congratulations, guess right ')
Break
Else
Print (' Three chance ran out, no guess right ')
4. String formatting
Example 1: Stitching two strings with a plus sign
Username = input (' Please enter your name: ')
Time = ' 12:00 '
Print (username+ ' Welcome, Time is: ' +time ')
Example 2: by% placeholder,%s string%d int%.2fload
Username = input (' Please enter your name: ')
Time = ' 12:00 '
Print ('%s, welcome, time is:%s '% (username,time))
Example 3:.format (username,time)
Username = input (' Please enter your name: ')
Time = ' 12:00 '
Print (' {}, welcome, time: {} '. Format (username,time))
Example 4:.format (name=username,date=time)
Username = input (' Please enter your name: ')
Time = ' 12:00 '
Print (' {name}, welcome, time: {date} '. Format (name=username,date=time))
Conditional judgment, looping, and string formatting for Python