Python: Input and Variables - Beating...I Mean Asking the User for Information (
Page 2 of 4 )
So now that we know everything there is to know about printing and we know about variables, let's learn how to get data from the user and work with it.
#!/usr/local/bin/python
print “Go no further!”
name = raw_input(“Who are you?”)
print “Did you say:”, name
The above code prints a statement: Go no further! Then it asks the user: Who are you? and prompts them for some text. When the user types in the text and presses enter, it then prints: Did you say: and appends the value of the variable name to the end.
Let's say the user entered in the name: The Knights Who Go Neep! This is what the code would print:
Go no further!
Who are you?
Did you say: The Knights Who Go Neep!
We use raw_input when we want to get textual input from a user. If we wanted to get a numeric value, we would use input, like so:
#!/usr/local/bin/python
age = input(“Enter your age: “)
print “You are”, age
print “If I were twice your age I would be: “, age * 2
Same principle as before. If the user had entered an age of 20, this would be the printout result:
Enter your age:
You are 20
If I were twice your age I would be 40
And of course we could always combine the two together:
#!/usr/local/bin/python
first_name = raw_input(“What is your first name?”)
last_name = raw_input(“What is your last name?”)
age = input(“How old are you?”)
print “Your full name is “, first_name + last_name
Print “And this is your age: “, age
If the user had answered Lando Calrissian 50, then the printout would be:
Your full name is LandoCalrissian
And this is your age: 50
When you use the + symbol with text it is called concatenating strings, or adding them to one another. You will note that the values in the concatenated sentence have no space. You must add one to the sentence like so:
#!/usr/local/bin/python
first_name = raw_input(“What is your first name?”)
last_name = raw_input(“What is your last name?”)
age = input(“How old are you?”)
print “Your full name is “, first_name + “ “ + last_name
Print “And this is your age: “, age
This will print:
Your full name is Lando Calrissian
And this is your age: 50