Python - Multi Input Validation - python

I'm writing a pay calculator program using a series of nested loops. Everything works except I have to make sure that the input for number of hours worked on the specified day is between 0 and 24 inclusive. This is the code I have for that section, I've tried multiple different options but they all either crash the program or aren't recognised at all. Any help would be appreciated!
This is the related code:
for x in range(0, weeks):
for y in days:
while True:
print ("Enter the number of hours for Week", x+1, y, ":")
try:
hours = int(input())
except ValueError:
print ("Invalid: Enter a positive integer")
continue
else:
break;
if y == 'Saturday':
newRate = satRate
elif y == 'Sunday':
newRate = sunRate
else:
newRate = baseRate
rate += (hours * newRate)
This is the whole code if you need a more wide look:
baseRate = -1
while baseRate < 1:
baseRate = float(input("Enter the base pay rate: "))
if baseRate < 1:
print("Invalid: Enter a non-negative amount")
satRate = baseRate * 1.5
sunRate = baseRate * 2
pay = 0
rate = 0
hours = -2
weeks = -1
while weeks < 1:
while True:
try:
weeks = int(input("Enter the number of weeks: "))
except ValueError:
print("Invalid: Enter a positive integer")
continue
else:
break
if weeks < 1:
print("Invalid: Enter a positive integer")
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
for x in range(0, weeks):
for y in days:
while True:
print ("Enter the number of hours for Week", x+1, y, ":")
try:
hours = int(input())
except ValueError:
print ("Invalid: Enter a positive integer")
continue
else:
break;
if y == 'Saturday':
newRate = satRate
elif y == 'Sunday':
newRate = sunRate
else:
newRate = baseRate
rate += (hours * newRate)
pay = (round(rate, 2))
av = pay/weeks
average = round(av,2)
print("Total pay is: ", pay)
print("Average pay per week is: ", average)

Your code doesn't check for valid hours input (unless you removed it due to it crashing, etc). Here one way to do it:
try:
hours = int(input())
while not 0 <= hours <= 24:
print ("Invalid input, hours must be between 0 and 24 inclusive.")
print ("Try again")
hours = int(input())
except ValueError:
print ("Invalid: Enter a positive integer")
continue

It is usually better to work more modular, using functions for your actions. This code may work and it's much more readable:
def get_baserate():
rate = input('Base rate:')
try:
rate = float(rate)
if not rate > 0:
print 'Rate must be positive'
return get_baserate()
return rate
except TypeError:
print 'Rate must be a positive number'
return get_baserate()
def get_weeks():
weeks = input('Number of weeks:')
try:
weeks = int(weeks)
if not weeks > 0:
print 'A positive number must be entered'
return get_weeks()
return weeks + 1
except TypeError:
print 'An integer must be entered'
return get_weeks()
def get_hours(week, day):
hours = input('Enter number of hours worked on %s of week %s:' % (day, week))
try:
hours = int(hours)
if not 0 <= hours <= 24:
print 'A number between 0-24 must be entered'
return get_hours(day)
return hours
except TypeError:
print 'An integer must be entered'
return get_hours(day)
def get_payday(rate, hours, day):
rate = 2*rate if day == 'Sunday' else 1.5*rate if day == 'Saturday' else rate
return hours*rate
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
rate = get_baserate()
weeks = get_weeks()
total_payday = 0
for week in range(1, weeks):
for day in days:
hours = get_hours(week, day)
total_payday += get_payday(rate, hours, day)
print 'Your total pay is: %s' % total_payday

Related

Check if the input value is valid in list using python

The programm is check if input value is valid in list.
below is my code. could you please help?thanks
while True:
try:
count = 0
Day_list = []
days = int(input("Enter number : "))
except ValueError:
print("Please input the integer")
else:
for i in range(days):
Day_list.append(float(input("Enter the day "+str(i+1)+ ": " )))
if( 0<= Day_list[i] <=10):
print('good' )
else:
print('Amount cant be negative, try again')
break
i would like check the value one by one
eg.
Enter the day 1 : -1
then output : Amount cant be negative, try again
return Enter the day 1 : 1
Enter the day 2 :
but i dont have idea where is mistake,thanks
here you are:
while True:
try:
count = 0
Day_list = []
days = int(input("Enter number : "))
except ValueError:
print("Please input the integer")
else:
if days >= 0:
for i in range(days):
valid = False
while not valid:
try:
Day_list.append(float(input("Enter the day "+str(i+1)+ ": " )))
if( Day_list[i] >= 0 and Day_list[i] <=10):
print('good' )
valid = True
except ValueError:
print ('input is not valid')
break
else:
print('Amount cant be negative, try again')

Finding Minutes Between Years

can you please check my code? I think something is wrong somewhere.
import datetime
this_year = datetime.datetime.today().year
def age_in_minutes(b_year: int):
d1 = datetime.datetime.strptime(f'{this_year}', '%Y')
d2 = datetime.datetime.strptime(f'{b_year}', '%Y')
age = (d1-d2).days * 24 * 60
return f"{age:,}"
while True:
birth_year = input("Enter you birth year: ")
try:
if int(birth_year) == this_year:
print("Please enter year less than this year...")
elif int(birth_year) > this_year:
print("Please enter year less than this year...")
elif len(birth_year) < 4 or len(birth_year) > 5:
print("PLease enter a valid year...")
elif int(birth_year) <= 1900:
print("Please enter a year after 1900...")
else:
minutes_old = age_in_minutes(int(birth_year))
print(f"You are {minutes_old} minutes old.")
break
except ValueError:
print("Please enter in a year format: ")
I'm tackling a challenge. It said if I enter 1930, I should get "48,355,200". But I'm getting "48,388,320". I'm new to Python.
You could try this code
I found it somewhere in 2021 but I don't know the source
current_year = 2022
year = int(input("Please enter a year: "))
if year == current_year:
print("There are 0 minutes from", year, "to present.")
elif year < current_year:
print("There are", (current_year - year) * 525600, "minutes from", year, "to present.")
else:
print("There are", (year - current_year) * 525600, "minutes from present to", year)
try this:
import datetime
this_year = datetime.datetime.today().year
print(this_year)
def age_in_minutes(b_year: int):
d1 = datetime.datetime.strptime(f'{this_year}', '%Y')
d2 = datetime.datetime.strptime(f'{b_year}', '%Y')
age = (d1-d2).days * 24 * 60
return f"{age:,}"
while True:
birth_year = int(input("Enter you birth year: "))
try:
if birth_year == this_year:
print("Please enter year less than this year...")
elif birth_year > this_year:
print("Please enter year less than this year...")
elif len(str(birth_year)) < 4 or len(str(birth_year)) > 5:
print("PLease enter a valid year...")
elif birth_year <= 1900:
print("Please enter a year after 1900...")
else:
minutes_old = age_in_minutes(birth_year)
print(f"You are {minutes_old} minutes old.")
break
except ValueError:
print("Please enter in a year format: ")
Output:
Enter you birth year: 1930
You are 48,388,320 minutes old.
I don't do any exceptional but change your type casting, and it can give me a desire result.
You haven't calculated leap year. You can follow this:
import datetime
this_year = datetime.datetime.today().year
def age_in_minutes(b_year: int):
leap_year = 0
non_leap_year = 0
for year in range(b_year, this_year+1):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
leap_year += 1
else:
non_leap_year += 1
leap_year_in_days = leap_year * 366
non_leap_year_in_days = non_leap_year * 365
age = (leap_year_in_days + non_leap_year_in_days) * 24 * 60
return f"{age:,}"
while True:
birth_year = input("Enter you birth year: ")
try:
if int(birth_year) == this_year:
print("Please enter year less than this year...")
elif int(birth_year) > this_year:
print("Please enter year less than this year...")
elif len(birth_year) < 4 or len(birth_year) > 5:
print("PLease enter a valid year...")
elif int(birth_year) <= 1900:
print("Please enter a year after 1900...")
else:
minutes_old = age_in_minutes(int(birth_year))
print(f"You are {minutes_old} minutes old.")
break
except ValueError:
print("Please enter in a year format: ")

creating a program that calculates the number of days delegated to heating and cooling homes based on temperature on certain days

I have created a program that calculates the number of days delegated to heating and cooling homes based on temperature on certain days. If the temp>80 it is delegated as a cooling day and if the temp<60 delegated as a heating. I have created a while loop to loop through and ask for the temp for each day with a corresponding "stop" value to stop entering days. After this the program is supposed to print the total amount of heat and cool days but something in my code is broke where it is not able to decipher the different days and each time it just comes up as 0 for each.
def main():
day = 1
C_days = 0
H_days = 0
done = False
while not done:
temp = input("Please enter the average temperature for day " + str(day) + " or stop to end: ")
if temp.lower() != "stop" and temp.lower() != "s":
temp = eval(temp)
if temp > 80:
C_days += temp-80
elif temp < 60:
H_days += 60-temp
day += 1
else:
done = True
print("The number of heating-degree days: ", H_days)
print("The number of cooling-degree days: ", C_days)
main()
Try changing your code to this
def main():
day = 1
C_days = 0
H_days = 0
done = False
while not done:
temp = input("Please enter the average temperature for day " + str(day) + " or stop to end: ")
#checks if it's supposed to stop or not
if temp.lower() != "stop" and temp.lower() != "s":
temp = eval(temp)
if temp > 80:
#here is a change, since you want the total number of days,
#you just have to add one to the cooling days if it's more than 80
C_days = C_days + 1
elif temp < 60:
#and here is a change, since you want the total number of days,
#you just have to add one to the heating days if it's more than 80
H_days = H_days + 1
day += 1
else:
done = True
print("The number of heating-degree days: ", H_days)
print("The number of cooling-degree days: ", C_days)
main()

My python code does what it is intended to do, but breaks/keeps going with the try/catch blocks?

#A 0-50 Units is multiplied by $0.59 (multiply by 0.59)
#B Up to 150 Units (minus 50 and multiply remaning by 0.65)
#C Greater than 150 Units(minus 150(first 150 = $94.50) and multiply remaining by 0.68)
#D All Residential charges are fixed # $13.00(always add $13)
print (" * SKELEC Electricity Bill Calculator * ")
def main():
while True:
try:
prev_month = float(input("Enter the meter reading for the previous month\n"))
break
except ValueError:
print("Invalid value entered. Please try again.")
continue
if prev_month < 0:
print("Please enter a valid reading.")
main()
while True:
try:
pres_month = float(input("Enter the meter reading for the current month\n"))
break
except ValueError:
print("Invalid value entered. Please try again.")
continue
if pres_month < 0:
print("Please enter a valid reading.")
main()
if pres_month < prev_month:
print("Present month value is lower than previous month value")
main()
units_kwh = pres_month - prev_month #Variable for the subtraction of present month and previous month
print("Usage = ", units_kwh,"kw/h")
if units_kwh <= 50: #Argument for 0-50 kwh units
Energy_charge = units_kwh * 0.59
print("Your charge for the month is, $", Energy_charge)
elif units_kwh > 50 and units_kwh <= 150: #Argument for units up to 150kwh
units_fifty = units_kwh - 50
Energy_charge = (units_fifty * 0.65 + 29.50) + 13.00
print("Your charge for the month is, $", Energy_charge)
elif units_kwh > 150: #Argument for units over 150kwh
Energy_charge = ((units_kwh - 150) * 0.68 + 94.50) + 13.00
print("Your charge for the month is, $", Energy_charge)
print("Residential Charge of $13.00 added")
main()
Everything works well, but if an incorrect value is entered at first(such as characters), the code unwantedly loops once it gives the final result. I've tried moving the try/catch blocks outside of the loop, double checking my conditional statements and proofreading to see how the code could loop in such a way. I'm convinced the problem lays in the try/catch blocks, but I'm fairly new to coding with Python so I am unsure of how to fix this?
You can make a couple changes to improve the code:
If the user enters a negative number, raise an exception
Add an outer while loop for the pres_month < prev_month condition
Try this code:
def main():
while True: # pres_month < prev_month
while True:
try:
prev_month = float(input("Enter the meter reading for the previous month\n"))
if prev_month < 0: raise ValueError()
break
except ValueError:
print("Invalid value entered. Please try again.")
while True:
try:
pres_month = float(input("Enter the meter reading for the current month\n"))
if pres_month < 0: raise ValueError()
break
except ValueError:
print("Invalid value entered. Please try again.")
if pres_month < prev_month:
print("Present month value is lower than previous month value")
else:
break # data is valid

Collatz Sequence: Automate the Boring Stuff with Python Chapter 3 Practice Project

This is my working code:
number = int(input())
while number > 1:
if number % 2 == 0:
number = int(number) // 2
print (number)
elif number % 2 == 1:
number = 3 * int(number) + 1
print (number)
Now I'm trying to add the exception that if user input has non-integer value, it should print 'Enter a number'
while True:
try:
number = int(raw_input())
break
except ValueError:
print("Enter a number!")
while number > 1:
....
EDIT: As noted in a comment by Anton, use raw_input in Python 2, and input in Python 3.
I'm a complete beginner so I would appreciate all kinds of tips. Here is how I managed to solve the problem, and for now it seems to work fine:
def collatz(number):
if number%2 == 0:
return number // 2
else:
return 3*number+1
print ('Enter a number:')
try:
number = int(input())
while True:
if collatz(number) != 1:
number= collatz(number)
print(number)
else:
print('Success!')
break
except ValueError:
print('Type an integer, please.')
You could check for ValueError for the except. From docs:
exception ValueError
Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.
try:
number = int(input())
while number > 1:
if number % 2 == 0:
number = int(number) // 2
print (number)
elif number % 2 == 1:
number = 3 * int(number) + 1
print (number)
except ValueError:
print('Enter a number')
You could do this-
while number != 1:
try:
if number % 2 == 0:
number = int(number) // 2
print (number)
elif number % 2 == 1:
number = 3 * int(number) + 1
print (number)
except ValueError:
print('Enter a number')
break
def collatz(number):
if number % 2 == 0:
return number // 2
else:
return 3 * number + 1
while True:
try:
value = int(input("Eneter a number: "))
break
except ValueError:
print("enter a valid integer!")
while value != 1:
print(collatz(value))
value = collatz(value)
def coll(number):
while number !=1:
if number%2==0:
number= number//2
print(number)
else:
number= 3*number+1
print(number)
while True:
try:
number = int(input("Enter the no:"))
break
except ValueError:
print("Enter a number")
print(coll(number))
I did it like this:
# My fuction (MINI-Program)
def collatz(number):
if number % 2 == 0:
return number // 2
else:
return 3 * number + 1
# try & except clause for errors for non integers from the users input
try:
userInput = int(input("Enter a number: "))
# Main loops till we get to the number 1
while True:
number = collatz(userInput)
if number !=1:
userInput = number
print(userInput)
else:
print(1)
break
except ValueError:
print("Numbers only! Restart program")

Categories

Resources