已知程序段m=0 n=0 while n<=10 n=n+1

2025年03月24日 阅读 (54)

例1.超市购物案例:

#去超市买东西,单价和数量,允许买多件商品

#计算总额 float

total=0 #初始变量赋值要放在循环体外。

number=0

whileTrue: #当不知道循环次数时,可考虑用while True

price=float(input('输入价格:')) #先买

number=int(input('输入数量:')

total+=price*number #金额累加

number+=number #数量累加

#判断是否继续购买

answer=input('当前商品总额:%.2f,是否继续添加商品(q表示退出)?'%total)

ifanswer=='q':

break #跳出while循环

print

例2、猜数字

#产生随机数 random.randint(start,end)

#可以猜多次,直到猜对为止,如果猜错了适当给出提示,猜大了还是猜小了

#统计猜了几次

#如果1次就中,赶快去买彩票吧,运气爆了

#2-5次,猜对了,运气还可以哦

#6次以上,猜对了,运气一般啊

import random

ran=random.randint(1,50)

count=0

#循环猜多次

while True: #当我们不知道循环次数时,考虑用while True

guess=int(input('猜一个1-50之间的数字:'))

count+=1

#猜对就结束

ifguess==ran:

ifcount==1:

print('赶快去买彩票吧,运气爆了!')

elif2=count=5:

print('猜对了,运气还可以哦!')

elifcount=6:

print('猜对了,运气一般啊!')

break

elifguessran:

print('猜大了,再小一点!')

else:

print('猜小了,再大一点!)

#猜拳游戏 三局两胜

import random

n=1

#计数

p_count=0

m_count=0

while n=3:

#猜拳

#机器产生数字 0 1 2

ran=random.randint(0,2)

#人猜数字

guess=int)

#比较判断

if or or

print('~~~~~本局我赢了!~~~~~~')

p_count+=1

elif or or

print('~~~~~本局机器赢了!~~~~~~')

郑重声明:玄微运势的内容来自于对中国传统文化的解读,对于未来的预测仅供参考。