簡體   English   中英

如何使程序在python中的空白行處結束?

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

所以我有一個任務,我們必須創建一個程序來計算薪水並使其循環,如果我們輸入薪水或小時數的空白行,教授希望我們結束它。 到目前為止,這就是我所擁有的

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

數小時做同樣的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM