我是python的新手,仍在努力弄清楚基础知识。我在网上寻找答案,但似乎没有解决方案适合我。我不知道我是否遗漏了一些小东西,或者我的总体结构是错误的。我的代码的计算部分就像它应该的那样工作。
我的问题是,我无法弄清楚如何要求用户输入是或否导致:
(答案是重新启动循环,以便用户可以尝试其他计算)
(答案是关闭循环/结束程序)
请让我知道你的建议!
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
答案 0 :(得分:0)
我认为你应该要求用户输入是或否,直到他这样做。
while play:
# Here goes your code
while True:
answer = input("Would you like to try again? Yes or No?").lower()
if answer in ('yes', 'no'):
break
play = answer == 'yes'
答案 1 :(得分:0)
您使用的是Python 2.x. input()
尝试将输入作为有效的Python表达式运行。当您输入一个字符串时,它会尝试在命名空间中查找它,如果找不到则会抛出错误:
NameError:未定义名称“是”
您不应该使用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()
答案 2 :(得分:-1)
var = raw_input("Would you like to try again: ")
print "you entered", var
可以在this question和Vicki Laidler的答案中找到是/否的变体。