fee = []
age = int(input("Enter age: "))
while age != '':
age = int(input("Enter age: "))
if age <= 5:
fee.append(0)
elif age >= 6 and age <= 64:
fee.append(50.00)
else:
fee.append(25.00)
total = sum(fee)
print("Total payment: ", total)
I want to make a program that would sum up the given entrance fees. I don't even know if I'm doing it correctly
You can't compare a string to an integer, that's your main problem. If you retrieve it from the user as a string and check it is indeed an integer or not will work. That code should do the trick:
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
fee = []
r='start'
while r != '':
r = input("Enter age: ")
if RepresentsInt(r):
age = int(r)
if age <= 5:
fee.append(0)
elif age >= 6 and age <= 64:
fee.append(50.00)
else:
fee.append(25.00)
total = sum(fee)
print("Total payment: ", total)
fee = 0
age = int(input("Enter age: "))
while age != '':
try:
age = int(input("Enter age: ")) // to avoid exception of string
except:
break
if age <= 5:
fee += 0 // no need to append if outcome is a number
elif age >= 6 and age <= 64:
fee += 50
else:
fee += 25
total = fee
print("Total payment: ", total)
Related
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: ")
This progam was working fine before i used data validation(the while loops) but now i get the following error -
average_grade = (grade1 + grade2) / 2
NameError: name 'grade2' is not defined
This error was not happening before , I have just started programming so i am quite confused
valid = False
while valid==False:
grade1 = float( input("Enter the grade1: ") )
if grade1 <0 or grade1 > 10:
print('Please enter a grade between 0 and 10')
continue
else:
valid = True
while valid==False:
grade2 = float(input("Enter the grade2: "))
if grade2 < 0 or grade2 > 10:
print('Please enter a grade between 0 and 10')
continue
else:
valid = True
while valid == False:
absences = int(input("Enter the number of absences: "))
if type(absences)!=int:
print("Number of absences can only be an integer value")
continue
else:
valid = True
while valid == False:
total_classes = int(input("Enter the total number of classes: "))
if type(total_classes)!=int:
print("Total number of classes can only be an integer value")
continue
else:
valid = True
average_grade = (grade1 + grade2) / 2
attendance = ((total_classes - absences) / total_classes)*100
print(average_grade)
print("Your attendance is :", attendance , "%")
if(average_grade>=6):
if(attendance>=0.8):
print("YOU HAVE PASSED")
else:
print("You have failed as your attendance is less than 80%")
elif(attendance>=0.8):
print("You have failed due to average grade being lower than 6")
else:
print("You have failed due to average grade being lower than 6 and attendance lower than 80%")
The problem is that you're never resetting the value of valid, so once you set valid = True in the first while loop, none of the other loops will execute (because the loop condition will be false).
You don't need the valid variable in any case; instead of having a
conditional loop expression with a flag, just break out of the loop
when you receive a valid value:
while True:
grade1 = float( input("Enter the grade1: ") )
if grade1 <0 or grade1 > 10:
print('Please enter a grade between 0 and 10')
continue
else:
break
while True:
grade2 = float(input("Enter the grade2: "))
if grade2 < 0 or grade2 > 10:
print('Please enter a grade between 0 and 10')
continue
else:
break
while True:
absences = int(input("Enter the number of absences: "))
if type(absences)!=int:
print("Number of absences can only be an integer value")
continue
else:
break
while True:
total_classes = int(input("Enter the total number of classes: "))
if type(total_classes)!=int:
print("Total number of classes can only be an integer value")
continue
else:
break
Unrelated to your question, but when you have a boolean variable you
don't need to compare it explicitly to False (or True); you can
use the value of the variable itself as the condition:
while somevar == False:
You can just write:
while not somevar:
it as been a long time without programming. I'm doing a function that converts the age of a dog to human years, but I'm getting some mistakes and I am not getting through them. This is my code
def calculator():
# Get dog age
age = input("Input dog years: ")
try:
# Cast to float
d_age = float(age)
# If user enters negative number, print message
if(d_age < 0):
print("Age can not be a negative number", age)
# Otherwise, calculate dog's age in human years
elif(d_age == 1):
d_age = 15
elif(d_age == 2):
d_age = 2 * 12
elif(d_age == 3):
d_age = 3 * 9.3
elif(d_age == 4):
d_age = 4 * 8
elif(d_age == 5):
d_age = 5 * 7.2
else:
d_age = 5 * 7.2 + (float(age) - 5) * 7
print("\n \t \'The given dog age", age, "is", d_age, "human years.'")
except ValueError:
print(age, "is an invalid age")
calculator()
and I'm not understanding why d_age < 0 is not working and I'm not getting why it appears as an error "calculator() is not defined". Thanks in advance!
NOTE: I saw that there already is question about this, but I'm doing in a different way.
EDIT: I just didn't do it with dictionaires, because it wasn't yet introduced in the course. I'm just trying to do with what I learned. Thanks anyway.
Looks like your code is not structure correctly. If you move the elif blocks and make some minor changes it will work. See below:
def calculator():
# Get dog age
age = input("Input dog years: ")
try:
# Cast to float
d_age = float(age)
# If user enters negative number, print message
if(d_age < 0):
print("Age can not be a negative number", age)
# Otherwise, calculate dog's age in human years
elif(d_age == 1):
d_age = 15
elif(d_age == 2):
d_age == 2 * 12
elif(d_age == 3):
d_age == 3 * 9.3
elif(d_age == 4):
d_age = 4 * 8
elif(d_age == 5):
d_age = 3 * 7.2
else:
d_age = 5 * 7.2 + (age - 5) * 7
print("\n \t \'The given dog age", age, "is", d_age, "human years.")
except ValueError:
print(age, "is an invalid age")
calculator()
How about this?
While statement to keep question looping until you get a valid response.
Dictionary to have a more organised age calculation sheet instead of lots of if statements.
def calculator_dog_age():
age = 0
while age == 0:
age = input("Input dog years: ")
try:
age = int(age)
if 20 > age > 0:
print('A good age was entered:', age)
age_dict = {1: 15, 2: 24, 3: 27.9, 4: 32}
if age in age_dict:
return age_dict[age]
else:
return age * 7.2 + (age - 5) * 7
else:
print('Please enter a realistic age!')
age = 0
except:
print('Please enter an integer!')
age = 0
print(calculator_dog_age())
This is my suggestion, even though the answer was accepted.
def calculator():
age = input("Input dog years: ")
try:
d_age = float(age)
ageDict = {1: 15, 2: 12, 3: 9.3, 4: 8, 5: 7.2}
if d_age in ageDict:
print(round(d_age*ageDict[d_age],2))
else:
print(round(5*7.2+(d_age - 5)*7,2))
except ValueError:
print(age,"is an invalid age")
calculator()
#get user's input on dog_age
dog_age = input("Enter your dog's age in years")
try:
#cast to a float
d_age = float(dog_age)
#convert dog age to human age
#ensure input is not negative
if (d_age > 0):
if (d_age <=1):
h_age = d_age *15
elif (d_age <=2):
h_age = d_age *12
elif (d_age <=3):
h_age = d_age*9.3
elif (d_age <=4):
h_age = d_age*8
elif (d_age <=5):
h_age = d_age*7.2
else:
h_age = 36 + (d_age - 5) *7
human_age = round(h_age,2)
#print instruction for valid input
print('The given dog age', dog_age,'is', str(human_age),'in human years')
else:
print('Age cannot be a negative number.')
except ValueError:
print(dog_age,'is invalid.')
The question I was solving has similar conditions but with different calculations required. I hope it helps (P.S initially I also could not figure out why my dog age <0 condition was not working, turns out, it’s all about blocking the conditions together and indentation use (: )
If anyone struggling with indention error or "SyntaxError: unexpected character after line continuation character" from print("\n \t 'The given dog age", age, "is", d_age, "human years."
The following solution helped me
def calculator():
# Get dog age
age = input("Input dog years: ")
try:
# Cast to float
d_age = float(age)
if (d_age> 5):
human_age = (d_age-5)*7+5*7.2
print("The given dog age",str(d_age),"is", str(human_age), "in human years")
elif (d_age>4):
human_age = d_age*7.2
print("The given dog age",str(d_age),"is",str(human_age),"in human years")
elif (d_age>3):
human_age = d_age*8
print("The given dog age",str(d_age),"is",str(human_age),"in human years")
elif (d_age>2):
human_age = d_age*9.3
print("The given dog age",str(d_age),"is",round(human_age,2),"in human years")
elif (d_age>1):
human_age = d_age*12
print("The given dog age",str(d_age),"is",str(human_age),"in human years")
elif (d_age>0):
human_age = d_age*15
print("The given dog age",str(d_age),"is",str(human_age),"in human years")
elif (d_age<0 or d_age==0):
print(d_age, "is a negative number or zero. Age can not be that.")
except:
print(age, "is an invalid age.")
print(traceback.format_exc())
calculator()
I am a beginner with python and I am working with this project that will print the result of the students.I am done with nearly everything execpt the percentage.See,in my code,the program will only print the percentage of the last person's marks.I need to make it so that it calculates percentage for everyone individually and then print it at the end.Your help will be much appreciated.Thanks
T_marks = 1100
data = {}
while True:
ask = input("What do you want? ")
if ask == "y":
name = input("Enter your name: ")
marks = int(input("Enter marks: "))
data[name] = marks
percentage =(marks / T_marks) * 100
elif ask == "print":
for (key,value) in data.items():
print(key,"::",value)
if percentage > 90:
print("Passed with A grade")
elif percentage >= 70 and percentage < 90:
print("Passed with B grade")
elif percentage >= 60 and percentage < 70:
print("Passed with C grade")
elif percentage >= 50 and percentage < 60:
print("passed with D Grade")
else:
print("You failed")
else:
print("Your work has ended")
break
You need to compute percentage under the print case, this should get you what you want:
T_marks = 1100
data = {}
while True:
ask = input("What do you want? ")
if ask == "y":
name = input("Enter your name: ")
marks = int(input("Enter marks: "))
data[name] = marks
elif ask == "print":
for (key,value) in data.items():
# NOTE percentage is under the case when user asks for print
percentage =(value / T_marks) * 100
print(key,"::",value)
if percentage > 90:
print("Passed with A grade")
elif percentage >= 70 and percentage < 90:
print("Passed with B grade")
elif percentage >= 60 and percentage < 70:
print("Passed with C grade")
elif percentage >= 50 and percentage < 60:
print("passed with D Grade")
else:
print("You failed")
else:
print("Your work has ended")
break
Also two hints: This code will output "You failed" if someone got a grade of 90. You need to set equality at 90 for one of the cases. Also python has simplified comparisons where and is not needed. Here is a simplified version, and corrected for case of 90 to get an A grade:
T_marks = 1100
data = {}
while True:
ask = input("What do you want? ")
if ask == "y":
name = input("Enter your name: ")
marks = int(input("Enter marks: "))
data[name] = marks
elif ask == "print":
for (key,value) in data.items():
percentage =(value / T_marks) * 100
print(key,"::",value)
if percentage >= 90:
print("Passed with A grade")
elif 90 > percentage >= 70:
print("Passed with B grade")
elif 70 > percentage >= 60:
print("Passed with C grade")
elif 60 > percentage >= 50:
print("passed with D Grade")
else:
print("You failed")
else:
print("Your work has ended")
break
The input() method reads a string, but you cannot convert e. g. "4 4 4 5" to int. Method split() without arguments creates a list of the words in string as follow:
"4 5 5" -> ["4", "5", "5"]
Change your input to:
marks_string = input("Enter marks: ")
marks = [int(mark) for mark in marks_string.split()] # convertion to int
And change calculate of percentage:
percentage =(sum(marks) / T_marks) * 100
Indentation, fixed in edit:
T_marks = 1100
data = {}
while True:
ask = input("What do you want? ")
if ask == "y":
name = input("Enter your name: ")
marks = int(input("Enter marks: "))
data[name] = marks
percentage =(marks / T_marks) * 100
elif ask == "print":
for (key,value) in data.items():
print(key,"::",value)
if percentage > 90:
print("Passed with A grade")
elif percentage >= 70 and percentage < 90:
print("Passed with B grade")
elif percentage >= 60 and percentage < 70:
print("Passed with C grade")
elif percentage >= 50 and percentage < 60:
print("passed with D Grade")
else:
print("You failed")
else:
print("Your work has ended")
break
>>> What do you want? y
>>>Enter your name: Alex
>>>Enter marks: 12
>>>What do you want? y
>>>Enter your name: Michael
>>>Enter marks: 22
>>>What do you want? print
>>>Alex :: 12
>>>You failed
>>>Michael :: 22
>>>You failed
>>>What do you want?
print('Hello, welcome to your grade calculator.')
GradeCount = 0
totalGrades = 0.0
moreStudent = 'y'
while moreStudent == 'y' or moreStudent == 'Y':
grade = float(input('Enter a grade or a -1 to end: '))
while grade != -1:
if grade > 100 or grade < 0:
print('Invalid input. Please enter a value between 1 and 100.')
grade = float(input('Enter the next grade or -1 to end: '))
continue
totalGrades = totalGrades + grade
GradeCount = GradeCount + 1
if 90 <= grade <=100:
print('You got an A. Thats awesome.')
print('Number of grades entered: ',GradeCount)
print('Class total: ',totalGrades)
elif 80 <= grade < 90:
print('You got a B. Good job.')
print('Number of grades entered: ',GradeCount)
print('Class total: ',totalGrades)
elif 70 <= grade < 80:
print('You got a C. Thats fine I guess.')
print('Number of grades entered: ',GradeCount)
print('Class total: ',totalGrades)
elif 60 <= grade < 70:
print ('You got a D. Not very good.')
print('Number of grades entered: ',GradeCount)
print('Class total: ',totalGrades)
elif grade < 60:
print ('You got an F. You fail.')
print('Number of grades entered: ',GradeCount)
print('Class total: ',totalGrades)
grade = float(input('Enter the next grade or -1 to end: '))
moreStudent = input('Are you a new student and ready to enter your
grades? y or n: ')
print ('Number of grades entered:', GradeCount)
print ('Class total:',totalGrades)
print ('Class grade average:', format(totalGrades / GradeCount, '.2f'))
How can I make it so the user only has 2 tries before the program issues an error message then clears the screen and starts over? Also how can I make it clear the screen every time there is a new user?
The most basic modification you could use to the current code is to add a counter, other methods can be used as well
while moreStudent == 'y' or moreStudent == 'Y':
grade = float(input('Enter a grade or a -1 to end: '))
count = 0
while grade != -1:
if grade > 100 or grade < 0:
count += 1
if count == 2:
moreStudnet = 'n'
break
else:
print('Invalid input. Please enter a value between 1 and 100.')
grade = float(input('Enter the next grade or -1 to end: '))
continue
totalGrades = totalGrades + grade
GradeCount = GradeCount + 1