what is wrong with python my python code in while loop? - python

I don't know what is the error of my code can anyone help me to fix this code.
age = ""
while int(len(age)) == 0:
age = int(input("Enter your age: "))
print("Your age is " + age)

You wanted a string for age but you transformed this age into an integer inside your loop :)
You can write :
age = ""
while age == "":
age = input("Enter your age: ")
print("Your age is " + age)

In Python, "" and 0 (and values like None and empty containers) are considered "falsey". Not necessarily the same thing as False but logically treated like False.
So you can simplify your while loop:
age = ""
while not age:
age = input("Enter your age: ")
print("Your age is " + age)

You cast age to be an int inside of your while loop, while using the len(age) as the comparison.
int does not have a length.
You want to wait to cast age until you are outside of the loop, or in this situation, don't cast it at all.
age = ""
while len(age) == 0:
age = input("Enter your age: ")
print("Your age is " + age)

Related

creating a holiday programme?

I have been set a task and it is the following, I was wondering would my code would work?
write a program to ask for a name and an age.
when both values have been entered, check if the person is the right
age to on an 18-30 holiday(they must be over 18 and under 31
name = input("What is your name? ")
age = int(input("How old are you ? "))
if 18 <= age < 31:
print("Hello",name,"welcome to this holiday.".format(name))
else:
print("Sorry",name,"you are not old enough to go on this holiday. ")
well actually it works but you don't need the format part
name = input("What is your name? ")
age = int(input("How old are you ? "))
if age >=18 and age <31:
print("Hello",name,"welcome to this holiday.")
else:
print("Sorry",name,"you are not old enough to go on this holiday. ")
if you want to use format you can do this
print("Hello {name} welcome to this holiday.".format(name=name))
Code works perfect, but you have a useless format
Just use format, not the , part.
name = input("What is your name? ")
age = int(input("How old are you ? "))
if 18 <= age < 31:
print("Hello {name} welcome to this holiday.".format(name))
else:
print("Sorry {name} you are not old enough to go on this holiday.".format(name))
Or if you don't like to do format
name = input("What is your name? ")
age = int(input("How old are you ? "))
if age >=18 and age <31:
print("Hello",name,"welcome to this holiday.")
else:
print("Sorry",name,"you are not old enough to go on this holiday. ")

Python input ranges and types of input

How do i get it to not keep repeating after a sucessfull trial
while age == "": #make it only except numbers so it wont give an error
age = input("How old are you " + name + "? ")
if age.isdigit() == False:
print("Only digits are allowed!")
age = ""
if age not in range(0,99):
print ("Age must be between 0,90!")
age = ""
convert the input to int to check it's value:
while age == "": # make it only except numbers so it wont give an error
age = input("How old are you " + name + "? ")
if not age.isdigit():
print("Only digits are allowed!")
age = ""
elif int(age) not in range(0, 99):
print("Age must be between 0,99!")
age = ""
Your variable "age" is a string - that's what the "input" function returns. Later you check to see if it's in the range (0, 90), but the "range" function returns a sequence of integers. So "age" - a string - is NEVER in the sequence.
Here is one way to fix it:
while age == "": #make it only except numbers so it wont give an error
age = input("How old are you " + name + "? ")
if age.isdigit() == False:
print("Only digits are allowed!")
age = ""
if int(age) not in range(0,99):
print ("Age must be between 0,90!")
age = ""

why cant I get this if statement to show? [duplicate]

This question already has answers here:
Comparing numbers give the wrong result in Python
(4 answers)
Closed 3 years ago.
so I need to make sure the information I am inputting shows if its less than, greater than, or equal too.
not sure if the variable is messed up or not.
here is the code:
#the main function
def main():
print #prints a blank line
age = getAge ()
weight = getWeight()
birthMonth = getMonth()
print
correctAnswers(age, weight, birthMonth)
#this function will input the age
def getAge():
age = input('Enter your guess for age: ')
return age
#thisfunction will input the weight
def getWeight():
weight = input('Enter your guess for weight: ')
return weight
#thisfunction will input the age
def getMonth():
birthMonth = raw_input('Enter your guess for birth month: ')
return birthMonth
#this function will determine if the values entered are correct
def correctAnswers(age, weight, birthMonth):
if age <= 25:
print 'Congratulations, the age is 25 or less.'
if weight >= 128:
print 'Congatulations, the weight is 128 or more.'
if birthMonth == 'April':
print 'Congratulations, the birth month is April.'
#calls main
main()
input() function returns a string. Before performing the integer comparison you are trying to do, you have to convert string.
For example:
def getAge():
age = input('Enter your guess for age: ')
return int(age)
I have edited your code so that it will work correctly.
def main():
print #prints a blank line
age = getAge()
weight = getWeight()
birthMonth = getMonth()
print()
correctAnswers(age, weight, birthMonth)
#this function will input the age
def getAge():
age = input('Enter your guess for age: ')
return age
#thisfunction will input the weight
def getWeight():
weight = input('Enter your guess for weight: ')
return weight
#thisfunction will input the age
def getMonth():
birthMonth = raw_input('Enter your guess for birth month: ')
return birthMonth
#this function will determine if the values entered are correct
def correctAnswers(age, weight, birthMonth):
if int(age) <= 25:
print('Congratulations, the age is 25 or less.')
if int(weight) >= 128:
print('Congatulations, the weight is 128 or more.')
if birthMonth == 'April':
print('Congratulations, the birth month is April.')
#calls main
main()

Simple Python "if", "elif", "else"

Making a "Mad Libs" style thing in Python for class, it's my first day, I've already picked up most of what I needed to know, but I'm not sure how to go about using the "if", "elif", "else" things. Here's what I have so far, basically, when the age is input I want it to choose if the person is an adult or a kid.
print "welcome to your short story"
name = raw_input("Input your name: ")
age = raw_input("Input your age: ")
if age > 21:
age = "adult"
elif age < 21:
age = "kid"
print "My name is ",name,"and I am a " ,age,"year old ",age
1) You are overriding the inputted age with strings adult of kid.
2) You have to handle the case when age equals 21.
3) The age input needs to be converted to an integer.
Let's rewrite your code, and see how we can improve:
print "welcome to your short story"
name = raw_input("Input your name: ")
# Convert the input to an integer.
age = int(raw_input("Input your age: "))
# This is the status variable being either adult or child
# before you were overriding age variable with adult or kid
status = ""
# Also, you have to handle the case where the age equals 21, before
# you were just checking if it is less or greater than 21
if age >= 21:
status = "adult"
elif age < 21:
status = "kid"
print "My name is ", name ," and I am a " , age ," year old " , status
I realized I needed a different value and have changed it.
print "welcome to your short story"
name = raw_input("What is your name?: ")
age = raw_input("How old are you?: ")
sex = raw_input("Are you a boy or a girl?: ")
if age > 21:
targetAge = "adult"
elif age < 21:
targetAge = "kid"
print "My name is ",name,"and I am a " ,age,"year old ",targetAge,"."
So, basically, when it is printed, it should read as "My name is _____ and I am a __ year kid/adult." Depending on the number they've input. The reason I'm not using the int() function is because that was never mentioned, this is literally the first day of class, so I'm going by what the instructor has gone over.
As suggested by foxygen, the int function is needed to convert your input from a string to an int
age = int(raw_input("Input your age: "))
There is a difference between the characters "1", "2", "3" and so forth, and the numbers 1, 2, 3, and so forth. Some languages try to convert for you, but python will not do this, so you end up comparing "32" to 21, which is an apples-to-oranges comparison.
Also, while you're safe in this particular instance, you'll notice how you're reassigning age while you're still computing based on its original value. This is not generally safe, and you would be better off assigning to a new variable:
if age > 21:
age_label = "adult"
elif age < 21:
age_label = "kid"
else:
age_label = "person" # in case a 21 year old uses your program
You're safe in this case because the if/else construction will only ever execute one branch, but it's best not to get in the habit of rewriting the input value while you're still consulting it.
print "Welcone to your Story"
name = raw_input("Please enter yout name: ")
age = int(raw_input("please enter your age: "))
if age >= 21:
status = "an adult"
else:
#enter code here
status = "a kid"
print "My name is %r , I am %r and I am %r years old" %(name,status,age)

Simple raw_input and conditions

I created the simple code:
name = raw_input("Hi. What's your name? \nType name: ")
age = raw_input("How old are you " + name + "? \nType age: ")
if age >= 21
print "Margaritas for everyone!!!"
else:
print "NO alcohol for you, young one!!!"
raw_input("\nPress enter to exit.")
It works great until I get to the 'if' statement... it tells me that I am using invalid syntax.
I am trying to learn how to use Python, and have messed around with the code quite a bit, but I can't figure out what I did wrong (probably something very basic).
It should be something like this:
name = raw_input("Hi. What's your name? \nType name: ")
age = raw_input("How old are you " + name + "? \nType age: ")
age = int(age)
if age >= 21:
print "Margaritas for everyone!!!"
else:
print "NO alcohol for you, young one!!!"
raw_input("\nPress enter to exit.")
You were missing the colon. Also, you should cast age from string to int.
Hope this helps!
With python, indentation is very important. You have to use the correct indentation or it won't work. Also, you need a : after the if and else
try:
if age >= 21:
print #string
else:
print #other string
Firstly raw_input returns a string not integer, so use int(). Otherwise the if-condition if age >= 21 is always going to be False.:
>>> 21 > ''
False
>>> 21 > '1'
False
Code:
name = raw_input("Hi. What's your name? \nType name: ")
age = int(raw_input("How old are you " + name + "? \nType age: "))
The syntax error is there because you forgot a : on the if line.
if age >= 21
^
|
colon missing

Categories

Resources