Python的条件判断和循环

条件判断

计算机之所以能做很多自动化的任务,因为它可以自己做条件判断。

在Python程序中,用if语句实现

根据Python的缩进规则,如果if语句判断是True,也可以给if添加一个else语句,意思是,如果if判断是False,不要执行if的内容,去把else执行了。

例1:输用户名和密码,判断是否能登录

import getpass
username = input('请输入用户名')
password = getpass.getpass('请输入密码')
if username == 'admin' and password == '123456' :
print('欢迎使用本系统。')
else:
print('用户名或密码错误!')

例2:百分制的成绩转成等级制

a = float(input('请输入成绩:'))
if a >= 90:
print('等级为A')
elif a >=80:
print('等级为B')
elif a >= 70:
print('等级为C')
else:
print('等级为D')

例3:输入三个数,找出最大的数    三元条件运算

a = int(input('请输入一个整数:'))
b = int(input('请输入一个整数:'))
c = int(input('请输入一个整数:'))

my_max = a > b and a or b
my_max = c >my_max and c or my_max
print(my_max)

例4:个人所得税计算器

salary = float(input('请输入本月收入:'))
insurance = float(input('五险一金:'))
diff = salary - insurance - 3500
if diff <= 0:
tax = 0
deduction = 0
elif diff <= 1500:
tax = 0.03
deduction = 0
elif diff <=4155:
tax = 0.1
deduction = 105
elif diff <= 7755:
tax = 0.2
deduction = 555
elif diff <= 27255:
tax = 0.25
deduction = 1005
elif diff <= 41255:
tax = 0.3
deduction = 2755
elif diff <= 57505:
tax = 0.35
deduction = 5505
else:
tax = 0.45
deduction = 13505
personal = abs(diff * tax - deduction)
print('个人所得税为:¥%.2f元' % personal)
print('实际到手工资为:¥%.2f元' % (salary - insurance - personal))

循环

为了让计算机能计算成千上万次的重复运算,我们就需要循环语句。

Python的循环有两种,一种是for...in循环,第二种循环是while循环,只要条件满足,就不断循环,条件不满足时退出循环。

例5:计算机出一个1~100的数字,然后人来猜

from random import randint

answer = randint(1, 100)
counter = 0
while True:
thy_answer = int(input('请输入:'))
counter += 1
if thy_answer < answer:
print('大一点')
elif thy_answer > answer:
print('小一点')
else:
print('恭喜你猜对了')
break

例6:反转的猜数字,人出数字机器猜

from random import randint
my_answer = int(input('输入数字:'))

while True:
answer = randint(1,100)
if answer < my_answer:
print('大一点')
elif answer > my_answer:
print('小一点')
else:
print('猜对了')
break

例7:人机猜拳  (计算机产生随机数表示剪刀石头布,1000)

原文地址:https://www.cnblogs.com/kurusuyuu/p/8497204.html