我正在处理这个简单的任务,我需要使用2个while循环。第一个while循环检查小时数是否小于0,如果是,则循环应该继续询问用户。 这是我的代码:
hours = float(input('Enter the hours worked this week: '))
count = 0
while (0 > hours):
print ('Enter the hours worked this week: ')
count = count + 1
pay = float(input('Enter the hourly pay rate: '))
while (0 > pay):
print ('Enter the hourly pay rate: ')
count = count + 1
total_pay = hours * pay
print('Total pay: $', format(total_pay, ',.2f'))
答案 0 :(得分:4)
break
正是您要找的。 p>
x = 100
while(True):
if x <= 0:
break
x -= 1
print x # => 0
至于你的例子,似乎没有任何东西会导致中断。例如:
hours = float(input('Enter the hours worked this week: '))
count = 0
while (0 > hours):
print ('Enter the hours worked this week: ')
count = count + 1
您根本没有编辑hours
变量。这只会继续打印"Enter the hours worked this week: "
并无限增加count
。我们需要知道提供更多帮助的目标是什么。
答案 1 :(得分:4)
您可以使用break
或将条件设为false来退出循环。
在您的情况下,您接受用户的输入,如果hours < 0
,则打印提示并更新计数,但您不会更新小时数。
while (0 > hours):
print ('Enter the hours worked this week: ')
count = count + 1
应该是:
while (0 > hours):
hours = float(input('Enter the hours worked this week: '))
count = count + 1
同样适用于付款:
while (0 > pay):
pay = float(input('Enter the hourly pay rate: '))
count = count + 1
答案 2 :(得分:1)
好吧,另一个答案向您展示了如何摆脱while循环,但您还没有分配付费和小时变量。您可以使用内置输入功能来获取用户提供给程序的内容
hours = float(input('Enter the hours worked this week: '))
count = 0
while (0 > hours):
hours = input('Enter the hours worked this week: ')
count = count + 1
pay = float(input('Enter the hourly pay rate: '))
while (0 > pay):
pay = input('Enter the hourly pay rate: ')
count = count + 1
total_pay = hours * pay
print('Total pay: $', format(total_pay, ',.2f'))