Fundamentals

Variables, Expressions, Statements, Conditionals

Python is an imperative programming language. Your programs are a series of Statements that are executed in order.

Each Statement can be made up of Variables and Expressions.

Conditional Statements change the execution of your program depending on the state of Variables and Expressions.

This is a lot, so let’s unpack it.

What are Variables?

Variables are names that can be attached to data. Each variable has a type:

  • Integer: x = 1
  • Float: x = 1.5
  • String: x = “umd”
  • Boolean: x = True

We’ll be talking about more complex types (e.g. lists, dictionaries, sets) and even how to create your own over the course of the semester.

Working with Variables

There are two main actions we take with variables:

  • assignment: attach a name to some data
  • evaluation: lookup the data by its name

Practice with Variables

# assignment
x = "Hello World"

# evaluation
print(x)

Notice the use of comments on lines 1 and 4?

What are Expressions?

Expressions are pieces of Python that get evaluated, and are often created with operators:

  • addition (+)
  • subtraction (-)
  • multiplication (*)
  • division (/)
  • integer division (//)
  • modulo (%)
  • exponentiation (**)
  • equality (==)

Remember order of operations: PEMDAS

Practice with Expressions

x = 2
x * x

4

x = 2
x ** 3

8

x = 2
y = 3
x == y

False

x = 80
y = 30
x - y

50

x = 2
y = 3
y - x + 4

5

x = 2
2 + x ** 3

10

Operators behave differently depending on the type:

"u" + "m" + "d"

umd

"umd " * 5

umd umd umd umd umd

What are Statements?

  • Statements are the most basic units of executable Python code.
  • A Python program is a series of statements executed in order.

Try these statements to input and print a variable:

username = input("Enter your name: ")
print("Hello", username)

What are Conditionals?

  • In practice, you often do not want every statement in a program to be executed every time.
  • Instead, you want your program to execute depending on the logical state of data or input when your program is running.
  • The basic building blocks for this logic are conditionals, which are constructed with the keywords if, else and elif.

Structure of Conditionals

if 1 > 0:
    print("yes")
else:
    print("no")

yes

Practice with Conditionals

order = input("What can I get you? ")

if order == "burger":
    side = input("Would you like fries? ")
elif order == "salad':
    side = input("What kind of dressing? ")
else:
    print("We only sell burgers and salads.")

print("You ordered:", order, side)

So …

We’ve covered a lot but now you know the basic buiding blocks of all Python programs, and imperative programming languages in general:

  • Statements
  • Variables
  • Types
  • Operators
  • Expressions
  • Conditionals