Let's take some math: 4 = 3 + 1 (See chart for details)
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 + yx 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 / 2print(answer)OUTPUT: 1.5answer = 3 // 2print(answer)OUTPUT: 1answer = 3 + 2print(answer)OUTPUT: 5answer = 3 - 2print(answer)OUTPUT: 1answer = 3 * 2print(answer)OUTPUT: 6answer = 3**2print(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 % 2print(answer)OUTPUT: 0answer = 17 % 2print(answer)OUTPUT: 1print(132 % 100)print(132 % 10)Often, you'll find yourself adding or subtracting 1 to a variable.
This looks like
x = x + 1Python has a shortcut for this:
x += 1The following is not rounding. You have a large decimal number, but only want to show a certain amount of decimal places.
theLargeDecimal = 5/3print(theLargeDecimal)theSmallDecimal = format(theLargeDecimal, '.2f') #format functionprint(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 - 1answer = str(answer) # Change the int type variable answer into a string type so it will be outputtedprint('The answer is: ' + answer)OUTPUT: The answer is 2We've looked at math operators like +, -, *, /, and %.
Next, we're going to look at conditional operators.
x < y # less thanx <= y # less than or equal tox > y # greater thanx >= y # greater than or equal tox == y # is / equalx != y # not equalHow 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 = 5print(x)OUTPUT: 5Can we use that to print our message?
message = Helloprint(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: HelloNot much of a program. Can it be changed, and still work?
What happens if we try to print the string directly?
print('Hello')OUTPUT: HelloNow 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 + number2print(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:
A cast would look like this:
x = 5.0y = 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.0x = 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 = 1print( type(y) )z = 1.0print( 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 + number2print(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.
Managing your own projects is an important skill.
You should be using a directory in your home directory for your rough work.
When you are ready to hand work in:
Name all work like this: Lastname_AssignmentName.py
When we start external documentation: Lastname_AssignmentNameHelpFile.txt
Please don't hand in a .zip compressed archive unless you speak to me first.
We will use Google Classroom to collect assignments. I will give you a class code so that you can join our class.
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 10x = 10 / 2# versusx = 2 / 10Run-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 numberuserinput = input('Please enter your name: ')INPUT: 5OUTPUT: CRASH!