Expression If ... else
First, user login verification
12345678910111213141516171819202122 |
# 提示输入用户名和密码
# 验证用户名和密码
# 如果错误,则输出用户名或密码错误
# 如果成功,则输出 欢迎,XXX!
#!/usr/bin/env python
# -*- coding: encoding -*-
_username = ' Qian '_password = ' zxc123 'username = input ("username:")password = input ("Password:")if _username = = Username and _password = = Password:print ("Welcome user {name} login ...". Format (name=username))Else:print ("Invalid username or password!") |
Second, guess the age game
Set your age in the program, and then start the program to let the user guess, after the user input, according to his input prompts the user to enter the correct, if the error, the hint is guessed big or small,
12345678910111213 |
#!/usr/bin/ Env python #-*-coding:utf-8-*- my_age = +   guess_age = Int (input ("Guess Age:")) if guess_age = my_age: print ("Yes, you got it.") elif guess_age > My_age: print ("think smaller ...") else: print ("Think bigger!")   |
Second, while loop
There's a cycle called a dead loop.
12345 |
count = 0 while True : print ( "死循环" ,count) count + = 1 |
The above guess age with while loop to achieve: guess only 3 times
12345678910111213141516 |
#!/usr/bin/env python # -*- coding: utf-8 -*- Count = 0 My_Age =While count < 3:guess_age = Int (input ("Guess Age:"))if Guess_age = = My_age:print ("Yes, you got it.") Breakelif guess_age > My_age:print ("Think smaller ...")Else:print ("Think bigger!")Count +=1Else:print ("You have tried too many times. Fuck off ") |
Third, expression for loop
The simplest loop 5 times
123456 |
#_*_coding:utf-8_*_ __author__ = ‘Many Qian‘ for i in range ( 5 ): print ( "loop:" , i ) |
Output:
12345 |
loop: 0 loop: 1 loop: 2 loop: 3 loop: 4 |
Requirements one: or the above program, but encountered less than 5 cycle times will not go, jump directly into the next cycle
1234 |
for i in Range ( 10 ): if i< 5 : continue #不往下走了, go directly to the next loop print ( "loop:" |
Requirements Two: or the above program, but encountered more than 5 cycles will not go, direct exit
1234 |
for i in Range ( 10 ): if I> 5 : break #不往下走了, jump right out of the loop print ( "loop:" |
Use the For loop you learned above to guess age:
123456789101112131415 |
#!/usr/bin/env python
# -*- coding: utf-8 -*- My_Age =For I in range (3):guess_age = Int (input ("Guess Age:"))if Guess_age = = My_age:print ("Yes, you got it.") Breakelif guess_age > My_age:print ("Think smaller ...")Else:print ("Think bigger!")Else:print ("You have tried too many times. Fuck off ") |
Little white Python road day1 expression if ... else, while loop, for loop