视频教程来自:www.zygx8.com,谢谢!
一、 If 语句
if 条件:
语句1
elif 条件2:
语句2
else
语句3
范例:
# if-猜数字
number=66
guess=int(input('Enter an intenger: '))
if guess==number:
print('you are right!')
elif guess<number:
print('the number is higher than that')
else:
print('the number is lower than that')
二、For 语句
# for语句
#1
for i in range(1,10):
print(i)
else:
print('done')
#2
a_list=[1,2,4,5,8]
for i in a_list:
print(i)
#3
a_tuple=(2,3,5,6)
for i in a_tuple:
print(i)
ano_tuple=('a','b','c')
for i in ano_tuple:
print(i)
#4
a_dict={'Tom':11,"May":23}
for ele in a_dict:
print(ele)
print(a_dict[ele])
三、while 语句
# while 语句
number=66
flag=True
while flag:
guess=int(input('Enter an intenger: '))
if guess==number:
print('you are right!')
flag=False
elif guess<number:
print('the number is higher than that')
else:
print('the number is lower than that')
print('done!')
四、range 语句
# range 语句:range(1,10),实际上是从1-9,包括前面不包括后面
# 同猜数字,限定次数时
number=66
chances=3 #3次机会
for i in range(1,chances+1):
guess = int(input('Enter an intenger: '))
if guess == number:
print('you are right!')
flag = False
elif guess < number:
print('the number is higher than that')
print('you still have '+str(chances-i)+' chances')
else:
print('the number is lower than that')
print('you still have ' + str(chances - i) + ' chances')
print('done!')
五、其他
1. break:跳出整个循环
2. continue:忽略循环剩下的部分,重新回到for的部分
3. pass:相当于什么都没有
#pass
list1=[0,1,2]
for i in list1:
if not i:
continue
print(i)
# i=0, if生效,执行continue,忽略循环体剩余部分,进入下一次循环i=1
# i=1, if不满足,继续执行print;i=2时一样的道理
# 【注意】:python中,布尔型属于int,其实就是1-0
for i in list1:
if not i:
pass
print(i)
# i=0,if生效,执行pass,pass相当于什么都没有,所以继续执行print
最后我想吐槽一下,为什么我的程序代码乌漆抹黑的???为什么???