Creating Variables

Variables store and label information.
They also can change in value (like your score and the number lives you have left change in a game).
Varaibles are how we'll keep track of things like score and lives left in the games we create.


Opening IDLE3

Open the python shell. Then create a new file. You should now have two windows open. drag each one to each end of the screen so that it looks like this:

Write your code in the window on the right.

How to Create a Variable

Write the code below in the shell. This produces a varialbe called score and assigns it the value 0. Run the code and see what happens

Now add the following line of code. Run the code again and see what happens
It should something like below. The code you write in the window on the right side executes in the window on the left side.
Play around some more with the code. Try changing the variable name and the value


Number Variables

As you saw above, variables can store numbers that you can do math with!

Symbol  Meaning 
+ add
- subtract
* multiply
/ divide

Type this code into the shell. It uses two variables, x and y, which store integers to perform a simple calculation. Can you guess what the code will print out? Run the code to see the answer

Change the values for xand y in your code and see what output you get!


Strings

A string is any data made up of a sequence of characters (letters, numbers, or symbols). In Python, Strings are always surrounded by quotation marks (for example, "Hello!"). Words and sentences are strings.


String Variables

Strings can be assigned to variables. Type this code into the shell window. It assigns the string John to the name variable and then displays it.
Variables can be combined to create new ones. For example, you can add two strings and store the combination in a new variable using the + sign. Type this code into the shell to try it out.
Try changing the greeting and the name to make a new message

Challenge

For some programs, it’s useful to be able to count the number of characters in a string. You can do this using the len() function. A function is a useful operation that contains multiple lines of code, so you don’t have to rewrite them.
To find out the number of characters in the string Hello, John, type this line of code into the shell after you’ve created the string, then hit run the code. What do you think the output will be?

Copyright © KX Technology Group, LLC. All Rights Reserved.