Ok, I'm gonna explain this as best I can.
I am trying to make an if/else statement in python that basically informs the user if they put in the right age based on raw input, but I keep getting an error in terms of my if statement. Can I get some help?
from datetime import datetime
now = datetime.now()
print '%s/%s/%s %s:%s:%s' % (now.month, now.day, now.year, now.hour,now.minute, now.second)
print "Welcome to the beginning of a Awesome Program created by yours truly."
print " It's time for me to get to know a little bit about you"
name = raw_input("What is your name?")
age = raw_input("How old are you?")
if age == 1 and <= 100
print "Ah, so your name is %s, and you're %s years old. " % (name, age)
else:
print " Yeah right!"
change your if statement to this:
if age >=1 and age <=100:
two things:
if age >=1 and <=100 is missing age <=100
you are missing a : at the end
Here is the formatted and corrected code:
import datetime
now = datetime.datetime.now()
print '%s/%s/%s %s:%s:%s' % (now.month, now.day, now.year, now.hour,now.minute, now.second)
print "Welcome to the beginning of a Awesome Program created by yours truly."
print " It's time for me to get to know a little bit about you"
name = raw_input("What is your name?")
age = raw_input("How old are you?")
while int(age) < 1 or int(age) > 100:
print " Yeah right!"
age = raw_input("How old are you?")
print "Ah, so your name is %s, and you're %s years old. " % (name, age)
Also, double check indents and your logic for the age.
Related
Guys I tried a couple of ways to solve a problem I am having.
My program works well without decimal numbers.
I want to get an answer with decimal points.
So each time i type in the decimal point, there is an error.
This is what I tried:
from __future__ import division
def bmi (): ## bmi = body mass index
print " program to calculate person BMI"
name = raw_input(" Hi welcome , what is your name ? : ")
print " welcome %s " % name
weight = raw_input (" your weight(kg) : ")
height = raw_input ("your height (m): ")
bmi = int(weight)
bmi_1 = int(height)
if bmi/bmi_1**2 <= (25):
print " your ibm is : %d , you are not overweight "%( bmi/bmi_1**2)
elif bmi/bmi_1**2 >= 24:
print " your iibm is : %d , sorry you are overweight" % ( bmi/bmi_1**2)
else :
print " sorry mistake, try again "
float()
and
str()
Will do the trick.
I'm a new programmer and just starting off with Python. I have the following 2 questions, however, I decided to put them in one post.
When asking to input age, how do I force the program to only accept numbers?
The concept is that after the user has entered their age, the program would pick a random number between 1 and 100 and compare it to the user input, returning either "I'm older than you", "I'm younger than you" or "we are the same age".
# Print Welcome Message
print("Hello World")
# Ask for Name
name = input("What is your name? ")
print("Hello " + str(name))
# Ask for Age
age = input("How old are you? ")
print("Hello " + str(name) + ", you are " + str(age) + " years old.")
random.randint(1, 100)
Try the following
import random
# Print Welcome Message
print("Hello World")
# Ask for Name
name = input("What is your name? ")
print("Hello " + str(name))
# Ask for Age
while True: # only numbers
try:
age = int(input("How old are you? "))
except:
pass
print("Hello " + str(name) + ", you are " + str(age) + " years old.")
t=random.randint(1, 100)
if t==age:
print("we are the same age") #compare ages
if t<age:
print("I'm younger than you")
if t>age:
print("I'm older than you")
Hi you can try this simply.
import random
name = input("What is your name? ")
print("Hello " + str(name))
while True :
try :
age = int(input("How old are you? "))
break
except :
print("Your entered age is not integer. Please try again.")
print("Hello " + str(name) + ", you are " + str(age) + " years old.")
randNumber=random.randint(1, 100)
if randNumber > age :
print("I am older than you")
if randNumber < age :
print("I am younger than you")
else :
print("we are the same age")
Only made few changes to existing code with modifications asked.
import random
# Print Welcome Message
print("Hello World")
# Ask for Name
name = input("What is your name? ")
print("Hello " + str(name))
# Ask for Age
while True:
try:
age = int(input("How old are you? "))
except ValueError:
pass
print("Hello " + str(name) + ", you are " + str(age) + " years old.")
my_random = random.randint(1, 100)
if my_random > age:
print("Im older than you")
elif my_random < age:
print("I'm younger than you")
else:
print("We are the same age")
Includ a try block around the age part. If the user inputs an non-int answer then it will just pass. I then saved the random int that you generated it and compared it to the age to find if the random int was greater than the age.
To answer your first question, use int() as such:
age = int(input("How old are you? "))
This will raise an exception (error) if the value is not an integer.
To answer your second question, you may store the random number in a variable and use it in comparison to the user's age, using conditional statements (if, elif, else). So for instance:
random.seed() # you need to seed the random number generator
n = random.randint(1, 100)
if n < age:
print("I am younger than you.")
elif n > age:
print("I am older than you.")
else:
print("We are the same age.")
I hope this answers your question. You can refer to the official Python docs for more info on conditional statements.
My guess is that you should convert the variable age into integer. For example:
age = input("How old are you?")
age = int(age)
This should work.
The answer to the 1st question.
x = int(input("Enter any number: "))
To force the program to enter number add int in your input statement as above.
This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 7 years ago.
I have the following script:
#! /usr/bin/python3
name1 = input('Enter the name of first person ')
name2 = input('Enter the name of second person ')
age1 = int(input("Enter the first age "))
age2 = int(input('Enter the second age '))
print('%s' %name1, 'is %d' %age1, 'years and %s' %name2, 'is %d' %age2, 'years')
agex = age1
age1 = age2
age2 = agex
print('Now we swap ages: %s' %name1, 'is %d' %age1, 'years and %s' %name2, 'is %d' %age2, 'years')
What I'd want is to ask for ages including the name entering in the name questions, I mean, something like:
age1 = int(input("Enter the age of", name1))
But that does not work...
So if you answer as first personame John, so you should get:
Enter the age of John:
How can I do that?
Try
age1 = int(input("Enter the age of {}:".format(name1)))
or if you prefer string interpolation:
age1 = int(input("Enter the age of %s:" % name1))
input() takes a string as its parameter so just create a string with your variable. ie, if firstname == 'John':
lastname = input('What is the last name of '+firstname+': ')
age1 = int(input("Enter the first age " + name1))
You need to concatenate the strings. You were so close ...
No mather what input I give I get the output "I think you're to old to go on an adventure. Your adventure ends here."
Like if I input 17 I get "I think you're to old to go on an adventure. Your adventure ends here." and if I input 18-59 I get "I think you're to old to go on an adventure. Your adventure ends here."
while True:
age = raw_input("\n So tell me " + str(name) + ", how old are you?: ")
if age.isdigit() == False:
print "\n Please, put only in numbers!"
time.sleep(3)
elif age < 18:
print "\n %s. A minor. You got to be atleast 18 to go on this adventure. Your adventure ends here." % age
time.sleep(7)
exit(0)
elif age >= 60:
print "\n %s. I think you're to old to go on an adventure. Your adventure ends here." % age
time.sleep(5)
exit(0)
else:
print "\n %s. You're starting to get old." % age
break
You need to compare your input as an int
age = int(raw_input("\n So tell me " + str(name) + ", how old are you?: "))
Otherwise you are comparing a str to an int. See the following example
>>> 5 < 10
True
>>> type(5)
<type 'int'>
>>> '5' < 10
False
>>> type('5')
<type 'str'>
In Python 2.x, comparing values of different types generally ignores the values and compares the types instead. Because str >= int, any string is >= any integer. In Python 3.x you get a TypeError instead of silently doing something confusing and hard to debug.
The problem is that raw_input always returns a string object, and those don't really compare to int types. You need to do some type conversion.
If you want to use isdigit to test if the input is a number, then you should proceed this way:
while True:
age = raw_input("\n So tell me " + str(name) + ", how old are you?: ")
if age.isdigit() == False:
print "\n Please, put only in numbers!"
time.sleep(3)
elif int(age) < 18:
print "\n %s. A minor. You got to be atleast 18 to go on this adventure. Your adventure ends here." % age
time.sleep(7)
exit(0)
elif int(age) >= 60:
print "\n %s. I think you're to old to go on an adventure. Your adventure ends here." % age
time.sleep(5)
exit(0)
else:
print "\n %s. You're starting to get old." % age
break
However, you can simplify the code a little by converting to an integer right away, and just catching the exception if it's an invalid string:
while True:
try:
age = int(raw_input("\n So tell me " + str(name) + ", how old are you?: "))
if age < 18:
print "\n %s. A minor. You got to be atleast 18 to go on this adventure. Your adventure ends here." % age
time.sleep(7)
exit(0)
elif age >= 60:
print "\n %s. I think you're to old to go on an adventure. Your adventure ends here." % age
time.sleep(5)
exit(0)
else:
print "\n %s. You're starting to get old." % age
break
except ValueError:
print "\n Please, put only in numbers!"
time.sleep(3)
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