龙空技术网

年近半百自学Python之while循环结构练习

i51win 863

前言:

眼前各位老铁们对“python循环结构作业”大约比较看重,我们都需要学习一些“python循环结构作业”的相关内容。那么小编同时在网摘上汇集了一些对于“python循环结构作业””的相关知识,希望兄弟们能喜欢,大家快快来了解一下吧!

例1.超市购物案例:

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

#计算总额 float

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

number=0

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

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

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

total+=price*number #金额累加

number+=number #数量累加

#判断是否继续购买

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

if answer=='q':

break #跳出while循环

print('商品数量共:%d,商品的总额是:%.2f ' %(number,total)

-------------------------------

例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

#猜对就结束

if guess==ran:

if count==1:

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

elif 2<=count<=5:

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

elif count>=6:

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

break

elif guess>ran:

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(input('请输入:剪刀(0) 石头(1) 布(2)\n'))

#比较判断

if (guess==0 and ran==2) or (guess==1 and ran==0) or (guess==2 and ran==1)

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

p_count+=1

elif (ran==0 and guess==2) or (ran==1 and guess==0) or (ran==2 and guess==1)

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

m_count+=1

else:

print('本局平局!')

n+=1

#比较胜负:

if p_count>m_count:

print(‘最终人获胜了!')

elif p_count<count:

print('最终机器获胜!')

else:

print('最终平局!')

标签: #python循环结构作业 #python循环结构程序有趣案例 #python循环结构程序有趣案例解析