在python中,如何使程序以空行结束?

在python中,如何使程序以空行结束?,python,python-3.x,Python,Python 3.x,所以我有一个作业,我们必须创建一个程序来计算工资,并让它循环,教授希望我们在工资或工时输入一个空行时结束它。到目前为止,这就是我所拥有的 answer = 'yes' while answer == 'yes': hourly_pay = float(input('Enter hourly pay: ')) if hourly_pay == 0: print ('Program Terminated') break hours = int(input('Enter

所以我有一个作业,我们必须创建一个程序来计算工资,并让它循环,教授希望我们在工资或工时输入一个空行时结束它。到目前为止,这就是我所拥有的

answer = 'yes'

while answer == 'yes':

 hourly_pay = float(input('Enter hourly pay: '))

 if hourly_pay == 0:
    print ('Program Terminated')
    break

 hours = int(input('Enter hours worked: '))

 if hours == 0:
     print ('Program Terminated')
     break

 pay = hours * hourly_pay

 ot_pay = 1.5*hourly_pay

 if hours > 40:
     othours = hours - 40
     reghours = hours - othours
     pay = (ot_pay*othours)+(hourly_pay*reghours)

 print ('Pay = $',pay)

 answer = input ('repeat? (yes/no) ')

 while not (answer == 'yes' or answer == 'no'):
     answer = input('invalid response, answer (yes/no) ') 
仅当输入为零时,程序才会终止,但当仅输入一个空行时,程序会因错误而终止

编辑

多亏了Ricky Kim,程序现在可以在空行和零上运行和终止! 这是新代码

answer = 'yes'

while answer == 'yes':

hourly_pay = input('Enter hourly pay: ')

if not hourly_pay:
    print('Program Terminated')
    break
else:
    hourly_pay = float(hourly_pay)

if hourly_pay == 0:
    print ('Program Terminated')
    break

hours = input('Enter hours worked: ')

if not hours:
    print('Program Terminated')
    break
else:
    hours=int(hours)

if hours == 0:
    print('Program Terminated')
    break

pay = hours * hourly_pay

ot_pay = 1.5*hourly_pay

if hours > 40:
    othours = hours - 40
    reghours = hours - othours
    pay = (ot_pay*othours)+(hourly_pay*reghours)

print ('Pay = $',pay)

answer = input ('repeat? (yes/no) ')

while not (answer == 'yes' or answer == 'no'):
    answer = input('invalid response, answer (yes/no) ')

在转换为float或int之前,可以检查它是否为空。例如:

answer = 'yes'
while answer == 'yes':
    hourly_pay = input('Enter hourly pay: ')

    if not hourly_pay:
        print('empty line so quit')
        break
    else:
        hourly_pay = float(hourly_pay)

    if hourly_pay == 0:
        print ('Program Terminated')
        break
    #rest of your code here

持续数小时做同样的事情。

我不想给出答案,但您可以尝试在得到输入时不将其转换为数值-这样您可以尝试将其与空字符串进行比较,或检查得到的字符串的长度。如果不是“”,这也可能有帮助。
:print('None string'))
此外,输入将始终为字符串,因此您可以检查有效字符串,然后继续进行浮点/int类型转换whatever@mad_如果将其余代码放在下面,则输入零,则它将终止。你需要我写完整的代码吗?@mad_uu我添加了OP的代码来检查零。我不认为我需要把它包括进去,因为OP已经有了