Reputation: 1
I am new to Python and new to programming.
Can anyone tell me how I can code the following correctly?
name=raw_input("What is your name? ")
age=raw_input(" How old are you",name)
Upvotes: 0
Views: 184
Reputation: 32310
name = raw_input('What is your name? ')
age = raw_input('How old are you, %s? ' % name)
Or:
name = raw_input('What is your name? ')
age = raw_input('How old are you, {}? '.format(name))
The raw_input
function can't receive more than 1 argument. We can overcome this problem by using string formatting (see here and here for info on the different types of formatting).
Also, depending on what you want to do, you might also want to convert age
into an integer. We can do this:
age = int(age)
but if the user entered something else, like 'foobar'
, then you'll get an error. You can bypass this using a try/except
block, and using a while
loop so you can loop until you get a valid number.
name = raw_input('What is your name? ')
while True:
age = raw_input('How old are you, {}? '.format(name))
try:
age = int(age)
break
except ValueError:
print 'You entered an invalid age. Please try again.'
Upvotes: 2
Reputation: 5209
Always use type conversion. Anyway, the following code should do it:
name = str(raw_input('Enter your name:'))
string1 = 'Enter your age,' + name + ':'
age = int(raw_input(string1))
As you can see, i have the stored whatever i want to prompt into a string called string1 and then i have used it as the parameter to raw_input.
raw_input takes only one parameter. So, you can do it this way.
And i have used python 2.7 for this. If you are using
Upvotes: 0