How do I use a python table? - python

I was requested by my teacher to write a program in python which would require visitors of said attraction to insert the number of family members they are visiting with, and based off of that, have them know the admission fee. The admission fees given were $25 for anybody under 16, and 40 for anybody over 40.
This is what I've got so far:
def main():
admission = 0
print("Welcome to Wally World - use this program to calculate your admission fees")
number = int(input("How many members will you be taking with you? "))
members = {}
for n in range(0,number):
age = int(input("Please enter your ages: "))
if age <= 16:
admission = 25
if age > 16:
admission = 40
main()
How would I go about grabbing said admission values and adding them all together?
Thank you!

There is no need to use members = {}
Admissions can be added with only single line conditional statement (ternary if-else).
Check whether number of person is not negative or zero (I've used exit() in this case).
Check whether age is not negative (I've put pass you may call your program again using main() or exit using exit()).
Here is the working code:
def main():
admission = 0
print("Welcome to Wally World - use this program to calculate your admission fees")
number = int(input("How many members will you be taking with you? "))
if number < 0: exit()
for n in range(0,number):
age = int(input("Please enter your ages: "))
admission += (25 if age <= 16 and age > -1 else 40 if age> 16 else 0)
return admission
main()

Related

How to check 2 conditions in while loop at the same time

The Question
Write a program that asks the user to enter their name and grades for all the courses they took this
semester. Check that the name is composed of only letters and that each grade entry is composed of
numbers only. When the user has entered all their grades, they may enter -1 to indicate they are done.
Calculate the average grade and display that to the user.
Sample given to me
Enter your name: Sar#
Please enter a valid name.
Enter your name: sara
Enter your grade for course 1: 90
Enter your grade for course 2: 90s
Please enter a valid grade.
Enter your grade for course 2: 80
Enter your grade for course 3: 70
Enter your grade for course 4: 60
Enter your grade for course 5: -1
Sara, your average grade for 4 courses this semester is 75.0. Well done!
My progress
count=0
sum=0
name = input("Enter your name: ")
while name.isalpha()==False:
print("Please enter a valid name.")
name = input("Enter your name: ")
grade = int(input("Enter your grade for course "+ str(count+1)+": "))
grade == 1
while grade!=-1:
grade = str(grade)
while grade.isnumeric()==False:
print("Please enter a valid grade.")
grade = input("Enter your grade for course "+ str(count+1)+": ")
grade =int(grade)
count+=1
sum+=grade
grade = int(input("Enter your grade for course "+ str(count+1)+": "))
avg = sum/count
if avg>60:
print(name.capitalize(),", your average grade for",count,"courses this semester is",avg,". Well done!")
else:
print(name.capitalize(),", your average grade for",count,"courses this semester is",avg,". Please do better.")
I get an int error. though I know why I get the error but have no other way to solve this problem. Please help!
You can use try except
Like this:
count=0
sum=0
name = input("Enter your name: ")
while name.isalpha()==False:
print("Please enter a valid name.")
name = input("Enter your name: ")
grade = 1
while grade!=-1:
try:
grade = int(input("Enter your grade for course "+ str(count+1)+": "))
if grade == -1: break
count+=1
sum+=grade
except:
print("Please enter a valid grade.")
avg = sum/count
if avg>60:
print(name.capitalize(),", your average grade for",count,"courses this semester is",avg,". Well done!")
else:
print(name.capitalize(),", your average grade for",count,"courses this semester is",avg,". Please do better.")
I assume you got an int error after entering a non-numeric value as your grade. You convert the grade to an int when you define it without checking if it's a numeric value or not. This will raise an exception, you can avoid it by using try/except or first checking if grade is numeric.
Your while grade.isnumeric()==False: is failing when user enters nothing. It passes through an empty string and in line
grade = int(input("Enter your grade for course "+ str(count+1)+": "))
it tries to evaluate it as int although it can't since its an empty string.
You have several things wrong with this homework assignment.
Here are some suggestions:
Append to a list grades =[] rather than a running grade that is initialized with a '1'. You don't want the '1' to be part of your average.
Use a try/except clause to validate the user input.
Compute the average on the list after you exit the while loop.

Python : Amount input with While

Beginner here. I'm trying to build a loop where the chekout displays a total amount that has to be over 0$. For example, if I start with 450$ the code works. But if I start with say -12 it will ask me again (which is what I want), but then if I enter 450 as the third essay; the first condition keeps runing. Why is that? Thanks in advance.
amount = input("What's the total amount of the bill ? :")
value = float(amount)
while (value < 0):
print("Please enter an amount higher than 0$ !")
amount = input("What's the total amount of the bill ? :")
else:
print("Total amount of the bill:{0}".format(value))
You forgot to update the variable "value" so your while loop condition remains true even after inputting 450 (value is still -12). You can convert the input to a float in the same line too, which removes the need for the "amount" variable
value = float(input("What's the total amount of the bill ? :"))
while (value < 0):
print("Please enter an amount higher than 0$ !")
value = float(input("What's the total amount of the bill ? :"))
else:
print("Total amount of the bill:{0}".format(value))

My code starts yielding illogical answers when a I deal with number bigger than 99

I am trying to write a program that determines a person stage of life, whether the person is a baby, kid, teenager, adult or elder. The program starts with a variable that contains an input() function that allows the user to type in an age so the program can start running.
The issue is that when I type ages higher than 99, the program prompts that the person whose age has been typed in is a baby. So basically, according to the program someone who is 123 years old is a baby, which does not make sense.
age=input("enter the person's age: ")
if age<'2':
print('the person is a baby')
elif age=='2' and age<'4':
print('the person is a toddler')
elif age >='4' and age<'13':
print ('the person is a kid')
elif age>='13' and age<'20':
print('the person is a teenager')
elif age>='20' and age<'65':
print('the person is an adult')
elif age>='65':
print('the person is an elder')
I am wondering if I am making a mistake on my code, although it seems to me pretty straight forward. Anyways, I am guessing there is some theoretical knowledge that I am missing, if that is the case I would appreciate if you folks can shed some light on the whole issue.
What you are essentially doing here is comparing strings which does not translate to the behavior you are seeking. You will need to cast the input as int() first.
If you know the input is guaranteed to be formatted correctly, use:
age = int(input("enter the person's age: "))
However, nobody is perfect so it would be best to wrap in a try-except:
age = input("enter the person's age: ")
try:
age = int(age)
except:
# Handle exception
if age < 2:
# Do something
elif ...
# Do more stuff
You are comparing strings no integers thus '100' is less than '99' as the first and second characters are less.
You need to convert your input to an integer and thenuuse that for the comparisons and then you shall be fine.
You should convert age to an integer and then compare. You are comparing strings, and that gives you weird answers.
Reformatted code:
age_str=input("enter the person's age: ")
try:
age = int(age_str)
except:
print("Invalid Entry. Enter age as a number.")
exit(0)
if age < 2:
print('the person is a baby')
elif age == 2 and age < 4:
print('the person is a toddler')
elif age >= 4 and age < 13:
print('the person is a kid')
elif age >= 13 and age < 20:
print('the person is a teenage r')
elif age >= 20 and age < 65:
print('the person is an adult')
elif age >= 65:
print('the person is an elder')
Code also checks for invalid entries above. If anything other than an integer is entered, it throws an error.

Is this the proper way to start my loop?

Question: “A movie theater charges different ticket prices depending on a person’s age. If a person is under the age of 3, the ticket is free; if they are between 3 and 12, the ticket is $10; and if they are over age 12, the ticket is $15. Write a loop in which you ask users their age, and then tell them the cost of their movie ticket.”
The reason I put != 'quit' is to give the end user the option of quiting the program. I don't know if that makes sense. This is what I have so far:
prompt = 'What is your age? '
age = ' '
while age != 'quit':
age = input(prompt)
age = int(age)
if age < 3:
price = 0
if age > 3:
price = 10
if age < 12:
price = 15
print('The price of your ticket is ' + price)
I keep getting a syntax error on the last print statement.
Preamble: In general, you should write what your code is supposed to accomplish. Also, it would be helpful if you wrote your code in a .py file for my (and anyone else who wants to help) convenience; I can't paste your code in the python interpreter, so I have to paste it in a file but I have to remove all those ">>>" and "...".
In this case, I will deduce that your requirements are
Get an age from the user and print it.
Validate the input and continue asking for an age until the input is valid.
The problem that you have is that your condition for quitting causes problem:
~/Desktop $ python3 stack_overflow.py
What is your age? 32
Age : 32
What is your age? quit
Age : quit
Traceback (most recent call last):
File "stack_overflow.py", line 6, in <module>
age = int(age)
ValueError: invalid literal for int() with base 10: 'quit'
So let's get the logic that we want down, then we'll see how to do it in python.
<get a valid input>
<decide the ticket price based on said valid input>
One thing to note is that in python, since the input is valid if it can be turned into an int we can try to turn it into an int and call the input valid if that conversion succeeds.
By reading error messages we can see that writing 'quit' results in ValueError, we can deduce that this:
prompt = 'What is your age? '
age = ' '
input_valid = False
while !input_valid:
age = input(prompt)
try:
age = int(age)
except ValueError:
input_valid = False
continue
if age > 0:
break
if age < 3:
price = 0
if age > 3:
price = 10
if age < 12:
price = 15
print('The price of your ticket is ' + str(price))
Now, at this point, I think you would have satisfied your requirements. However, lemme drop some more knowledge on you:
What if you read the following code:
age = get_age()
price = ticket_price(age)
print("The price of your ticked is " + str(age))
This reminds me of something I saw in a talk on YouTube which I thought was really nice: write code using functions that you wish existed then implement those functions.
def get_age():
while True:
age = input('What is your age : ')
try:
age = int(age)
except ValueError:
continue
if age > 0:
return age
def ticket_price(age):
if age < 3:
# Under 3 years old don't pay
return 0
if age < 12:
# between 3 and 12, price is 10$
return 10
# 12 and above pay 15
return 15
age = get_age()
price = ticket_price(age)
print('The price of your ticket is ' + str(price))
Also, another tip: whenever I have something like
while True:
...
if <something>:
break
It's a good idea to put that while loop in a function and replace the break with a return statement.
Given that I did not have your requirements, I can't be sure I solved your question. That being said, the main takeaways should be
separating the getting of input and the conversion from age to
price.
putting code into functions is worth your time even for toy examples
like this because it's practice for actual coding.
Writing out the logic of your program in pseudo code is also helpful.
You need to change the way you have set up your loop. It shouldn't terminate if the user enters 'quit' as the age. This doesn't make sense for the rest of your logic with regards to the variable age. Instead of using a while loop, you could instead use a for loop and print the price for a number of users
for user in range(5):
age = int(input('What is your age?'))
if age < 3: price = 0
if 3 <= age <= 12: price = 10
if age > 12: price = 15
print('The price of your ticket is: $' + str(price))

Python3 about Loops Iteration multiple variable simple algorithm

What i have to do is have T number of test cases which is how many time i will
obtain the average of "n" number of students in each test case and i need to display the average score for each test case and the highest mark in that test case and the name of student
If you can tell me the proper way to code this and explain why it has to be that way i will greatly appreciate it! I am lost
My code:
t = int(input("enter number of cases: "))
def casing(t):
for case in range (1, t+1):
n = int(input("enter number of students: "))
def studentmarks(n):
total = 0
student = "none"
for computetotal in range(1,n+1):
student = input("please enter student name: ")
mark = int(input("please enter mark: "))
total = total+ mark
highestmark = mark
if studentmark(n) > mark:
highestmark = mark
achieve = student
return highestmark, acheive
return total, studentmark()[0], studentmark()[1]
average = float((studentmarks(n)[0])/ n)
print("average: ", average, "highest: ",studentmark(n)[1], "student: ", studentmark(n)[2])
I think the code, as it is, would be much simpler to understand and debug without the function declarations. Unless you're doing functional-style programming (e.g. passing around function objects) there's rarely a good reason to use nested functions. Here you're defining the functions, then immediately calling them once, which is fairly pointless. So here's a simplified version of your code:
t = int(input("enter number of cases: "))
for _ in range (t):
total = 0
highest_mark = 0
best_student = "none"
n = int(input("enter number of students: "))
for _ in range(n):
student = input("please enter student name: ")
mark = int(input("please enter mark: "))
total = total+ mark
if mark > highestmark:
highestmark = mark
beststudent = student
average = total / n
print("average: {}, highest: {}, student: {}"
.format(average, highestmark beststudent))
I also eliminated the function named studentmark (with no "s") which your code was calling but never defined. I'm not sure if I correctly interpreted what it was supposed to be doing, but I think so. It certainly wouldn't have worked before.
There are a few reasons this isn't working - but the root cause seems to be because your highestmark is started off in the wrong place. It looks like you later expect the student name and mark to be in a tuple, which is a good idea - but you never actually make this tuple anywhere. So, make one, and call it highest - it replaces both the student and highestmark variables. Start it as None instead of "none" (which could actually be a valid student name!), so you have above the loop:
total = 0
highest = None
and change your "is this one higher than the highest" logic to this:
if highest is None or mark > highest[1]:
highest = (name, mark)
Read as "if there is no highest student yet, or this one has a higher mark than the current highest, this one is the highest". Then you'll want the return to be:
return total, highest[0], highest[1]
But, since you only have a small amount of data (enough that it is feasible to have a user type it in at a console), then you can simplify this logic quite a bit. Read all of the data for a particular test case into a list of (student, mark) tuples, and then use Python's builtins to do the calculations:
def studentmarks(n):
marks = []
for _ in range(n):
student = input("please enter student name: ")
mark = int(input("please enter mark: "))
marks.append(student, mark)
return marks
# Calculations
marks = studentmarks(5)
print('Average: ', sum(result[1] for result in marks)/len(marks))
print('Highest: ', max(marks, key=lambda s: s[1])
Seeding it with:
>>> marks
[('Fred', 4), ('Wilma', 10), ('Barney', 8), ('Wilma', 7), ('Pebbles', 6)]
Gives an average of 7.0, and a maximum of ('Wilma', 10).

Categories