Lecture 02 Review

Joseph Haugh

University of New Mexico

Python As Pseudocode

  • To start the class we will review these prerequisite topics
  • We will use Python to do this as most of you already know it
  • If you don’t know you should be able to learn it very quickly

Comments

  • Comments are lines of code which are only used to communicate to programmers
  • Comments do not effect the output of a program
  • Can add more context to a program
# This is a comment
x = 5 # This is an inline comment

Variables

  • Variables store information
  • This can be numbers, string, lists and more
  • Variables can have their values changed as the program runs
x = 5     # x is 5
y = 6 + 3 # y is 9
z = y * 2 # z is 18

If Statements

  • Allows a program to take branching paths
  • If the condition is true then takes the first branch
  • Otherwise checks the other branch conditions until it finds one which is true
  • Or gets the the else at the end of the chain
  • Does not have to have an else branch
x = 5
if x > 5: # If x is greater than 5
    # Then do these statements
    print("Greater than 5")
elif x == 5: # Else if x is equal to 5
    # Then do these statements
    print("Equal to 5")
else:
    # Else do these statements
    print("Less than 5")

Looping

  • Allows a program to repeat a sequence of statements many times
  • While loops repeat the body of the loop until the condition is false
  • Loops can repeat as many times as they want
i = 0
while i < 5: # Loop until i is NOT less than 5
    # While the condition holds do these statements
    print(i)
    i = i + 1
    # Then check the condition again and repeat if necessary

Indentation

  • In Python indentation matters
  • Indentation is how many spaces/tabs precede a line of code
  • In order for statements to be inside a given Python if statement or while loop they must be indented further than if/while
  • For example:
x = 5
y = 6
if x < 5:
    x = 7 # This line is inside the if
y = 8 # This line is not
print(x) # Prints 5
print(y) # Prints 8

Indentation

x = 0
y = 0
while x < 10:
    x += 1   # This line is in the while loop
    print(x) # And so is this one
print(y) # But this is not

Input

  • Getting user input in Python is easy
  • To get an int you do the following:
# Read an int from user input
x = int(input())
# Now you can use the number
if x >= 0:
    print("Positive")
else:
    print("Negative")