Welcome to Python for Teens, Part 2. In this part, we will learn about variables, types, and if-statements.
This is where programming meets fun. Variables let you keep track of a number, some text, or many other different types. Speaking of which, we learn about many different types of variables.
Let’s start with variables. Fire up your python interpreter and we will start. (If you forget how to do that, look back at Part 1 of the tutorial.)
To set a variable, simply enter:
variable_name = 928
Now change it to:
As you can see, this prints out the number that we set it to: 928. Variables are used to keep track of things that change. For example, if I wrote a game and I wanted to keep track of score, I would use a variable.
Everything in python has a type. When you assigned the variable
variable_name, you assigned it to a number. In programming, a number is referred to as an integer.
When you type
print "Hello, World!", you are running a command called
"Hello, World!". The type of the code that is enclosed by quotes (double or single) is called a string. You can remember that a string is a string of letters and numbers.
Remember that “9″ and 9 are two different types. The first one is a string since it is enclosed by quotes, and the second one is an integer since it is just a number without quotes.
Finally, the last type you will learn is a boolean. This is either True or False. Note that a boolean must be capitalized and it must not have quotes (Or else it is a string).
If statements run some code only if a conditional is true. A conditional is a statement that returns a boolean. The most common conditional statements are listed below:
|==||Is equal to||5 == 5|
|>||Is greater than||6 > 5|
|<||Is less than||4 < 5|
|<=||Is less than or equal to||5 <= 5|
|>=||Is greater than or equal to||5 >= 5|
|!=||Is not equal to||“a” != 5|
Now, using any of these, you can form an if statement to run a block of code if the conditional is true. We can do this as shown:
if conditional: print "RUN BLOCK OF CODE"
Great! Now, let’s do a test using a useful program.
name="Julian" if name=="Julian": print "Hello Julian!"
This will check if the name is equal to “Julian”. If it is, then it will print Hello, Julian! Try running the program. As you can see, it prints out “Hello Julian!” In the next tutorial, we will talk about expanding the if statement, and getting some input from the user. Before that, please take the quiz below. If you get anything wrong, reread the part you missed.