Python-if,while, for循环
key points
if语句,及if语句套用
- if…else
1 | name=input() #显示输入框,name=输入内容 show the inputbox,name=input #input 函数 |
该代码可判断用户名及密码是否与设定值相符
check the user‘s name and password
- if…elif
1 | name=input() |
该代码通过判断年龄确定身份
check the user through age
while语句
1 | spam = 0 |
output:
1 | Hello world! |
‘break’ and ‘continue’
break:
When the break is executed, the loop ends.
1 | spam=0 |
continue:
When continue is executed, the loop starts again.
1 | spam=1 |
while+if
输入密码 input the password
1 | key=input() |
e.g.
1 | >1 |
another way:
1 | key=input() |
for循环
1 | for i in range(12,16): |
12到16的所有整数
print all integers in 12 to 16
1 | for i in range(0,10,2): #the 2 here means the step is 2 |
1 | for i in range(5,-1,-1): |
example
a tricky game:
You must input ‘your name’ instead of the real name:
你要输入 ”your name” 而不是真的名字
1 | print('Please type your name.') |
e.g.
1 | Please type your name. |
another way:
1 | while True: |
make patterns!
1
1 | a=6 |
e.g.
1 | ****** |
2
1 | a=1 |
1 | * |
another way
1 | for a in range(1,7): |
calculation of factorial
阶乘计算
1 | result=1 |
e.g.
input=9
output=362880