How to Total a while loop? - python

Purpose is to put diff ages in, if -1 is entered then the program stops, my totaling statement is wrong. Will Someone please help me fix it.
Totalage = 0
age = 0
print "Enter you Family member's ages!"
age = raw_input ("Enter an age ")
while age != -1:
age = input("Enter an age ")
Totalage = Totalage + age
print Totalage

There are two problems with your code
You are skipping your first input, and you are not adding it to your total
You are adding the last terminator input -1 to your Total.
Just Change the order of the statements in your while loop
age = int(raw_input ("Enter an age "))
while age != -1:
Totalage = Totalage + age
age = int(input("Enter an age "))
Also note, raw_input, in general returns a string, which needs to be converted to int before you may want to calculate on it.
Itertools Provide some wonderful tools, and for fun, I tried coding the above while loop with itertools.takewhile
>>> from itertools import count, takewhile
>>> sum(takewhile(lambda x: x != -1,
(int(raw_input("Enter an age ")) for e in count())))
Enter an age 20
Enter an age 30
Enter an age 40
Enter an age 50
Enter an age -1
140

The problem is that your while condition is working properly, but you don't trigger it until your next run through. Therefore if your input is -1, this:
age = input("Enter an age ")
Totalage = Totalage + age
Will decrement the age by -1 and on the next loop through it will exit the loop. In order to adjust, you could do something like this. Note that one adjustment is changing input to raw_input (usually a better practice in Python 2.x, and Python 3.x changes the behavior of input to match it):
Totalage = 0
print "Enter you Family member's ages!"
while True:
age = int(raw_input("Enter an age "))
if age == -1:
break
Totalage += age
print Totalage
while True puts you into a continuous loop, and you break out of it whenever the value -1 is entered. Also, the int here is what you need to do to convert the number to an integer. This will fail if somebody enters an incorrect value (like 'ten', for instance), so if that is a concern you would have to add some additional error handling.

The problem is that you're adding -1 to Totalage before the loop condition is checked. You could rewrite the loop something like this instead:
print "Enter you Family member's ages!"
Totalage = 0
while True:
age = input("Enter an age ")
if age == -1:
break
Totalage += age
print Totalage

Related

How would I add user input to a list? Python [duplicate]

This question already has an answer here:
python add users input to an empty list using a for loop
(1 answer)
Closed 2 years ago.
I'm looking to write a function that will prompt the user for a series ages and store them in a list and to stop when the age is <= 0 and find the average age. I've been struggling on how to add the user input into a list. I can't figure out which type of loop to use.
age = int(input("Please enter an age (or 0 to quit): "))
age_list = []
def get_ages():
list = age.split()
if age >= 0:
You'll need to use a loop here,
try something like this:
age_list = []
while True:
age = input("Please enter an age (or 0 to quit): ")
if int(age) <= 0:
break
else:
age_list.append(int(age))
print(str(sum(age_list) / len(age_list)))
also, welcome to StackOverflow! :)
One solution is to iterate forever until a 0 or negative number is input. Something like this should work:
age_list = []
while True:
age = int(input("Please enter an age (or 0 to quit): "))
if age <= 0:
# this will break out of the loop
break
else:
age_list.append(age)
print(age_list)
If you need a function, you can do it like this:
def get_age():
age_list = []
input_age = True
while input_age:
age = int(input("Please enter an age (or 0 to quit): "))
if age > 0:
age_list.append(age)
else:
input_age = False
return age_list
if __name__ == '__main__':
print(get_age())

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.

My code doesn't work

I have a problem with my code. When I enter numbers it still shows "only numbers are allowed". How can I fix it?
This is the code:
age = input("What's your age? ")
while age != age.isdigit():
print("only numbers are allowed")
age = input("What's your age? ")
age = int(age)
The expression age.isdigit() does not return a number. It returns either True or False. Therefore the condition age != age.isdigit() is comparing a string value in age to boolean True or False and this will never evaluate as true.
If you want the loop to continue while age is not a value all-digit string, you can use while not age.isdigit().
You might also consider writing it this way:
while true:
age = input("What's your age? ")
if age.isdigit():
break
age = int(age)
which I find easier to understand since you don't have to repeat the input prompt and you're not using a negative condition.

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))

Easier way to find if string is a number in Python 3 [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
I'm quite new to programming. I was trying to figure out how to check if a user input (which get stores as a string) is an integer and does not contain letters. I checked some stuff on the forum and in the end came up with this:
while 1:
#Set variables
age=input("Enter age: ")
correctvalue=1
#Check if user input COULD be changed to an integer. If not, changed variable to 0
try:
variable = int(age)
except ValueError:
correctvalue=0
print("thats no age!")
#If value left at 1, prints age and breaks out of loop.
#If changed, gives instructions to user and repeats loop.
if correctvalue == 1:
age=int(age)
print ("Your age is: " + str(age))
break
else:
print ("Please enter only numbers and without decimal point")
Now, this works as shown and does what I want (ask the persons age untill they enter an integer), however is rather long for such a simple thing. I've tried to find one but I get too much data that I don't understand yet.
Is there a simple shorter way or even a simple function for this to be done?
You can make this a little shorter by removing the unnecessary correctvalue variable and breaking or continue-ing as necessary.
while True:
age=input("Enter age: ")
try:
age = int(age)
except ValueError:
print("thats no age!")
print ("Please enter only numbers and without decimal point")
else:
break
print ("Your age is: " + str(age))
Use isdigit()
"34".isdigit()
>>> "34".isdigit()
True
>>> "3.4".isdigit()
False
>>>
So something like this:
while True:
#Set variables
age=input("Enter age: ")
#Check
if not age.isdigit():
print("thats no age!")
continue
print("Your age is: %s" % age)
age = int(age)
break
This works for nonnegative integers (i.e., without a sign marker):
variable = ''
while True:
variable = input("Age: ")
if variable.isdigit():
break
else:
print("That's not an age!")
variable = int(variable)
The idea is that you loop continuously until the user inputs a string that contains only digits (that's what isdigit does).
Your code can be made a bit shorter like this. I was going to suggest changing your correctvalue variable from an integer 1 or 0 to a boolean True or False but it is redundant anyway. continue can be used to repeat the loop as necessary.
while True:
age = input("Enter age: ")
try:
age = int(age)
except ValueError:
print("That's no age!")
print("Please enter only numbers and without decimal point")
continue
print ("Your age is: " + str(age))
break

Categories