2016-08-23 62 views
0

試圖返回到數據問題是用戶輸入不正確的數字。計算電話帳單(蟒蛇)

我需要需要知道,如果輸入不正確的數字

import math 

p=float(input('Please enter the price of the phone: ')) 
print('') 
data=int(input('Enter the amount of the data you will use, 1 gig, 3 gigs, 6 gigs: ')) 
tax=p*.0925 
Total=p+tax 
print('') 

print ('If your phone cost',p,',the after tax total in Tennessee is',round(Total,2)) 
print('') 
if data==1: 
    datap=30 
    print('The price of one gig is $30.') 
elif data==3: 
    datap=45 
    print('The price of three gig is $45.') 
elif data==6: 
    datap=60 
    print('The price of six gigs is $60.') 
else: 
    print(data, 'Is not an option.') 
    #I need need to know how to return to the question again if incorrect number is entered 

pmt=Total/24 
bill=(datap+20)*1.13 

total_bill=bill+pmt 
print('') 
print('With the phone payments over 24 months of $',round(pmt,2),'and data at $',datap, 
'a month and line access of $20. Your total cost after tax is $',round(total_bill,2)) 

回答

1

你應該進入一個無限循環,只有擺脫它,當用戶輸入一個有效的輸入如何再回到這個問題。

import math 

costmap = {1: 30, 3: 45, 6: 60} 
price = float(input('Please enter the price of the phone: ')) 
datamsg = 'Enter the amount of the data you will use, 1 gig, 3 gigs, 6 gigs: ' 

while True: 

    try: 
     data = int(input(datamsg)) 
    except ValueError: 
     print('must input a number') 
     continue 

    tax = price * .0925 
    total = price + tax 

    print('If your phone cost {}, the after tax total in Tennessee is {}' 
      .format(price, round(total, 2))) 

    try: 
     datap = costmap[data] 
     print('The price of one gig is ${}.'.format(datap)) 
     break 

    except KeyError: 
     print('{} is not an option try again.'.format(data)) 

pmt = total/24 
bill = (datap + 20) * 1.13 
total_bill = bill + pmt 

print('With the phone payments over 24 months of ${}'.format(round(pmt, 2))) 
print('and data at ${} a month and line access of $20.'.format(datap)) 
print('Your total cost after tax is ${}'.format(round(total_bill, 2))) 

您也可以通過定義一個字典映射投入成本值簡化if/else條款。如果該值不存在,則會拋出一個您可以捕獲的異常,併發出錯誤並再次繞過該循環。

最後,我建議您嘗試通過pep-8檢查程序運行您的代碼,如http://pep8online.com/。它會教你如何格式化你的代碼,使其更易於閱讀。目前你的代碼比它更難以閱讀。

+0

謝謝,我是新來的編碼和欣賞的幫助。 – todd2323

+0

沒問題,歡迎您。 –