Invent with Python — Chapter 2: The Interactive Shell; Notes

Topics Covered — Basic Programming Concepts:

  • Integers and Floating Point Numbers
  • Expressions
  • Values
  • Operators
  • Evaluating Expressions
  • Storing Values in Variables

Integers and Floating Point Numbers

integer (int): a whole number; ex: 5, 600, 76, 1, 0, … etc.

floating point number (float): a fraction or a number with a decimal point; ex: 3.5, 7.998, 23.0, 5.0, … etc.

value: any integer or floating point number

Expressions

python math operators

Expression: comprised of values connected together by operator(s); ex: math problems like 2+2+3/2*2, 1+1, … etc.

NB: There can be any number of spaces between values and operators;
ex:
>>> 2   +                 2
4

Evaluating Expressions

Evaluate an expression: reduce that expression to a single value; ex: getting 15 from 10+5

NB1: A single value is also an expression; ex: the expression 15 evaluates to the value 15

NB2: The / division operator evaluates to a float value; ex: 24/2 evaluates to 12.0

NB3: Math operations w/ float values also evaluate to float values; ex: getting 14.0 from 12.0 + 2

Syntax Errors 

syntax error: Python doesn’t understand the instruction because it is typed incorrectly

Example:
>>> 5 +
Syntax Error: invalid syntax

This error occurred because 5 + is not an expression.
Expressions have values connected by operators. The + operator expects a value after itself, but it is missing.

Storing Values in Variables 

variable:
-like a box that can store a value

statement: an instruction that doesn’t evaluate to any value

assignment statement: instruction to store a value inside a variable; ex: spam = 15
assignment operator: =

spam 15

SUMMARY

There are two types of instruction:

  1. Expression: evaluates to a single value
  2. Statement: doesn’t evaluate to any value

 

Other Notes

  • Python creates a variable the first time this variable is used in an assignment statement
  • A variable stores a value, not an expression; ex: spam = 10 + 5 v.s. spam = 10 + 7 -2 ; they both evaluate to 15; the end result is the same; both assignment statements store the value 15 in the variable spam, not the expressions 10 + 5 or 10 +7-2
  • If a value is stored in a variable, the variable can be used in an expression; ex:
    >>> spam = 1
    >>> spam
    1
    >>> spam + 5
    6
  • Can change the value stored in a variable by entering another assignment statement; ex:
    >>> spam = 15
    >>> spam + 5
    20
    >>> spam = 3
    >>> spam + 5
    8
  • Cannot use a variable before an assignment statement creates it; Python will return NameError b/c no such variable by that name exists yet

Leave a comment