Python 1: Variables and I/O
By the end of this lesson you should be able to:
1. Describe what a variable is.
2. Identify the basic Data Types.
3. Write to the screen
4. Process User input.
Variables are a location in memory that can hold information. Variables always have a name and a type. Basic variable types that you will be using are:
int - Numbers without decimals. Like 6 or 7
float- Numbers that can have decimals. Like 3.14
string – A group of Characters. Like “dog”, “cat” or “4353 George K”
2 Weird things about Python:
1. In Python, you don’t need to “declare” variables you can just use them.
Note 1: the ‘=’ sign is used to assign a value to a variable.
Note 2: Variable names should:
· Be meaningful
· always start with a lower case letter
· subsequent words should be capitalized
2. Variables can change type in the middle of a program.
I don’t know of any other languages that do this… but Python lets you, for example, use a variable to hold an int for a while then you can start using it as string if you feel like it.
Getting User Input
The function raw_input() will get a value from the user. Use it like this:
This program gets the name from the user, stores it in userName and displays it on the screen.
Note: raw-input() will bring in the user’s value as a string. If you want to use it as a number you will need to convert it to an int or float like this.
Save each program in you unit 1 folder as a text document called A1Px where x is the program number. Then copy and paste it into the python interpreter. Use the # symbol in include your name and the program code at the top of your script.
Ex: #Tony Demello A1P1
Program 1 – Echo
Write a program that prompts the user to enter some words then echo it back on the screen.
Program 2 – The Multiplier
Prompt the user to enter 2 numbers, multiply them and report the result with an appropriate comment.
Program 3- Average Score
Prompt the user to enter 5 scores. Calculate the average and display the result.
Program 4- Madlib
Prompt the user to enter 3 nouns, 3 adjectives and 3 past tense verbs (ran, fell etc). Write a short story (3 sentences tops) that uses the user’s words. Something like this:
The adjective1 noun2 verb3 neatly on a adjective3 noun1. Suddenly it verb2 into a big pile of adjective 2 noun3. The adjective1 noun2 verb 1 all the way to its mom.
Show Mr.Kurz all 4 programs when you are finished.