gpt4 book ai didi

Python:如何使用用户输入来关闭或继续 while 循环

转载 作者:行者123 更新时间:2023-12-05 07:42:09 24 4
gpt4 key购买 nike

我是 python 的新手,仍在努力弄清楚基础知识。我在网上寻找答案,但似乎没有任何解决方案适合我。我不知道我是否遗漏了一些小东西,或者我的整体结构是错误的。我的代码的计算部分按预期工作。

我的问题是,我不知道如何要求用户输入是或否导致:

(回答 YES 重新开始循环,以便用户可以尝试另一个计算)

(答案不关闭循环/结束程序)

请告诉我您的建议!

    play = True

while play:

hours = float(input("Please enter the number of hours worked this week: "))
rate = float(input("Please enter your hourly rate of pay: "))

#if less than 40 hrs
if hours <= 40:
pay = hours * rate
print "Your pay for this week is",pay

#overtime 54hrs or less
elif hours > 40 < 54:
timeandhalf = rate * 1.5
pay = (40 * hours * rate) + ((hours - 40) * timeandhalf)
print "Your pay for this week is",pay

#doubletime more than 54hrs
elif hours > 54:
timeandhalf = rate * 1.5
doubletime = rate * 2
pay = (40 * hours * rate) + ((hours - 40) * timeandhalf) + ((hours - 54) * doubletime)
print "Your pay for this week is",pay


answer = (input("Would you like to try again?: "))
if str(answer) == 'yes':
play = True
else:
play = False

最佳答案

您正在使用 Python 2.x。 input() 尝试将输入作为有效的 Python 表达式运行。当你输入一个字符串时,它会尝试在命名空间中寻找它,如果找不到它就会抛出一个错误:

NameError: name 'yes' is not defined

您不应该使用 input 来接收未经过滤的用户输入,这可能很危险。相反,使用 raw_input()返回一个字符串:

play = True

while play:

hours = float(raw_input("Please enter the number of hours worked this week: "))
rate = float(raw_input("Please enter your hourly rate of pay: "))

#if less than 40 hrs
if hours <= 40:
pay = hours * rate
print "Your pay for this week is",pay

#overtime 54hrs or less
elif hours > 40 < 54:
timeandhalf = rate * 1.5
pay = (40 * hours * rate) + ((hours - 40) * timeandhalf)
print "Your pay for this week is",pay

#doubletime more than 54hrs
elif hours > 54:
timeandhalf = rate * 1.5
doubletime = rate * 2
pay = (40 * hours * rate) + ((hours - 40) * timeandhalf) + ((hours - 54) * doubletime)
print "Your pay for this week is",pay

answer = raw_input("Would you like to try again?: ").lower()
while True:
if answer == 'yes':
play = True
break
elif answer == 'no':
play = False
break
else:
answer = raw_input('Incorrect option. Type "YES" to try again or "NO" to leave": ').lower()

关于Python:如何使用用户输入来关闭或继续 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44751720/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com