Thursday, 24 March 2011

Python: Interaction and Variables

The majority of programs require some form of question and answer based interaction. And in Python it is a must know, it is also very easy to get to grips with too.

All variables have to be defined so they can be called up at a later stage in your program, this itself is not overly useful (other than perhaps when a large variable consistently comes up, like Pi).

This is no different with variables that need interaction. It is used so that whatever value the user inputs can be called up at a later point, makes sense right? There are only two main things you need to remember when setting interactive variables is whether the answer you want will be numerical or text based.
name = raw_input ("What is your name? ")
age = input ("How old are you? ")
The key differences here are 'raw_input' and 'input'. You use 'raw_input' for text based data and 'input' for numerical data, easy. The name is just what you apply to the variable that you use when you call it up, just remember that once the user inputs a name to this interactive variable it will not automatically be displayed, in order to do that you must print their variable, my example should make more sense.
name = raw_input ("What is your name? ")
age = input ("How old are you? ")
print "Hello,", name, age, "is a great age!"
This small program would look like this when ran:
What is your name? Mersenne
How old are you? 16
Hello, Mersenne 16 is a great age!
Remember how that if you want to show the solution to a mathematical problem you separate the problem with a comma? Well that's the same with variables you have defined, if you can remember these few simple rules you can begin to create more complex programs that involve user interaction.

No comments:

Post a Comment