Python: Input and Variables (Page 1 of 4 )
In our last article we covered the history of Python, the print command, working with strings and variables, and how to comment your code. In this episode we will learn how to retrieve input from users, work with variables, and if you are lucky, Loops.
So arise young knight and join me as we search for the Holy Grail of programming!
Variables Vary Very Vivaciously
The easiest way to describe a variable is to think of a box that holds information. You can store data in the box, you can take data out of the box and you can put different data in the box. Heck, if you don't get a programming job after reading this series, you can even live in a box.
Here is how you work with variables in Python:
#!/usr/local/bin/python
sometext = “I like to eat grits.”
some_number = 127
anothernumber = 113
totalnumbers = some_number + anothernumber
print sometext
print some_number
print totalnumbers
print some_number + anothernumber
print “some_number plus anothernumber is”, some_number + anothernumber
print sometext * 5
In the above example we create variables by assigning them a name and a value (i.e. sometext = “I like to eat grits”). We then print them out. Here is the output:
I like to eat grits.
127
150
150
some_number plus anothernumber is 150
I like to eat grits. I like to eat grits. I like to eat grits. I like to eat grits. I like to eat grits.
The code above should be mostly self-explanatory. The exception would be the statement: print sometext * 5. Because sometext holds a string value and not a mathematical one, the program writes the text contained in the sometext variable five times. When the * symbol is used in this manner it is known as the Repetition operator.
Next: Beating...I Mean Asking the User for Information >>
More Python Articles
More By James Payne