Coding Curriculum - Python

Getting Input from User

You will need to write some questions and answers to make a quiz, so before you can play you need to tell the computer what you want to study, and how many questions you have. The easiest way to tell the computer information is by using the raw_input() function. You give this function parameters, such as "Can I have that cupcake?", and the program will wait for you to type an answer before it moves on.

raw_input("Can I have that cupcake?")
# Type in your answer:
Yes!

That piece of code will work great, but the answer 'Yes!' isn't stored anywhere. This means that you can't use it further in your code, so you need to create a variable to store the answer. This is much more useful:

answer = raw_input("Can I have that cupcake?")
# Type in your answer:
Yes!
# Now you can reuse the variable 'answer', for example:
print answer

However using raw_input() will only take the user input as a String (a chain of characters), so if you give it a number it will think of it as a character and not an integer. This is why we have a more powerful function called input(). This analyses the answer you give the computer, and if it is a number, then it will be stored as an integer. For example, this would not work:

perPerson = raw_input("How many cupcakes can we each have?")
#You type in: 2, the computer will think '2'
numberOfPeople = 5
totalCupcakes = numberOfPeople * perPerson
# Error, because perPerson isn't a number! It's actually a character

But this would:

perPerson = input("How many cupcakes can we have?")
#You type in: 2
numberOfPeople = 5
totalCupcakes = numberOfPeople * perPerson
# Hooray! perPerson was interpreted as an integer by input()

Alright, so now you know how the computer can ask for information from the user. Now let's look at where we can store some of this information.