import random
a = 0
while True:
x = random.choice(range(100))
y = random.choice(range(100))
a = a+1
if x > y:
print(x,'>',y)
elif x < y:
print(x,'<',y)
else:
print('x=y=', x, 'total cal ', a, 'times')
break
1102Python3 条件控制
取随机数扩展。取随机数直到两数相等,显示取数次数。
import random
x = random.choice(range(100))
y = random.choice(range(100))
b,c = x,y
a = 1
print(x,y)
while x != y:
if x > y:
print('x:',x)
elif x == y:
print('x+y:', x + y,'totall cal ',a,'times')
else:
print('y:',y)
x = random.choice(range(100))
y = random.choice(range(100))
a = a+1
print('initialized data:',b,c,'x+y:', x + y,'total cal ',a,'times')
1101Python3 条件控制
if 的两种格式
可以括号限定代码域,加强代码可读性。
name ="pag"
if name == "pag":
print(name=="pag") # True
if (name == "pag"):{
print(name == "pag") # True
}
1100Python3 条件控制
下表列出了不同数值类型的 true 和 false 情况:
类型
False
True
布尔
False(与0等价)
True(与1等价)
数值
0, 0.0
非零的数值
字符串
'', ""(空字符串)
非空字符串
容器
[], (), {}, set()
至少有一个元素的容器对象
None
None
非None对象
1099Python3 条件控制
使用判断语句来实现 BMI 的计算。
BMI 指数(即身体质量指数,简称体质指数又称体重,英文为 Body Mass Index,简称BMI),是用体重公斤数除以身高米数平方得出的数字
1103Python3 条件控制
存在时间 楼上的太复杂了,而且 elif 还不会执行到,优化如下:
import random a = 0 while True: x = random.choice(range(100)) y = random.choice(range(100)) a = a+1 if x > y: print(x,'>',y) elif x < y: print(x,'<',y) else: print('x=y=', x, 'total cal ', a, 'times') break1102Python3 条件控制
取随机数扩展。取随机数直到两数相等,显示取数次数。
import random x = random.choice(range(100)) y = random.choice(range(100)) b,c = x,y a = 1 print(x,y) while x != y: if x > y: print('x:',x) elif x == y: print('x+y:', x + y,'totall cal ',a,'times') else: print('y:',y) x = random.choice(range(100)) y = random.choice(range(100)) a = a+1 print('initialized data:',b,c,'x+y:', x + y,'total cal ',a,'times')1101Python3 条件控制
if 的两种格式
可以括号限定代码域,加强代码可读性。
name ="pag" if name == "pag": print(name=="pag") # True if (name == "pag"):{ print(name == "pag") # True }1100Python3 条件控制
下表列出了不同数值类型的 true 和 false 情况:
1099Python3 条件控制
使用判断语句来实现 BMI 的计算。
BMI 指数(即身体质量指数,简称体质指数又称体重,英文为 Body Mass Index,简称BMI),是用体重公斤数除以身高米数平方得出的数字
#!/usr/bin/env python3 print('----欢迎使用BMI计算程序----') name=input('请键入您的姓名:') height=eval(input('请键入您的身高(m):')) weight=eval(input('请键入您的体重(kg):')) gender=input('请键入你的性别(F/M)') BMI=float(float(weight)/(float(height)**2)) #公式 if BMI<=18.4: print('姓名:',name,'身体状态:偏瘦') elif BMI<=23.9: print('姓名:',name,'身体状态:正常') elif BMI<=27.9: print('姓名:',name,'身体状态:超重') elif BMI>=28: print('姓名:',name,'身体状态:肥胖') import time; #time模块 nowtime=(time.asctime(time.localtime(time.time()))) if gender=='F': print('感谢',name,'女士在',nowtime,'使用本程序,祝您身体健康!') if gender=='M': print('感谢',name,'先生在',nowtime,'使用本程序,祝您身体健康!')