1.条件判断if else
如:
if age >=18 and scroe <= 100: #py中不使用&标识并集 等于使用== 不等于使用!=
print(‘成年‘)
else: #中间可以使用elif 加如其他条件
print (‘dd‘)
2.循环 遍历 迭代
(1)while循环 需要先定义一个计数器,需要有结束的条件,否则会死循环
count =0 while count<20: print(‘tianjia‘) #一直满足 count = count +1 #count+=1
(2) break 可以强制跳出循环体
(3) continue 结束当前此次循环
import random number = random.randint(1,100) #随机产生1-100的数字 count = 0 while count <7: count = count + 1 guess = input(‘请输入一个数字:‘) guess = int(guess) if guess == number: print(‘恭喜你猜对了‘) break elif guess <number: print(‘你猜的数过小啦‘) continue elif guess >number: print(‘你猜的过大啦,请继续猜‘) continue else:#与while对应的else的作用是循环正常结束时执行,否则不会执行 print(‘次数已经用完啦‘)
(4) for循环
for i in range(7):
for不需要计数器 可自动增加,与while不同也可不加continue
for i in range(7): guess = input(‘请输入一个数字:‘) guess = int(guess) if guess == number: print(‘恭喜你猜对了‘) break elif guess <number: print(‘你猜的数过小啦‘) elif guess >number: print(‘你猜的过大啦,请继续猜‘)
原文地址:https://www.cnblogs.com/cslw5566/p/12246812.html
时间: 2024-09-29 21:54:29