语法结构 :
for 自定义的变量 in 可迭代的对象:
条件执行体
注意:python中不用大括号括起来表示一个整体,而是用缩进。
练习:遍历列表元素
bicycles = ['trek','cannondale','redline','specialized']
for bicycle in bicycles:
print(bicycle)
trek
cannondale
redline
specialized
练习:通过以下代码,注意缩进与不缩进的区别
magicians = ['alice','david','carolina']
for magician in magicians:
print(f"{magician.title()},that was a great trick")
print(f"I can't wait to see your next trick,{magician.title()}.\n")
print("thank you,everyone.that was a great magic show!")
Alice,that was a great trick
I can't wait to see your next trick,Alice.
David,that was a great trick
I can't wait to see your next trick,David.
Carolina,that was a great trick
I can't wait to see your next trick,Carolina.
thank you,everyone.that was a great magic show!
while循环不断运行,直到条件不满足为止
语法结构
while 条件表达式: 条件执行体(循环体)
练习:使用while循环来数数,从1数到5
a = 1
while a<6:
print(a)
a=a+1
1
2
3
4
5
练习:
prompt = '\n Tell me sth,and I will repeat it back to you :'
prompt += '\n Enter "quit" to end the program '
message = ''
while message!='quit':
message=input(prompt)
print(message)
Tell me sth,and I will repeat it back to you :
Enter "quit" to end the program hello world
hello world
Tell me sth,and I will repeat it back to you :
Enter "quit" to end the program quit
quit
进程已结束,退出代码 0
while(条件):
······
if ····:
break
练习:用户指出去过的地方
prompt = '\n please enter a city you have ever visited'
prompt += '\n Enter "quit" to end the program '
message = ''
while True:
message=input(prompt)
if message =='quit':
break
else:
print(message)
please enter a city you have ever visited
Enter "quit" to end the program Beijing
Beijing
please enter a city you have ever visited
Enter "quit" to end the program Shanghai
Shanghai
please enter a city you have ever visited
Enter "quit" to end the program quit
进程已结束,退出代码 0
练习:要求输出1~30所有5的倍数
num = 0
while num <=30:
num+=1
if num % 5!=0:
continue
else:
print(num)
5
10
15
20
25
30
注意:
1、使用if语句、while、for循环时,着重注意不要忘记冒号导致语法出错
2、在循环时,不要忘记自加条件,例如上例中num+=1,一开始忘记加,造成死循环。
补充:input()函数
input()函数让程序暂停运行,等待用户输入一些文本。
注意input()输出为字符串类型,数值输入要进行运算和比较前需要进行类型转换
age = input('How old are you?')
print(age)
print(type(age))
How old are you?22
22
<class 'str'>
以下代码进行了类型转换为int型,否则不能进行数值比较
age = int(input('How old are you?'))
print(age>=18)
How old are you?22
True
如果…就… 语法结构: if 条件表达式: 条件执行体 如果条件满足就执行,反之如果条件不满足,则忽略。
练习:银行卡余额
a = 2000
num = int(input('请输入你想取的钱'))
if(num<a):
a=a-num
print(f"你的余额为{a}")
请输入你想取的钱300
你的余额为1700
双分支结构 如果…不满足 就…
语法结构:
if 条件表达式:条件执行体1 else:条件执行体2
练习:输入一个数,判断是奇数还是偶数
num = int(input('please input a number'))
if(num%2 ==0):
print('这是一个偶数')
else:
print('这是一个奇数')
please input a number22
这是一个偶数
多分支结构
if 条件表达式1:
条件执行体1
elif条件表达式2:
条件执行体2…
练习:按年龄收费的游乐场,4岁以下免费,4~18岁收费25美元,18岁及以上收费40美元
age = int(input('please input your age'))
if(age<4):
print('免费')
elif(age>4 and age<18):
print('收费25美元')
else:
print('收费40美元')
please input your age25
收费40美元