简体   繁体   English

如何使程序在python中的空白行处结束?

[英]How to make a program end on a blank line in python?

So i have an assignment where we had to create a program to calculate pay and have it loop, the prof wanted us to have it end if we input a blank line for either the pay or hours. 所以我有一个任务,我们必须创建一个程序来计算薪水并使其循环,如果我们输入薪水或小时数的空白行,教授希望我们结束它。 So far this is what I have 到目前为止,这就是我所拥有的

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) ') 

the program only terminates if the input is a zero but terminates with an error if only a blank line is input. 该程序仅在输入为零时终止,而在仅输入空白行时终止并返回错误。

EDIT 编辑

Thanks to Ricky Kim, the program now works and terminates on both blank lines and zeros! 多亏了Ricky Kim,该程序现在可以正常工作并且在空白行和零处终止! This is the new code 这是新代码

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) ')

You can check if it's empty before you convert to float or int. 您可以先检查它是否为空,然后再转换为float或int。 For example: 例如:

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

Do same thing for hours. 数小时做同样的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM