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)
Related
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)
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. ")
Teaching myself Python out of a book and I'm stuck on this exercise:
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.
I know how to make it work without using a loop but I am a uncertain how to make it work using a while loop. Any advice or examples would be greatly appreciated.
One way to do this would be an infinite loop. Don't forget to include a break condition, otherwise you won't be able to exit your program gracefully.
while True:
userinput = int(input())
if userinput < 0:
break
# your if logic goes here
I was able to figure it out on my own
prompt = "\nEnter 'quit' when you are finished."
prompt += "\nPlease enter your age: "
while True:
age = input(prompt)
age = int(age)
if age == 'quit':
break
elif age <= 3:
print("Your ticket is free")
elif age <= 10:
print("Your ticket is $10")
else:
print("Your ticket is $15")
One way of doing it would be creating an infinite loop like such:
price = -1
while price == -1:
try:
age=int(raw_input('Age: '))
except ValueError:
print "Not a number, try again."
continue
if age <= 3:
price = 0
elif age > 3 and age < 12:
price = 10
else:
price = 15
print "The price will be "+str(price)+"$."
Note:
Rename raw_input() to input() if you are using Python 3.
I know this is an old question but none of the answers seemed great. So here's my solution to 7-5/ 7-6
loop = True
#while loop = true run 'while loop'
while loop:
#Print message
print ('Please enter your age.')
#receive input from user
age = raw_input()
#check if the user input "quit" if so end loop. Break ends program but should be replaceable by
#if age == 'quit':
# loop = False
#resulting the the same effect (ending loop)
if age == 'quit':
break
#Convert age input by user to int so it is recognized as a number by python
age = int(age)
#If/ elif pretty self explanatory
if age < 3:
price = 5
elif age < 12:
price = 10
elif age > 12:
price = 15
else:
print('Input not recognized')
break
#Print ticket price based on age and ask user if they need another price/inform them how to exit program
print('Your ticked price is $' + str(price) + '.')
print('\n If you would like to check the price for another person please enter their age now or type "quit" to exit')
The formatting might be a little off since it pasted oddly. I tried to explain what everything does. Also I use 2.7 instead of 3 so if you're using python 3 replace raw_input() with input()
Hopefully this answer was helpful to some on. GL with programming.
prompt = "How old are you? "
prompt += "\nEnter 'quit' when you are finished. "
while True:
age = input(prompt)
if age == 'quit':
break
age = int(age)
if age < 3:
print("Your ticket is free. Congratulations")
elif age < 13:
print("Your ticket is $10 dollars")
else:
print("Your ticket is $15 dollars")
prompt = "\nPlease enter 'done' when finished! "
prompt += "\nPlease enter your age:"
while True:
try:
age = input(prompt)
if age == 'done':
break
age = int(age)
if age <= 3:
print("Free ticket")
elif age in range(4, 12):
print("You must pay 10$")
elif age >= 12:
print("You must pay 15$")
except ValueError:
continue
I am fairly new to python but already i am a very big fan of the language, i am currently working with some tutorials as well as doing a lot of reading and trying to apply what i read.
Been using this site for a while but this my first time posting
I am working on a problem that requires me to modify a function so that a list of tuples are returned. I have tried everything that i know and i am not having any success, this is as far as i have got.
this is my function:
def ask_age ():
newList=[]
count = int (input( "Enter Count "))
if count >7:
count=7
for n in range (count):
age = int(input( "Please Enter age = " ))
if age > 0:
newList.append(age)
print ("You are", age, "years old")
if age < 16:
print ("This is a child")
elif age >= 18:
print ("This is an Adult")
else:
print ("This is a youth")
print(newList)
when I run:
ask_age()
and this is the result
Enter Count 4
Please Enter age = 15
You are 15 years old This is a child
Please Enter age = 17
You are 17 years old This is a youth
Please Enter age = 18
You are 18 years old This is an Adult
Please Enter age = 25
You are 25 years old This is an Adult
[15, 17, 18, 25]
As I mentioned, I now need to modify the function so that instead a list of tuples is returned that looks like so:
[(15, 'This is a child'), (17, 'This is a youth'), (18, 'This is an Adult'), (25, 'This is an Adult')]
Any help would be greatly appreciated
change the part that's now
if age > 0:
newList.append(age)
print ("You are", age, "years old")
if age < 16:
print ("This is a child")
elif age >= 18:
print ("This is an Adult")
else:
print ("This is a youth")
to be instead:
if age > 0:
if age < 16:
newList.append((age, "This is a child"))
elif age >= 18:
newList.append((age, "This is an Adult"))
else:
newList.append((age, "This is a youth"))
and the print(newList) at the end to be return newList instead.
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