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.
Related
For the above question i have written this code . Math formula is correct but it is not giving the correct answer where is the fault?
def computepay(hours, rate):
if hours<=40:
pay = hours * rate
else:
pay = (((hours-40)*rate)*1.5)+rate*40
return pay
x = input("Enter hours: ")
y = input("Enter rate: ")
a = float(x)
b = float(y)
pay = computepay(a, b)
print("Pay: ", pay)
When hours is less than or equal to 40, computepay() doesn't return anything. Try changing the indent of the return pay line by four spaces, so it's indented by the same amount as the else::
def computepay(hours, rate):
if hours<=40:
pay = hours * rate
else:
pay = (((hours-40)*rate)*1.5)+rate*40
return pay
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.
I have looked and tried everything. I am a student and this is a homework assignment but I cannot figure out how to add the time to the date. I am trying to get the arrival date and time, by adding the hours and minutes it took to get there to the departure time, but it keeps adding days and second. This is what I have:
#!/usr/bin/env python3
from datetime import datetime, timedelta
import locale
def get_departure_date():
while True:
date_str = input("Estimated date of departure (YYYY-MM-DD:)")
try:
departure_date = datetime.strptime(date_str, "%Y-%m-%d")
except ValueError:
print("Invalid date format. Try again.")
continue
now = datetime.now()
today = datetime(now.year, now.month, now.day)
if departure_date < today:
print("Departure date must be today or later. Try again")
continue
else:
return departure_date
def get_departure_time():
while True:
time_str = input("Estimated time of departure (HH:MM AM/PM:)")
try:
departure_time = datetime.strptime(time_str, "%I:%M %p")
except ValueError:
print("Invaild time format. Try again.")
continue
else:
return departure_time
def get_miles():
while True:
try:
miles = int(input("Enter miles:"))
except ValueError:
print("Invalid Integer. Please try again.")
continue
else:
return miles
def get_mph():
while True:
try:
mph = int(input("Enter miles per hour:"))
except ValueError:
print("Invalid Integer. Please try again.")
continue
else:
return mph
def main():
print("Arrival Time Estimator")
print()
while True:
departure_date = get_departure_date()
departure_time = get_departure_time()
miles = get_miles()
mph = get_mph()
hours = int(miles // mph)
minutes = int(miles - (60 * hours))
arrival_date = departure_date + timedelta(hours, minutes)
print("hours: ", hours)
print("minutes: ", minutes)
print (arrival_date)
print()
result = input("Continue? (y/n): ")
print()
if result.lower() != "y":
print("Bye!")
break
if __name__ == "__main__":
main()
The timedelta constructor is not really intuitive in my mind. I find it's easiest to use with named arguments.
Change this line:
arrival_date = departure_date + timedelta(hours, minutes)
To this:
arrival_date = departure_date + timedelta(hours=hours, minutes=minutes)
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.