Python 如何根据我的程序中的用户输入给出错误消息?
所以我用Python编写了一个电费计算器。好消息是它能工作!但是,我需要让它更好地工作。当被问到每天有多少小时时,用户可以输入25小时,或者他们想要的任何其他数字。很明显,一天没有25个小时。我试过一些方法,但不能使它正常工作 我试过这样的方法:Python 如何根据我的程序中的用户输入给出错误消息?,python,if-statement,error-handling,while-loop,Python,If Statement,Error Handling,While Loop,所以我用Python编写了一个电费计算器。好消息是它能工作!但是,我需要让它更好地工作。当被问到每天有多少小时时,用户可以输入25小时,或者他们想要的任何其他数字。很明显,一天没有25个小时。我试过一些方法,但不能使它正常工作 我试过这样的方法: hours = input("How many hours per day? ") if hours > 24: print("Don't be silly, theres not more than 24 hours in a day
hours = input("How many hours per day? ")
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
else:
main()
while hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
hours = int(input("How many hours per day? "))
我想做的是,如果他们输入的时间超过24小时,让程序显示一条错误消息,如果他们输入的时间超过24小时,那么跳到下面的代码,询问他们是否想尝试另一个计算。如果他们输入24小时或更少,则继续程序,且无错误消息。我花了大约两天的时间试图解决这个问题,在谷歌上搜索了几个小时,我可能已经看到了正确的答案,但似乎无法让它工作。我想我需要某种真实的陈述,或者如果;然后,尽管我试了很多次,我还是在这一点上拔出了我的头发。整个程序的代码如下所示:
def main():
star = '*' * 70
print star
print ("Nick's Electric Bill Calculator")
print star
watts = input("Enter the watts of appliance, or total watts of appliances ")
hours = input("Enter the number of hours that appliance(s) run per day ")
cost = input("Enter the cost in cents per KwH you pay for electricty " )
# print ("Don't be silly, there isn't more than 24 hours in a day!")
x = (watts * hours / 1000.0 * 30) * cost
total = x
print star
print ("""If you use %s watts of electricity for %s hours per day, at a cost of
%s cents per Kilo-watt hour, you will add $%s to your monthly
electric bill""") % (watts, hours, cost, total)
print star
playagain = 'yes'
while playagain == 'yes':
main()
print('Would you like to do another Calculation? (yes or no)')
playagain = raw_input()
我是编程新手,我学习Python才几周,非常感谢您的建议。我将您的错误消息放在if语句中,将计算代码放在else语句中。这样,当小时数不正确时,它不会进行计算,而是退出main并返回while循环,询问用户是否愿意再次播放。另外,正如其他用户所指出的,按照我在下面所做的,您应该添加更多错误测试和负数消息,等等
def main():
star = '*' * 70
print star
print ("Nick's Electric Bill Calculator")
print star
watts = input("Enter the watts of appliance, or total watts of appliances ")
hours = input("Enter the number of hours that appliance(s) run per day ")
cost = input("Enter the cost in cents per KwH you pay for electricty " )
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
else:
x = (watts * hours / 1000.0 * 30) * cost
total = x
print star
print ("""If you use %s watts of electricity for %s hours per day, at a cost of %s cents per Kilo-watt hour, you will add $%s to your monthly electric bill""") % (watts, hours, cost, total)
print star
playagain = 'yes'
while playagain == 'yes':
main()
print('Would you like to do another Calculation? (yes or no)')
playagain = raw_input()
用户输入的是
字符串
类型,但您可以将其与int
类型进行比较。那是个错误。您应该首先将字符串
强制转换为int
:
hours = int(input("How many hours per day? "))
# ----^---
然后,您可以执行以下操作:
hours = input("How many hours per day? ")
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
else:
main()
while hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
hours = int(input("How many hours per day? "))
如果您不确定用户是否会输入数字,则应使用try/catch
statemant
除此之外,您应该验证您是否正确缩进了代码我的python技能有点生疏,但是当我必须做一些事情,比如检查输入时,我通常使用如下结构:
hours = 0
while True:
hours = input("How many hours per day? ")
#first make sure they entered an integer
try:
tmp = int(hours) #this operaion throws a ValueError if a non-integer was entered
except ValueError:
print("Please enter an integer")
continue
#2 checks to make sure the integer is in the right range
if hours > 24:
print("Don't be silly, theres not more than 24 hours in a day ")
continue
if hours < 1:
print("Enter a positive integer")
continue
#everything is good, bail out of the loop
break
hours=0
尽管如此:
小时=输入(“每天多少小时?”)
#首先确保他们输入了一个整数
尝试:
tmp=int(hours)#如果输入了非整数,则此操作将抛出ValueError
除值错误外:
打印(“请输入一个整数”)
持续
#2检查以确保整数在正确的范围内
如果时间>24小时:
打印(“别傻了,一天不超过24小时”)
持续
如果小时数小于1:
打印(“输入正整数”)
持续
#一切都很好,跳出圈套
打破
基本上,它从进入“无限”循环开始。它获取输入,通过所有检查查看它是否有效,如果一切正常,则点击中断(离开循环)。如果数据以任何方式损坏,它会通知用户并使用continue命令重新启动循环hours=0
在循环外部声明,因此它仍然可以在外部范围内访问,因此可以在其他地方使用
编辑:在看到@Ohad Eytan的答案后想到的示例代码中添加一个想法,一个@JamesRusso代码的优化版本:
def main():
star = '*' * 70
print star
print ("Nick's Electric Bill Calculator")
print star
watts = int(input("Enter the watts of appliance, or total watts of appliances"))
hours = int(input("Enter the number of hours that appliance(s) run per day"))
# Check that the hours number is good before getting to the cost
while (hours > 24) or (hours < 0):
print("Don't be silly, theres not more than 24 or less than 0 hours in a day ")
hours = int(input("Enter the number of hours that appliance(s) run per day "))
cost = int(input("Enter the cost in cents per KwH you pay for electricty "))
# We don't need an auxiliary variable x here
total = (watts * hours / 1000.0 * 30) * cost
print star
print ("""If you use %s watts of electricity for %s hours per day, at a cost of %s cents per Kilo-watt hour, you will add $%s to your monthly electric bill""") % (watts, hours, cost, total)
print star
if __name__ == '__main__':
playagain = 'yes'
while playagain == 'yes':
main()
print 'Would you like to do another Calculation? (yes or no)'
playagain = raw_input()
# Checking that the user's input is whether yes or no
while playagain not in ['yes', 'no']:
print "It's a yes/no question god damn it"
print 'Would you like to do another Calculation? (yes or no)'
playagain = raw_input()
def main():
星='*'*70
印刷明星
打印(“尼克的电费计算器”)
印刷明星
瓦特=整数(输入(“输入设备瓦特或设备总瓦特”))
hours=int(输入(“输入设备每天运行的小时数”))
#在计算成本之前,检查小时数是否正确
而(小时>24小时)或(小时<0小时):
打印(“别傻了,一天不超过24小时或少于0小时”)
hours=int(输入(“输入设备每天运行的小时数”))
成本=整数(输入(“输入您为电费支付的每千瓦时的成本,单位为美分”))
#这里不需要辅助变量x
总=(瓦特*小时/1000.0*30)*成本
印刷明星
打印(““”如果您每天使用%s瓦特的电力%s小时,每千瓦特小时的成本为%s美分,您将在每月电费中添加$%s”“”)(瓦特、小时、成本、总计)
印刷明星
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
再次播放='是'
当再次播放时==“是”:
main()
打印“您想再做一次计算吗?”?(是或否)'
再次播放=原始输入()
#检查用户的输入是否为是或否
当再次播放时,不在['yes','no']中:
打印“这是一个肯定/否定的问题,该死的”
打印“您想再做一次计算吗?”?(是或否)'
再次播放=原始输入()
您应该更好地格式化此代码,并解释更改的内容,而不是转储代码