3. Statements and Expressions

  • Programs we write will be made up of multiple lines of code

  • Each line will be doing some sort of work/computation

3.1. Statements

  • A statement is an instruction for Python to do something

  • If you type a series of statements and press run, Python does what you asked (or at least tries to)

  • Some statements result in some immediate output

    • print("Hello world")

  • Others will do some work behind the scenes

    • some_variable = 5

3.2. Expressions

  • An expression is, roughly, a statement that can be crunched down to a value

  • More precisely, an expression is a combination of

    • literal values (e.g., 5, "Hello world")

    • variables (e.g., some_variable)

    • operators (e.g., +, *)

  • some_other_variable = (some_variable + 1) * 2 is an example of an expression (and statement)

3.3. Operators

  • We have been using these in our code already

  • Operators are symbols that tell Python to perform computations on expressions

    • example arithmetic operators — +, -, *, /

Activity

Generate expressions to:

  1. Add two variables together (use whichever values you want) and save the result to some variable.

  2. Multiply two variables together and save the result to some other variable.

  3. Divide result of step 2 by the result of step 1.

  4. Add a third variable to the result of step 3.

Activity

Now for a tougher one. Convert a temperature from Celsius to Fahrenheit.



3.4. Operators On Other Types

  • There are operators for values other than just numbers

  • We will see many of these as we move through the course

Activity

  1. Experiment with the operators you know on strings (instead of just integers).

  2. Which ones work? What do they do?

  3. Try mixing strings and integers with various operators. What happens there?

3.5. Large Series of Statements

  • So far we have been writing programs that are about one line long

  • There is nothing stopping us from writing large programs with many lines of code

    • Saved in Colab or some other file

  • We often call these Python programs scripts

  • Python will run each line of the program, one line at a time, in the order that they exist

  • Technically you can write your script in any text editor, but there are editors/environments designed for programming languages

    • Colab (use through the internet)

    • Notepad++ (Windows)

    • Sublime (Windows and Mac)

    • PyCharm (Windows, Linux, and Mac)

    • VS Code (Windows, Linux, and Mac)

Activity

Consider the sentence “I am taking CSCI 161”. Write a program that stores each word of that sentence in it’s own variable, and then prints the whole sentence to the screen, using only a single print.



3.6. For Next Class