python - 如何根据程序中的用户输入给出错误消息?

标签 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 ")
else:
    main()

我想做的是让程序显示一条错误消息,如果他们输入的时间超过 24 小时,如果超过 24 小时,则跳到底部代码,询问他们是否想尝试另一个计算。如果他们输入 24 小时或更短时间,则继续执行程序,不会出现错误消息。我花了大约 2 天的时间试图解决这个问题,在谷歌上搜索了几个小时,我可能已经看到了正确的答案,但似乎无法让它发挥作用。我假设我需要某种 while True 语句,或者 if;then,但正如我尝试过的那样,此时我正在拔头发。整个程序的代码如下:

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 才几周时间,非常感谢您的任何建议。

最佳答案

@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()

关于python - 如何根据程序中的用户输入给出错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38777883/

相关文章:

c++ - 你如何使用是/否来输入你的答案 C++?

java - 如何缩短 if 语句

python - numpy,h5py : How do I make an array sorted by one of its columns from a bigger one saved with h5py?

SWIFT if 语句和 segue

python - 处理 Python 库包的最佳实践是什么?

php - Bugsnag 没有显示漂亮的错误页面

wpf - 在WPF应用程序中创建错误日志

php - PHP警告消息公开了OAuth应用的 secret

python - 如何在python中使用flask上传多个文件

python - 同时对多个列表进行排序