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 Replit

Go to Replit, create another pygame repl, and name it variables


How to Create a Variable

Clear out the sample code in main.py and write the code below. This produces a varialbe called score and assigns it the value 0. It then prints out the value for score. Run the code and see what happens

It should something like below:


Play around some more with the code. Try changing the variable name and the number 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. 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 in main.py. 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 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 after you’ve created the string, then hit run the code. What do you think the output will be?

Activity

You've probably heard or seen the phrase "The quick brown fox jumped over the lazy dog". It's basically a story with characters and an event. What if we replaced the fox, the dog, and what the fox did with other words? We'd have a completely different story! Write a program that prints out the above story, but replaces the following words in the story with variables.

Word  Variable 
quick adj_1
brown adj_2
fox noun_1
jumped verb
lazy adj_3
dog noun_2

It should look something like

"The " + adj_1 + " " + adj2 + " " + noun_1 +  " " + verb + " over the " + adj_3 + " " + noun_2
                            
Set the variables to whatever values you want. Notice how it changes the story. Once you've done that, try creating your own story with variables that can equal anything you want!

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