I like to think of a variable as a jar with a label on it.
In your math class, when you want to use x, you just write it down, and whoever reads it, understands that x is a variable.
Most programming languages require the user to declare a variable and assign a type. Let's look at that in Java or C / C++:
int x = 10; // Build a variable called x, of the 'type' integer, and set it's starting value to 10.
This isn't so in python:
>>> x = 5 # assign the value 5 to the variable x
What is a variable? We've covered this before, but let's think about it again.
A variable is a container with a label that holds a value.
Making a variable in Python is easy:
variable_name = some_value
Variables can be considered either as 'constant' or as 'variable' (as in changing). Python doesn't distinguish between the two as some languages do.
When we think of the freezing point of water, we know it's 0 degrees. It's not going to change unless we add something to the water. Therefore the freezing point of water is constant.
How does this work in Python?
Build a variable called freezing_point and set its value to 0:
freezing_point = 0
print(freezing_point)
Python doesn't care if variables are constants or variable!
Python does have constant values you can use. These 2 examples come from the math module (or library):
math.pi - The mathematical constant π = 3.141592...
math.e - The mathematical constant e, aka Euler's Number = 2.718281...
What about variables that change, like your age?
Build a variable called my_age and set its value to 62:
my_age = 62
print(my_age)
What two things did we just learn?
Building variables in Python is easy:
variable_name = value
Python doesn't care if variables are constants or variable, they are both built the same way:
variable_name = value
Technically speaking there are two things happening on that one line:
On the left hand side of the '=' is the Initialization (making) of the variable.
On the right side of the '=' is the Assignment of a value to that variable.
The '=' is called the assignment operator (more about it, later).
Like I mentioned earlier, in most other languages, you have to also include the variable's type. Python supports dynamic typing, so this isn't a concern for you.
So far our variables have held numbers. Can Python hold words or single characters?
Let's build some variables to see what we can get:
snacks_packed = 2
distance_to_school = 3.5
water_bottle_full = False
cell_phone_brand = 'Android'
Let's use the print() function to see what's in those variables:
print(snacks_packed)
print(distance_to_school)
print(water_bottle_full)
print(cell_phone_brand)
Looks like all of our values are there. But what TYPE are they?
We can use the type() function to let us know.
Because Python supports dynamic typing, it can alter a variable's type depending on how it's being used. This is a a powerful feature of Python.
Build a variable called my_name and set its value to Bobo, then check the type:
my_name = 'Bobo'
print(my_name)
print(type(my_name))
What are some types that you will need to know?
Let's check on the type of those previously made variables:
print(type(snacks_packed)) # Should be an int
print(type(distance_to_school)) # Should be a float
print(type(water_bottle_full)) # Should be a boolean
print(type(cell_phone_brand)) # Should be a string
NOTE: If you call the type() from the Python interpreter, it will output the type. If you call type() from with in source code, you must wrap it in a print() to see the output.
What do the different types mean?
int holds whole numbers only
float holds floating point numbers. Numbers with a decimal
boolean holds the logical values True or False
string holds words, single letters, symbols, and numbers that aren't numbers (more about that in a bit)
I've said that variables are containers with labels. We can refer to that label as a name. There are a few rules for naming variables:
lower case only. This is a coding / programming convention. A convention is a way something is usually done. A programming convention is a way of doing things across many languages. Python is case sensitive, so be aware that the variable cats is different than the variable caTs, or Cats.
Variable names tend to be noun based, that is 'things'. We may want to hold a player_name, or the player_score.
Variable names must begin with a letter, not a number.
If multiple words are used, separate them with an underscore character '_'.
It's a generally good idea to keep symbols out of variable names. Python should catch these and provide you with a error message like this: SyntaxError: invalid syntax
Variable names cannot be reserved keywords.
The following words have specific functionality in Python. You can't use them for naming variables. They have magical powers, and should only be used when you know what they are for.
and
as
assert
break
class
continue
def
del
elif
else
except
exec
False
finally
for
from
global
if
import
in
is
lambda
None
nonlocal
not
or
pass
raise
return
True
try
while
with
yield
At this point in the course, you're not supposed to know what that list of words can do. It's not important.
What's important is knowing that they can't be used as a variable's name.
Let's assume you're writing a poker video game. In poker, a player can 'raise' when they bet. It would then stand to reason that your game would probably have a variable called raise.
This is when Python gets confused.
As far as Python knows, the keyword raise has a specific function, and you would end up with an error in your code.
Maybe your raise variable could be called raise_bet? Python would be happier with that!
Can you get Python to hold the string Hello in a variable called message? Can you ask Python what type the variable message is? You're going to need the print() and type() functions.
message = 'Hello'
print(message)
print(type(message))
Before we talk about addition, subtraction, multiplication, division and brackets and exponents, I'd like to talk about '='.
Notice I never said 'equal sign'. Start by calling '=' the assignment operator.
To understand '=' you must understand that assignment moves from RIGHT to LEFT.
When you write y = x, the computer understands to move the value in x to the variable y.
Assignment can only happen from RIGHT to LEFT.
So, what does 2 + 2 look like?
For starters it DOES NOT look like:
2 + 2 = 4
It looks like:
4 = 2 + 2
Always. Forever and ever.
The operands are the values on either side of the operator.
So in the statement:
x + y
x and y are the operands and + is the operator.
Operators are symbols that help us perform calculations.
Here are a couple you've picked up over the years thanks to your math teachers: +, -, *, /
Addition, subtraction and multiplication all behave the way you think they should.
Sometimes division doesn't give you the answer you expect. DIVISION ALWAYS RETURNS A FLOATING POINT NUMBER.
answer = 3 / 2
print(answer)
OUTPUT: 1.5
answer = 3 // 2
print(answer)
OUTPUT: 1
answer = 3 + 2
print(answer)
OUTPUT: 5
answer = 3 - 2
print(answer)
OUTPUT: 1
answer = 3 * 2
print(answer)
OUTPUT: 6
answer = 3**2
print(answer)
OUTPUT: 9
%, the modulus operator allows us to calculate the remainder in integer division. Using % allows you to calculate if a number is even or odd, or it can be used to strip a digit into places.
answer = 6 % 2
print(answer)
OUTPUT: 0
answer = 17 % 2
print(answer)
OUTPUT: 1
print(132 % 100)
print(132 % 10)
Often, you'll find yourself adding or subtracting 1 to a variable.
This looks like:
x = x + 1
Python has a shortcut for this:
x += 1
The following is not rounding. You have a large decimal number, but only want to show a certain amount of decimal places.
theLargeDecimal = 5/3
print(theLargeDecimal)
theSmallDecimal = format(theLargeDecimal, '.2f') #format function
print(theSmallDecimal)
Python has an order of operations (BEDMAS) just like in math class. Parenthesis work just like they do in math class.
If one of your operands is a string, and the operator is the '+', concatenation occurs. Concatenation means joining.
Pay attention to the print() statement:
answer = 3 - 1
answer = str(answer) # Change the int type variable answer into a string type so it will be outputted
print('The answer is: ' + answer)
OUTPUT: The answer is 2
We've looked at math operators like +, -, *, /, and %.
Next, we're going to look at conditional operators.
x < y # less than
x <= y # less than or equal to
x > y # greater than
x >= y # greater than or equal to
x == y # is / equal
x != y # not equal
You can compare two strings with ==.
Please reread the Logic Gates note for more details. In the meantime, here's the Python implementation of Boolean Operators.
and # both conditions must be true
or # 1 or both conditions must be true
not # negation
How do programmers solve problems? The problem is divided into input, processing and output.
The first problem I'd like to solve is getting Python to ask me for my name.
In Python 3.x, you can get input from the user with the input() function.
Let's just call input(), and see what happens:
>>> input()
Hello
'Hello'
>>>
I called input() from the Python shell, and the interpreter waited for me to type something and then press 'Enter'. The interpreter then printed out my input.
Let's refine that a bit.
We know how to use the function print() to print variables:
x = 5
print(x)
OUTPUT: 5
Can we use that to print our message?
message = Hello
print(message)
OUTPUT:
That didn't work too well. What is our message? Python thinks that Hello is a variable.
The word Hello is a string. Python will understand that it is a string if we wrap it in quotes.
message = 'Hello'
print(message)
OUTPUT: Hello
Not much of a program. Can it be changed, and still work?
What happens if we try to print the string directly?
print('Hello')
OUTPUT: Hello
Now we have two ways to print information to the screen.
Firstly a flexible way, with a variable being passed to the function print(), and secondly by passing the string directly to the function print().
Which one is better?
Well, which one is more flexible? Let's explore that idea:
In Python, the function input() handles keyboard input. Let's use it to ask a question, and store the input in a variable.
You could just call input() like this:
input()
But the result is a bit odd. There's no explanation to the user. Let's try to give the user a hint.
print('Please type in your name: ')
input()
Well, that works, but how do we print the name to the screen?
It turns out that in our first attempt, there's nothing holding the string the user types.
Let's provide the function input() with a variable to hold the string the user types:
print('Please type in your name: ')
user_name = input()
OK, that seemed to do something, but how do we output the string?
Well, here's where flexibility comes in.
print('Please type in your name: ')
user_name = input()
print(user_name)
That solves our problem nicely, but what about flexibility?
Earlier, when we were discussing outputting the string Hello, we decided that it could be done two ways.
We said that output with a variable was more flexible.
If I wanted to have the program run in class, would it make sense to write 30 individual programs for each of you?
Or,
One program that was flexible and relied on variables to hold the different input?
Is there another solution?
Yes, but it involves knowing that input() can be passed a string:
user_name = input('Please type in your name: ')
print(user_name)
You've seen INPUT with input() and OUTPUT with print(). What about the processing?
print('This program will add 2 numbers.')
number1 = input('First number: ')
number2 = input('Second number: ')
sum = number1 + number2
print(sum)
Funny output, isn't it. It's not adding at all, and you're looking at a concatenation of the two values you entered.
Why? Because input() makes all input a string.
Casting is the action of converting or transforming one datatype to another.
You can cast any datatype to any other datatype by using the following methods:
str()
float()
int()
A cast would look like this:
x = 5.0
y = int(x)
x was a float on the first line. We then cast x to an integer and held it in y on the second line.
By the time we're done, we needed two variables.
We could make this more interesting by reusing our original variable:
x = 10.0
x = int(x)
Note that x is a float on the first line. x is then cast into an integer type, and then put back into x, effectively altering the type of x. x is now an integer.
This would be a great time to hum the "Transformers" theme song.
If you are ever unsure of a variables type, you can use type(). In the following example, I am using print() and type() at the same time, otherwise I would not be able to see the information that type() was providing.
x = "Hi"
print( type(x) )
y = 1
print( type(y) )
z = 1.0
print( type(z) )
print('This program will add 2 numbers.')
number1 = input('First number: ')
number2 = input('Second number: ')
sum = int(number1) + int(number2)
print(sum)
OR
print('This program will add 2 numbers.')
number1 = input('First number: ')
number2 = input('Second number: ')
number1 = int(number1)
number2 = int(number2)
sum = number1 + number2
print(sum)
Which one do you find easier to read?
Does the program works well?
Yes, but is the program clear for a programmer to understand? What's happening on line 5???
The program is lacking comments.
Comments are notes that describe what is happening in the code. The comments are not for Python, they are for a human to read.
In Python, anything to the right of a '#' is a comment, and Python ignores it. Look at the following two lines of code, and predict what will happen:
print('Hi')
# print('Hi')
The '#' turned the second example into a comment. It is not a statement any longer. It can't be executed.
Why would we use this?
If you are working on a very complicated formula like area = hw, you would want to describe it in a comment:
area = h * w # area is equal to height times width
Now, anyone who reads your code, understands exactly what is happening in your formula.
Here's an example of a poor comment:
area = h * w # formula
or
area = h * w # area = hw
Neither one of these comments help the reader understand what is happening in your formula.
Let's look at a commented version of that addition program:
print('This program will add 2 numbers.') # display welcome message
number1 = input('First number: ') # ask for and store first num
number2 = input('Second number: ') # ask for and store second num
sum = int(number1) + int(number2) # cast each number into an int, add 2 numbers, store in sum
print('Total: ' + str(sum)) # output message. Concatenate the message with the string version of the variable sum
Let's take a close look at the last print statement. The '+' operator is not behaving like an addition operator. It's clearly being used as the concatenation operator. If you didn't pay attention during the operator lesson, and that comment was missing, you'd have a hard time understanding what was happening in the last print().
You will provide internal documentation (comments) for all your work. Check out the programming rubric, a large portion of your mark comes from documentation.
The secret is to comment as you code. Going back to comment a small program is annoying. Going back to comment a large project is daunting.
Comment as you code.
Along with in-line comments, you must also provide a header to every file. Headers look like this:
# Author:
# Date:
# File Name:
# Description:
The first three areas of the header are easy to understand. The fourth section is YOUR UNDERSTANDING of my question. Do not re-copy my question and paste it. I know what my question is, I want to know what you've understood my question to be.
Comments are part of a larger idea called documentation.
Documentation isn't just for the next programmer who reads your code, but it's also for the user. There are 3 levels of documentation:
In-line documentation - comments
On-line documentation - help while the program is running. On-line doesn't mean the internet. Think 'Help' Option in the menu.
External documentation - help while the program is not running.
You will be responsible for internal documentation for now. I'll let you know when the other levels come into play.
Remember that a large portion of your mark comes from pseudo-code and comments.
When in doubt, comment.
Comments should be as clear and elegant as your solution, not an after thought.
Most importantly: Comment as you code. Going back to comment after is annoying on small programs, and daunting on larger programs
The top level comment block A.K.A the header comment
Program Name
Author
Date
Clear Description
All variables and objects. Remember the clearer the actual names, the easier it is to comment
Your algorithm / formula
Decision structures (Selection and Repetition)
In Grade 11, you to learn how to manage your own projects, and not use the project manager of your IDE.
You should be using a directory in your home directory for your rough work.
Name all work like this: Lastname_AssignmentName.py
When we start external documentation, you also have to include a Lastname_AssignmentNameHelpFile.txt for each assignment.
Please don't hand in a .zip compressed archive unless you speak to me first.
Smith_AreaCalc.py
Smith_TriArea.py
Smith_ChangeChange.py
Smith_TriArea.py
Smith_TriArea_Help.txt
We will use Google Classroom to collect assignments. I will give you a class code so that you can join our class.
Go to Google Classroom, login is: student#@educ.dpcdsb.org
Authenticate with your school userid and school password.
Errors are going to happen. Let's learn to deal with them.
Your early debugging will take place with print(). Later in the course, I'll show you how to use IDLE's debugger.
Syntax errors occur when you mistype, or attempt to use a part of the language in a way that doesn't work.
printz()
print)(
Logic errors occur when there is an error in your problem solving.
# You want to divide 10 by 2. But you divide 2 by 10
x = 10 / 2
# versus
x = 2 / 10
Run-time errors occur when the program is running. They can be based on poor error checking.
# Your code asks for a name, and the user incorrectly types in a number
userinput = input('Please enter your name: ')
INPUT: 5
OUTPUT: CRASH!
Let's look at this infographic together. It will teach you how to find errors in your own code and write quizzes.