Trying to return to data question is user enters incorrect number.
I need need to know how to return to the question again if incorrect number is entered
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))
You should enter an infinite loop and only break out of it when the user has entered a valid input.
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)))
You can also simplify your if/else clause by defining a dict to map inputs to cost values. If the value does not exist it throws an exception which you can catch, issue an error and go around the loop again.
Finally I'd recommend you try running your code through a pep-8 checker such as http://pep8online.com/. It will teach you how to format your code to make it easier to read. At present your code is more difficult to read than it could be.
Related
I'm a beginner at python and wanted to have a crack at my first personal project which is a score calculator for a student's subjects. I wanted to run a for loop that asks the user to input their scores for each of the individual subjects through an input() within a for loop. However, it would only take a singular string argument.
scores = {}
total = 0
years = int(input("How subjects have you completed? "))
for sub in range(0, years):
scores = input("Score for subject?",x)
total += int(scores)
Any help would be great, thanks!
If you wanted to keep track of scores by subject and find total score then...
subjects = dict( Math = 0, English = 0, Science = 0, History = 0 )
scores = dict()
total = 0
for sub in subjects.keys():
score = input( f"Score for {sub}? >" )
if score:
total += int( score )
scores[sub] = score
print( total )
for sub,tot in scores.items():
if tot > 0:
print( sub, tot )
The variable x never defined and used, just remove it may solve your problem.
scores first defined as a dict, then you re-define it without using it.Remove it make code more clear.
code:
total = 0
years = int(input("How subjects have you completed? "))
for sub in range(years):
scores = input("Score for subject?")
total += int(scores)
print(total)
result:
How subjects have you completed? 5
Score for subject?1
Score for subject?2
Score for subject?3
Score for subject?4
Score for subject?5
15
In the code sample:
x is an undefined variable.
scores = {} the 'scores' dictionary is useless as later you redefine it as a string.
Just removing the ,x in line 5 will make the code execute properly.
>>> total = 0
>>> for i in range(int(input("How many subjects have you completed? "))):
... total += int(input("Score for subject? "))
...
How many subjects have you completed? 3
Score for subject? 70
Score for subject? 80
Score for subject? 90
>>> total
240
I have run this code and changed it more times than I can count but it always results in a loop. I'm not quite sure what I've done wrong nor how to end the loop.
"""
WeeklyPay.py: generate payroll stubs for all hourly paid employees and summarizes them
"""
def main():
"""
total_gross_pay = 0
hours_worked = 0
gross_pay = 0
hourly_rate= 0
:return: None
"""
employee = input("Did the employee work this week? Y or y for yes: ")
while employee == "Y" or "y":
hours_worked = int(input("How many hours did the employee work this week? "))
hourly_rate = int(input("What is the employee's hourly rate? "))
gross_pay = hours_worked * hourly_rate
print("Your weekly pay is: "+ gross_pay)
main()
You might find the while loop shown below works more like what your program should do:
def main():
"""Help the user calculate the weekly pay of an employee."""
while input('Did the employee work this week? ') in {'Y', 'y'}:
hours_worked = int(input('How many hours? '))
hourly_rate = int(input('At what hourly rate? '))
gross_pay = hours_worked * hourly_rate
print('The weekly pay is:', gross_pay)
if __name__ == '__main__':
main()
You are using a while loop, in which the variable employee is never changed, so the condition stays True. It should work if you replace the while with an if.
I am writing this code for class I have and I need some help adding exception handling. Basically what I need help with is fitting the exception handling around my user inputs so if the user inputs anything other than what is specified it'll loop back and ask the user to input the correct answer. I also need to have an exception handling with one of my functions. This is my code so far.
symbol_list = ['AAPL', 'AXP', 'BA', 'CAT', 'CVX', 'DIS', 'GS', 'HD', 'IBM', 'INTC']
price_list = [150.75, 98.65, 340.53, 129.77, 111.77, 111.42, 175.37, 177.89, 119.83, 47.74]
invest_dict = {'AAPL': 150.75, 'AXP': 98.65, 'BA':340.53, 'CAT' :129.77, 'CVX' :117.77, 'DIS' :111.42, 'GS':175.37, 'HD':177.89, 'IBM': 119.83, 'INTC':47.74}
print("...............................Lab 8.........................")
def Greeting():
print("The purpose of this project is to provide Stock Analysis.")
def Conversions(investment_amount):
investment_amount = float(investment_amount)
Euro = float(round(investment_amount / 1.113195,2) )
Pound = float(round(investment_amount / 1.262304,2) )
Rupee = float(round(investment_amount / 0.014316,2) )
print("The amount you invest in euro is: {:.2f}" .format(Euro) )
print("The amount you invest in pounds is: {:.2f}" .format(Pound) )
print("The amount you invested in Rupees is: {:.2f}" .format(Rupee) )
def minimum_stock():
key_min = min(invest_dict.keys(), key = (lambda k: invest_dict[k]))
print("The lowest stock you can buy is: ",invest_dict[key_min])
def maximum_stock():
key_max = max(invest_dict.keys(), key = (lambda k: invest_dict[k]))
print("The highest stock you may purchase is: ",invest_dict[key_max])
def invest_range(investment_amount):
new_list = []
new_list = [i for i in price_list if i>=50 and i <=200]
return(sorted(new_list))
answer = 'yes'
while answer:
print(Greeting())
investment_amount = float(input("Please enter the amount you want to invest:$ "))
if investment_amount!='':
print("Thank you for investing:$ {:,.2f}".format(investment_amount))
print(Conversions(investment_amount))
for i in invest_dict:
i = investment_amount
if i <25:
print("Not enough funds to purchase stock")
break
elif i>25 and i <=250:
print(minimum_stock())
break
elif i >= 250 and i <= 1000:
print(maximum_stock())
break
print("This is the range of stocks you may purchase: ", invest_range(investment_amount))
answer = input("Would you like to complete another conversion? yes/no " )
if answer == 'no':
print("Thank you for investing.")
break
The archetypical way of doing this is something along the lines of
while True:
try:
investment_amount = float(input("Please enter the amount you want to invest:$ "))
break
except ValueError:
print("Please enter a dollar amount (a floating-point number)")
print("Thank you for investing: ${:,.2f}".format(investment_amount))
Alternatively, if you're willing to import stuff, the click module has a method to do something like this:
investment_amount = click.prompt('Please enter the amount you want to invest: $', type=float)
which will keep asking the user until the input is of the correct type. For your later prompt, asking for yes/no, click.confirm() can do that for you as well.
You can try this error handling where input is taken:
while answer:
print(Greeting())
try:
investment_amount = float(input("Please enter the amount you want to invest:$ "))
print("Thank you for investing:$ {:,.2f}".format(investment_amount))
except:
print("Please enter a valid amount...")
continue
print(Conversions(investment_amount))
Hope this will help.
How does one answer this question.
1. A dramatic society wants to record the number of tickets sold for each of their four performances. Ask the user to enter the number of tickets sold for each performance. The number must be between 0 and 120. Print an error message if an invalid number is entered and ask them to re-enter until they enter a valid number. Print the total number of tickets sold and the average attendance for a performance.
import re
affirm = False
p = 0
total = 0
for p in range(4):
p = input("Please enter the total number of tickets sold for the performance.")
while affirm != True:
try:
int(p)
except ValueError:
print("This is not a number")
else:
valid = re.match("[0-120]",p)
if valid:
total += p
affirm = True
else:
p = input("Please enter the total number of tickets sold for the performance.")
average = (total/480) * 100
average = round(average,2)
print("""
The total number of tickets sold is: """,total"""
The average attendance is : """,average)
My python book didn't really explain the correct syntax for the re module and the try except else function. Can someone point out if there is anything wrong with the code. This was my first go at validating user input.
You cannot use regular expression to see whether a number is between a certain range, and even if you did, it would be silly considering how easy it is to check if a number is between numbers in Python:
valid = 0 < p < 120
Here is your code after the fix:
affirm = False
p = 0
total = 0
for p in range(4):
p = input("Please enter the total number of tickets sold for the performance.")
while affirm != True:
try:
int(p)
except ValueError:
print("This is not a number")
else:
valid = 0 < p < 120
if valid:
total += p
affirm = True
else:
p = input("Please enter the total number of tickets sold for the performance.")
average = (total/480) * 100
average = round(average,2)
print("""
The total number of tickets sold is: """,total"""
The average attendance is : """, average)
More on: Expressions in Python 3
I have the example for gross pay but I want don't accept any string value . I tried to solve it with while true statement but executed with the first question of code.
I want these outputs :
Enter the hours worked this week:asd
please integer number
Enter the hours worked this week:10
Enter the hourly pay rate :asd
please float number
Enter the hourly pay rate :20.01
anyone help
my code
while True:
try:
hours = int(input('Enter the hours worked this week: '))
pay_rate = float(input('Enter the hourly pay rate: '))
gross_pay = hours * pay_rate
print('Gross pay: $', format(gross_pay, ',.2f'))
except ValueError:
print('please integer number)
This is a function I generally use when I need to validate multiple user input and request different types.
def get_input(typ, msg, err):
while True:
try:
return typ(input(msg))
except ValueError:
print("Please enter {0}".format(err))
hours = get_input(int, 'Enter the hours worked this week: ', 'an intger number')
pay_rate = get_input(float, 'Enter the hourly pay rate: ', 'a float number')
gross_pay = hours * pay_rate
print('Gross pay: $', format(gross_pay, ',.2f'))
Try this:
def hoursGet():
hours = input("Enter the hours worked this week: ")
try:
hours = int(hours)
return hours
except ValueError:
print ("please integer number")
hoursGet()
and simply write other functions for the other questions, substituting the printed statements and the data types.