2016-08-23 2 views
0

Попытка вернуться к вопросу данных - пользователь вводит неверный номер.Вычислить счет за телефон (python)

мне нужно знать, как вернуться к вопросу еще раз, если неправильный номер введен

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, определив Dict для отображения входов Стоить значение. Если значение не существует, оно генерирует исключение, которое вы можете поймать, выдать ошибку и снова пройти цикл.

В заключение я бы рекомендовал вам попробовать запустить код с помощью контрольной панели pep-8, такой как http://pep8online.com/. Он научит вас, как отформатировать код, чтобы его было легче читать. В настоящее время ваш код сложнее читать, чем может быть.

+0

Спасибо, я новичок в кодировании и ценю помощь. – todd2323

+0

Без проблем. –