2016-08-23 2 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 절을 단순화 할 수 있습니다. 값이 존재하지 않으면 catch 할 수있는 예외를 throw하고 오류를 발행 한 다음 루프를 다시 돌립니다.

마지막으로 http://pep8online.com/과 같은 pep-8 검사기를 통해 코드를 실행하는 것이 좋습니다. 코드를 쉽게 포맷 할 수있는 방법을 알려줍니다. 현재 코드는 읽을 수있는 것보다 읽기가 어렵습니다.

+0

감사합니다. 코딩에 익숙하지 않고 도움을 주셔서 감사합니다. – todd2323

+0

아무 문제 없습니다. –