My code doesn't work - python

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.

Related

Command on python regarding age on a loop until a correct answer appears

I want to make a command on python in which I ask the user to enter correct age of my brother. If the age 23 is entered, the program terminates saying "Good job". Otherwise, the user is again asked the age of my brother. I cannot understand how to make such a program. Below is my best guess:
age = input("what is the age of your brother? ")
while age = 23:
print ("correct answer entered")
else:
print ("incorrect answer entered")
I am getting a syntax error
You need to ask for the age inside the loop, and end the loop when it's correct. And since input() returns a string, you need to compare it with a string, not an integer. To compare things you need to use ==, not =.
while True:
age = input("what is the age of your brother? ")
if age == '23':
print("correct answer entered")
break
else:
print("incorrect answer entered")

How do I properly use the less than and greater than sign in Python [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 6 years ago.
So I have the following function in my script:
def age():
global age
age = raw_input("Age: ")
if age == 14:
sleep(1)
print ("LOL, same")
elif age < 18:
sleep(1)
print ("This test is made for contestants older than ten")
introduction()
elif age > 18:
sleep(1)
print ("Geez grandpa, you sure are old")
When I run this, it registers every age I type as above 18 like so:
Could you tell me your age?
Age: 4
Geez grandpa, you sure are old
Why does it do this?
As raw_input returns the user input as a string type, you should cast it into int.
Change this :
age = raw_input("Age: ")
To:
age = int(raw_input("Age: "))
your raw_input is taken as string
age = raw_input("Age: ")
so you need to convert it into a integer value if you want to compare it against numbers..
age = int(raw_input("Age: "))

Making a variable integer input only == an integer in Python

Im trying to make my variable integer input to be only == to an integer, and if its not I want to print and error message. I have put this in a if statement. I always get an error when I input a string instead of my error message.
age = int(input("Enter age:"))
if age != int:
print("Not a number")
you have to use raw_input instead of input
if you want this to repeat until you have the correct value you can do this
while True:
try:
age = int(raw_input("Enter age:"))
except ValueError:
print("Not a number")
if age == desired_age: # note I changed the name of your variable to desired_age instead of int
break
I dont recommend you use variable names like int... its generally a bad practice
from the discussion i posted the link above:
age = input("Enter age:") # raw_input("Enter age:") in python 2
try:
age = int(age)
except ValueError:
print('not a number!')
the idea is to try to cast age to an integer.
your attempt of age != int will always fail; age is a string (or an int if you were successful in casting it) and int is a class.

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

How to Total a while loop?

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

Categories