Can someone show the right approach to get below desired output? [duplicate] - python

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
When the user gives wrong input for tax_rate, it should ask user the correct input for that variable, but instead it is starting from first, asking the hr_rate input which is already received.
while True:
try:
hr_rate = float(input("Enter Hourly Rate: "))
emp_ot_rate = float(input("Enter Overtime Rate: "))
tax_rate = float(input("Enter Standard Tax Rate: "))
ot_tax_rate = float(input("Enter Overtime Tax Rate: "))
except Exception:
print("Invalid entry, please retry")
Output:
Enter Hourly Rate: abc
Invalid entry, please retry
Enter Hourly Rate: 10.2
Enter Overtime Rate: 20.25
Enter Standard Tax Rate: abc
Invalid entry, please retry
Enter Hourly Rate:
The last line should ask for Standard Tax Rate again.

Whenever you see repetitive code, it is generally the case of defining a function that performs the same task but with the appropriate differences based on the given argument(s):
def userInput(variable):
while True:
try:
user_input = float(input(f"Enter {variable}: "))
break
except Exception:
print("Please enter any numbers")
return user_input
This function will perform the same task but the input prompt will change according to the variable argument; e.g you can call it with 'Hourly Rate':
hr_rate = userInput("Hourly Rate")
and it will prompt the user with the correct sentence:
>>>Enter Hourly Rate:

From #Brian's comment above, and at the risk of doing someone's homework for them...
def float_input(prompt):
'''Prompt user with given <prompt> string.'''
while True:
try:
return float(input("Enter Hourly Rate: "))
except ValueError: # Make exceptions as specific as possible
print("Please enter any numbers")
hr_rate = float_input("Enter Hourly Rate: ")
emp_ot_rate = float_input("Enter Overtime Rate: ")
tax_rate = float_input("Enter Standard Tax Rate: ")
ot_tax_rate = float_input("Enter Overtime Tax Rate: ")

Related

How can I loop a line of code until the user types the correct answer? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I am a beginner and i can't understand that how can I loop a line until the user types that correct answer and then it breaks. For ex.
ask = int(input("How much rice do you want? "))
price_of_1kg = 50
total = ask*price_of_1kg
print("This is the price")
print(f"Value: ${total}")
pay = int(input("Pay this price mentioned above "))
while True:
if pay == total:
print("good")
break
if pay != total:
int(input("Hey!! Pay the exact amount "))
break
print("Thank you, visit again")
```
I want to loop the second if statement until the user enters the correct amount
you can do it like this:
ask = int(input("How much rice do you want? "))
price_of_1kg = 50
total = ask*price_of_1kg
print("This is the price")
print(f"Value: ${total}")
pay = int(input("Pay this price mentioned above "))
while pay != total:
pay = int(input("Hey!! Pay the exact amount "))
print("Thank you, visit again")

Hello There, trying to make this program continuously loop until they input a valid selection from the first menu

trying to make this program continuously loop until they input a valid selection from the first menu, options 1-6. So far I it only will only ask 1 more time and then if they input an invalid character it goes straight to terminate message. For a class I'm taking and very new to this program.
Any help would be appreciated. I did notice that if I post the
if Choice not in [1,2,3,4,5,6]:
print ("\n",Choice, "is not a valid choice.\n")
print ("Please select choose from the available options.\n")
menu()
Choice = int(input("What type of Conversion would you like to execute? Enter Choice(1-6): "))
section after elif Choice==6 it will loop another time but that's it.
# Imperial - Metric Conversion Calculator
# This Program Calculates the conversions from Imperial to Metric units
# or Metric to Imperial units. Users first select the type of conversion
# they wish to execute, then they enter their value and the program converts
# it. They will then be asked if they wish to execute another conversion,
# if yes the process would be repeated, if no the program will terminate.
#
# N = Number of Units, for the calculation
# R = Result from calculation
# Initialization
terminate = False
while not terminate:
# Welcome Message
print("\n""Created By Name \n")
# Instructions
print("Welcome to the Imperial/Metric Conversion Calculator,")
print("please select the type of Conversion you would like to")
print("perform from the list.\n")
# Define Menu
def menu():
print("1.Ounces to Grams Conversion.\n")
print("2.Grams to Ounces Conversion.\n")
print("3.Inches to Centimeters Conversion.\n")
print("4.Centimeters to Inches Conversion.\n")
print("5.Miles to Kilometers Conversion.\n")
print("6.Kilometers to Miles Conversion.\n\n")
menu()
# User Choice Input
Choice = int(input("What type of Conversion would you like to execute? Enter Choice(1-6): "))
# Calculations, if/elif Statements, Output
if Choice not in [1,2,3,4,5,6]:
print ("\n",Choice, "is not a valid choice.\n")
print ("Please select choose from the available options.\n")
menu()
Choice = int(input("What type of Conversion would you like to execute? Enter Choice(1-6): "))
# Process User Input, Display Result, Ounces to Grams
if Choice==1:
N = float(input("\n""Please enter the Number of Ounces: "))
R = N * (28.3495231)
print('\n \n'"Based on the units you entered the conversion from Ounces to Grams is {:,.2f}".format(R))
# Process User Input, Display Result, Grams to Ounces
elif Choice==2:
N = float(input("\n""Please enter the number of Grams?: "))
R = N / (28.3495231)
print('\n \n'"Based on the units you entered the conversion from Grams to Ounces is {:,.2f}".format(R))
# Process User Input, Display Result, Inches to Centimeters
elif Choice==3:
N = float(input("\n""Please enter the number of Inches?: "))
R = N * (2.54)
print('\n \n'"Based on the units you entered the conversion from Inches to Centimeters is {:,.2f}".format(R))
# Process User Input, Display Result, Centimeters to Inches
elif Choice==4:
N = float(input("\n""Please enter the number of Centimeters?: "))
R = N / (2.54)
print('\n \n'"Based on the units you entered the conversion from Centimeters to Inches is {:,.2f}".format(R))
# Process User Input, Display Result, Miles to Kilometers
elif Choice==5:
N = float(input("\n""Please enter the number of Miles?: "))
R = N * (1.609344)
print('\n \n'"Based on the units you entered the conversion from Miles to Kilometers is {:,.2f}".format(R))
# Process User Input, Display Result, Kilometers to Miles
elif Choice==6:
N = float(input("\n""Please enter the number of Kilometers?: "))
R = N / (1.609344)
print('\n \n'"Based on the units you entered the conversion from Kilometers to Miles is {:,.2f}".format(R))
# Thank You Message
print('\n\n'"Thank you for using the Imperial - Metric Conversion Calculator! \n")
# Terminate Check
response =input("Would you like to perform another conversion? (y/n): ")
while response != 'y' and response != 'n':
response = input("Please enter 'y' or 'n' : ")
if response == "n" :
terminate = True
You can try this:
while True:
try:
choice = int(input("What type of Conversion would you like to execute? Enter Choice(1-6): ")))
if choice not in [1, 2, 3, 4, 5, 6]:
raise ValueError
break
except ValueError:
print ("\n",Choice, "is not a valid choice.\n")
print ("Please select choose from the available options.\n")
menu()
Does this help?

How do I store user input WITHOUT using a list in Python? [duplicate]

This question already has answers here:
Print list without brackets in a single row
(14 answers)
Closed 4 months ago.
I'm currently trying to store user input as integers without appending them to a list or creating a list at all.
First off, I tried using 5 independent variables for each input (code below), and when this code is ran it gives something to the tune of:
The fahrenheits you entered are (1, 2, 3, 4, 5)
How would I go about removing those parentheses?
firstFahr = int(input("Please enter a Fahrenheit temperature: "))
secondFahr = int(input("Please enter a Fahrenheit temperature: "))
thirdFahr = int(input("Please enter a third Fahrenheit temperature: "))
fourthFahr = int(input("PLease enter a fourth Fahrenheit temperature: "))
fifthFahr = int(input("Please enter a fifth Fahrenheit temperature: "))
enteredFahrs = firstFahr, secondFahr, thirdFahr, fourthFahr, fifthFahr
print("The fahrenheits you entered are", enteredFahrs)
Thanks for any help in advance and apologies if this seems like a noob question, as I'm quite new to Python.
How about this:
prompts = ('first', 'second', 'third', 'fourth', 'fifth')
entered_fahrs = tuple(
int(input(f'Please enter a {p} Fahrenheit temperature: '))
for p in prompts
)
print(f'The Fahrenheits you entered are: {", ".join(str(f) for f in entered_fahrs)}')
If you really, truly want to avoid sequences, you can then do a simple unpack:
first_fahr, second_fahr, third_fahr, fourth_fahr, fifth_fahr = entered_fahrs
This should solve your problem:
firstFahr = int(input("Please enter a Fahrenheit temperature: "))
secondFahr = int(input("Please enter a Fahrenheit temperature: "))
thirdFahr = int(input("Please enter a third Fahrenheit temperature: "))
fourthFahr = int(input("PLease enter a fourth Fahrenheit temperature: "))
fifthFahr = int(input("Please enter a fifth Fahrenheit temperature: "))
print("The fahrenheits you entered are", firstFahr, secondFahr, thirdFahr, fourthFahr, fifthFahr)
There are no lists whatsoever (and no parentheses as well).
I doubt this is what you are really asked to do, but an alternative approach is to use a generator expression to avoid storing the variables entirely.
user_inputs = (
int(input(f'Please enter a {p} Fahrenheit temperature: '))
for p in ('first', 'second', 'third', 'fourth', 'fifth')
)
print("The fahrenheits you entered are", *user_inputs)

How to make input statements optional?

I was having a small issue while I was trying to write a program to calculate simple interest in Python.
def si(p,r=100,t=2):
return (p*r*t)/100
x=float(input("Enter principal amount"))
y=float(input("Enter rate"))
z=float(input("Enter time"))
print (si(x,y,z))
I want to make y and z optional. Any idea how can I do? If I leave it blank and press enter it shows error.
The easiest way is using or
def si(p,r,t):
return (prt)/100
x = float(input("Enter principal amount: "))
y = float(input("Enter rate: ") or 100)
z = float(input("Enter time: ") or 2)
print (si(x,y,z))
Enter principal amount: 1
Enter rate:
Enter time:
2.0
But correct way is validating input before converting it to float
def si(p,r=100,t=2):
return (p*r*t)/100
x = input("Enter principal amount: ")
y = input("Enter rate: ")
z = input("Enter time: ")
def validate(param):
return float(param) if param else 1
print (si(validate(x), validate(y), validate(z)))
Output:
Enter principal amount: 1
Enter rate:
Enter time:
0.01

How to use the return function but avoid repetition of a function?

Trying to write this salary calculator script, but the output keeps on calculating taxes twice. It does what it is supposed to do, but I am misusing the concept of return statement, I reckon. I am kinda new to Python and just starting with the DSA. I tried searching for this problem a lot but apart from info for return statement, I couldnt solve this recurring statement problem. I would like your suggestions on the rest of the program as well.
Thanks!
Here is my code:
import math
# Personal Details
name = input("Enter your first name: ")
position= input("Enter your job position: ")
def regPay():
#Computes regular hours weekly pay
hwage= float(input("Enter hourly wage rate: "))
tothours=int(input("Enter total regular hours you worked this week: "))
regular_pay= float(hwage * tothours)
print ("Your regular pay for this week is: ", regular_pay)
return hwage, regular_pay
def overTime(hwage, regular_pay):
#Computes overtime pay and adds the regular to give a total
totot_hours= int(input("Enter total overtime hours this week: "))
ot_rate = float(1.5 * (hwage))
otpay= totot_hours * ot_rate
print("The total overtime pay this week is: " ,otpay )
sum = otpay + regular_pay
print("So total pay due this week is: ", sum)
super_pay = float((9.5/100)*sum)
print ("Your super contribution this week is:",super_pay)
return super_pay
def taxpay():
#Computes the taxes for different income thresholds, for resident Aussies.
x = float(input("Enter the amount of your yearly income: "))
while True:
total = 0
if x < 18200:
print("Congrats! You dont have to pay any tax! :)")
break
elif 18201 < x < 37000:
total = ((x-18200)*0.19)
print ("You have to pay AUD" ,total , "in taxes this year")
return x
break
elif 37001 < x < 80000:
total = 3572 + ((x-37000)*0.32)
print("You have to pay AUD",(((x-37000)*0.32) +3572),"in taxes this year")
return x
break
elif 80001 < x < 180000:
total = 17547+((x-80000)*0.37)
print ("You have to pay AUD" ,total ,"in taxes this year")
return x
break
elif 180001 < x:
total = 54547+((x-180000)*0.45)
print ("You have to pay AUD" , total ,"in taxes this year")
return x
break
else:
print ("Invalid input. Enter again please.")
break
def super(x):
#Computes super over a gross income at a rate of 9.5%
super_rate = float(9.5/100)
super_gross = float((super_rate)*(x))
print ("Your super contribution this year is: ",super_gross)
def main():
#Main function to pass vars from regPay to overTime and call.
hw , r_p = regPay()
overTime(hw, r_p)
taxpay()
y = taxpay()
super(y)
#Call main
main()
The output I get in powershell:
PS C:\Users\tejas\Desktop\DSA> python salary_calc.py
Enter your first name: tj
Enter your job position: it
Enter hourly wage rate: 23
Enter total regular hours you worked this week: 20
Your regular pay for this week is: 460.0
Enter total overtime hours this week: 20
The total overtime pay this week is: 690.0
So total pay due this week is: 1150.0
Your super contribution this week is: 109.25
Enter the amount of your yearly income: 20000
You have to pay AUD 342.0 in taxes this year
Enter the amount of your yearly income: 20000
You have to pay AUD 342.0 in taxes this year
Your super contribution this year is: 1900.0
From your output, I see it asks twice for the yearly income:
Enter the amount of your yearly income: 20000
You have to pay AUD 342.0 in taxes this year
Enter the amount of your yearly income: 20000
You have to pay AUD 342.0 in taxes this year
Looks like your problem is here:
def main():
#Main function to pass vars from regPay to overTime and call.
hw , r_p = regPay()
overTime(hw, r_p)
taxpay()
y = taxpay()
super(y)
You call taxpay(), then set y to another call of taxpay(). Did you mean just to call this once? If so, try this instead:
def main():
#Main function to pass vars from regPay to overTime and call.
hw , r_p = regPay()
overTime(hw, r_p)
y = taxpay()
super(y)
Simply put, both of the following call / execute the taxpay function, so this will repeat exactly the same output, unless you modify global variables, which doesn't look like you are.
Only the second line will return the value into the y variable.
taxpay()
y = taxpay()
Along with that point, here you call the function, but never capture its returned output
overTime(hw, r_p)
And, as an aside, you don't want to break the input loop on invalid input.
print ("Invalid input. Enter again please.")
break # should be 'continue'

Categories