October 18 - Introduction to Programming

Welcome to the second lesson of Woodlands Computer Science :) Slides available here, use your PDSB account to view the slides.

Review

Last time, we covered:

The slides from last meeting are avaialble here (make sure to use your PDSB account)

Today, we’re going to learn about user input, booleans, and by the end of this lesson you’ll be writing your own conditional statements!

User input

In Python, we can use the input() function to receive input from the user. Try running the below code!

print("What is your name?") name = input() print("Hello " + name) ##### Jeffrey

We can also place a “string” inside the input() function which outputs the text before prompting for user input:

name = input("What is your name?\n") print("Hello " + name) ##### Jeffrey

Just a quick recap on data types: “string” means “sequence of characters”, and anything else means numbers. You can tell if a value is a string by checking if it has quotes around it. So:

"13" is a string, but

13 is not.

Notice that we need a '\n' character after the string if we want the user to type on the next line. Remember, \n means “new line”.

The input() function returns a string, so the following code would result in an error.

age = input("How old are you?\n") print(age+2) ##### 17

Instead, if we want to get an integer from user input, we can use the int() function, which converts strings to integers.

age = input("How old are you?\n") age = int(age) print(age+2) ##### 17

Similarly if we want a value with decimals, we can use the float() function:

num = input("Enter a decimal number:\n") num = float(num) print(num+0.5) ##### 1.65

But even if you use int() instead of float(), Python will implicitly cast integers to floats for you.

Activity

Create a program that asks a user for their name, age, and a decimal between 0 and 1.

Then, greet the user using their name and output their age multiplied by the decimal.

Example (>>> denotes user input, everything else is program output):

What is your name? 
>>> Jeffrey 
What is your age? 
>>> 17 
Pick a decimal between 0 and 1: 
>>> 0.1 
Hello Jeffrey! Your value is 1.7

Booleans

A new data type! Booleans are really just a fancy word for True or False. We can assign a variable to either value, or more commonly we can get a boolean value by evaluating an expression. One common expression is comparing two values. In Python, these operators can be used for comparison:

Operator Description Example (True)
== Are the two values equal? 4 == 4
!= Are the two values not equal? 10 != 5
< Is the left value less than the right value? 3 < 4
> Is the left value greater than the right value? 5 > 4
<= Is the left value less than or equal to the right value? 7 <= 7
>= Is the left value greater than or equal to the right value? 12 >= 1


We can also use logical operators to combine multiple conditional statements.

Operator Description Example (True)
and Are both statements true? 4 == 4 and 2 - 1 == 1
or Is either statement true? 4 == 4 or 2 - 1 == 0


Note that these operators consider both sides independently, so 3 == 3 or 4 only checks if 4 is equal to 3, not if 4 is equal to either 3 or 4. Just like in math, if you get confused with operator precedence you can just shove brackets everywhere :3

4 == 4 or 4 == 3 and 1 == 1 -> 4 == 4 or (4 == 3 and 1 == 1)

Here’s the complete list of operator precedence, which is kind of like the BEDMAS of Python.

One more useful logical operator is not, which flips the result of a boolean (True becomes False and vice versa)

Operator Description Example (True)
not Is the boolean False? not 4 == 3


Those are the most important basics! Let’s practice :)

For each scenario, try guessing if the expression is True or False. For scenario 1 and 2, it may be helpful to consider whether or not the expression x % 2 is the same when x is any even number or any odd number.

# Scenario 1 print(5 % 2 == 0) # Scenario 2 print(4 % 2 == 0) # Scenario 3 print((1 == 2 or 1 == 3) or (1 == 1 and 2 == 2)) # Scenario 4 print((1 + 2 * 3 == 9) and (1 - -1 == 2)) # Scenario 5 a = 5 b = 12 c = 13 print(a**2 + b**2 == c**2 and a + b >= c and a + c >= b and b + c >= a)

Conditional Statements

In Python, we can direct our code using conditional statements. Basically, based on expressions, our program decides on what code to execute.

The most basic conditional statement is the if statement. The syntax looks like this:

if <expression>:
    <run this code>

The can be anything that we covered in the previous slides, and the code below will only execute if the expression is truthy. The semicolon following the expression is necessary and the code below it must be indented.

# Scenario 1 if 1 == 1: print("This code has run!") # Scenario 2 if 2 == 1: print("This code has run!")

Indentation

Indentation in Python defines “blocks” of code. If lines of code are at the same indentation level, they are contiguous (and considered to be in the same block).

if <expression>:
    <code>
    <code>
    <code>
<also code>
<also code>
<also code>

All the code lines are in the same block, and they will only run if <expression> is true. All the also code lines are in the same block, and they will always run (after the if statement). This becomes more confusing when you have multiple nested blocks, but we will deal with those later. As a brief overview, nested blocks work the same way as in the example above, but the block might have an initial indentation level.

Else statements

The second conditional statement is the else statement. It is used with other conditional statements and specifies a block of code to execute if none of the previous conditional statements ran.

if 2 == 1: print("If block run!") else: print("Else block run!")

Notice that only one of these chained conditional statements can execute - the if statement and the else statement cannot both run. Once again, indentation is necessary. Try changing a number and see what happens!

What if we want to have multiple alternative if statements before our else statement executes?

We might try something like:

if 1 == 1: print("First") if 1 == 2: print("Second") else: print("Third")

But this doesn’t work because the two if statements are viewed independently Instead, we can use the elif statement (short for else if).

An elif statement goes after either an if statement or another elif statement.

if <expression1>:
    print("First")
elif <expression2>: 
    print("Second")
elif <expression3>: 
    print("Third")
else:
    print("Fourth")

Like with if-else statements, notice how only one conditional statement in the entire chain can be executed - “Third” cannot be printed if either expression1 or expression2 is True.

Finally, the first elif statement must come after an if statement, and you can have an infinite number of elif statements.

To summarize, all chains of conditional statements follow this structure:

if <expression>: # Must begin with an if statement, and there can only be one if statement. 
    <code>
elif <expression>: # The if statement can be followed by any number of elif statements (zero to infinity). 
    <code>
elif <expression>:
    <code>
... 
elif <expression>:
    <code>
else: # Following all the if/elif statements, an else statement can be optionally placed to execute if none of the previous conditional statements ran. 

<code>

Remember that only one of these conditional statements can be executed and that indentation is necessary to specify which block a line of code belongs to.

Activity

Create a program that prompts for input of an integer from 1 - 10. Verify that the number is in the range (assume the input is an integer). The next line should print whether the number is even/odd. The last line should print if the number is “less than”, “equal to” or “greater than” 5. If the number is not in the range, print an error message instead.

Examples (>>> denotes user input, everything else is program output):

Please enter an integer from 1-10:
>>> 9
9 is odd
9 is greater than 5
Please enter an integer from 1-10:
>>> 16
16 is not in the range