Week 2 - Variables and Statements
Variables and Statements¶
Introduction¶
- Previous chapter: Operators and arithmetic expressions
- This chapter: Variables, statements, import statement, print function
- New vocabulary: “argument” and “module”
Variables¶
Definition¶
- A name that refers to a value or a storage location for a value.
Creating variables (Assignment statements)¶
- Syntax:
variable_name = expression - Examples:
1 2 3
n = 17 pi = 3.141592653589793 message = 'And now for something completely different' - No visible output when running assignment statements in the Python interpreter or Jupyter Notebook (i.e. Google Colab).
Using variables¶
- As expressions
1 2
message # Output: 'And now for something completely different' - In arithmetic expressions
1 2 3 4
n + 25 # Output: 42 2 * pi # Output: 6.283185307179586 - In function calls
1 2 3 4
round(pi, 2) # Output: 3 len(message) # Output: 42
State diagrams¶
- Graphical representation of variables and their values
- Used throughout the book to model Python’s variable storage, but you can generate better ones on Python Tutor
- Python Tutor or your IDE Debugger can be used (and we will later) to give you a better understanding of how the internals of Python work (i.e. stack/frames, heap/objects)
Python Variable naming rules (Other languages have slightly different rules)¶
- Can be any length (Though choose to be reasonable!)
- Can contain letters and numbers
- Cannot start with a number
- Conventionally lowercase (PEP Standards)
- Underscore (_) is the only allowed punctuation
- Used for multi-word names:
your_name,airspeed_of_unladen_swallow - snake_case_it_is
- Used for multi-word names:
- Cannot use keywords as variable names
- They are reserved in the Python grammar to designate features supported by python like class, import, etc.
Illegal variable names (examples)¶
1 2 3 | |
Keywords in Python¶
- There currently exist 36 keywords in Python 3.12
- They will get highlighted in your PyCharm IDE
| Keyword | Description |
|---|---|
| and | Logical AND operator. |
| as | Used in import statements to alias modules or packages. |
| assert | Used for debugging, raises an AssertionError if a condition is false. |
| async | Indicates an asynchronous function or expression. |
| await | Used within asynchronous functions to wait for a coroutine to complete. |
| break | Terminates the innermost loop. |
| class | Defines a new class. |
| continue | Skips the current iteration of a loop and starts the next. |
| def | Defines a function. |
| del | Deletes an object or variable. |
| elif | Used in if statements for alternative conditions. |
| else | Used in if and try statements for a default block. |
| except | Used in try statements to handle exceptions. |
| False | Boolean value representing false. |
| finally | Used in try statements to execute code regardless of exceptions. |
| for | Used for creating loops that iterate over a sequence. |
| from | Used in import statements to import specific objects from a module. |
| global | Declares a variable as global. |
| if | Used for conditional statements. |
| import | Used to import modules or packages. |
| in | Used to check membership in a sequence. |
| is | Compares the identity of two objects. |
| lambda | Used to create anonymous functions. |
| None | Represents the absence of a value. |
| nonlocal | Declares a variable as nonlocal within a nested function. |
| not | Logical NOT operator. |
| or | Logical OR operator. |
| pass | Used as a placeholder for a statement. |
| raise | Raises an exception. |
| return | Returns a value from a function. |
| True | Boolean value representing true. |
| try | Used for exception handling. |
| while | Used for creating loops that continue as long as a condition is true. |
| with | Used for context management, often with file handling or resource management. |
| yield | Used in generator functions to return values one at a time. |
The import Statement¶
- Purpose: Importing Python features
- Syntax or Usage:
import module_name
Modules¶
- Collections of variables and functions
-
Example We’ve seen: math module
1 2
import math print(math.pi) # Output: 3.141592653589793 -
Accessing module contents, like functions stored in the module.
- Use the dot operator (.)
- Examples:
1 2
math.sqrt(25) # Output: 5.0 math.pow(5, 2) # Output: 25.0
Expressions and Statements¶
Types of expressions - These are Evaluated¶
Evaluating an expression means Computing its value
- Single values (integer, float, string)
- Collections of values and operators (i.e.
x + y) - Variable names
- Function calls
Complex expression example¶
1 | |
Statements - These are Executed¶
- Executing a statement: Running it and performing its action
- Definition: Units of code with an effect but no value
- Examples: Assignment statements, import statements
import mathorx = 5
The print Function¶
Purpose: Displaying multiple values¶
Basic usage¶
1 2 | |
Working with different data types¶
1 2 | |
Multiple arguments¶
-
(Yes, we will learn how to make our own functions that can take multiple arguments, both named and unnamed)
1print('The value of pi is approximately', math.pi) -
Note: print function ALWAYS adds a space between values when passing multiple arguments to the function.
- BUT you can change it:
1print("Hello", "world!", sep="---")
Printing Formmatted Strings and Format Specifiers¶
- Using variables in format string
1print(f"{variable_name}") - Using variables and utilizing data-type specific formatting
1 2
print(f"{math.pi:.2f}") # 2 decimal spots print(f"{my_int:05d}") # 5 spaces padded with 0 - Using variables and aligning in formatting
1 2 3
print(f"Hi {math.pi:>10.2f}") # 2 decimal spaces with 10 padded spaces aligned right print(f"Hi {math.pi:<10.2f}") # 2 decimal spaces with 10 padded spaces aligned left print(f"Hi {math.pi:^10.2f}") # 2 decimal spaces with 10 padded spaces aligned center
Arguments¶
- Definition: Expressions in parentheses when calling a function
Functions with different numbers of arguments¶
- Single argument:
int('101') - Two arguments:
math.pow(5, 2) - Optional arguments:
int('101', 2),round(math.pi, 3)- We will learn how to write functions and methods that take optional arguments, just not yet.
- Variable number of arguments:
print('Any', 'number', 'of', 'arguments')- We will learn how to write functions and methods that take a variable number of arguments and allow for packing and unpacking them, but not yet.
Argument errors¶
- Too many arguments: TypeError
- This implies the function does not allow variable arguments.
- Too few arguments: TypeError
- This implies the function has required arguments (i.e. non-optional) and you are missing one or more.
- Incorrect argument type: TypeError
- This implies there could be a datatype mismatch among other posibilities.
- Type Hints/Annotation were introduced in Python 3.5 to abet in addressing common TypeError issues in Python, but they are used by IDEs because the Python Interpreter does not enforce them.
1 2 3 4 5 6 7 8 9 10 11 12 13
def add_numbers(a: int, b: int) -> int: """Add two numbers and return the result.""" return a + b def concatenate_strings(strings: List[str]) -> str: """Concatenate a list of strings and return the result.""" return "".join(strings) age: int = 76 first_name: str = "Alice" last_name: str = "Cooper" concatenate_strings(first_name, last_name) add_numbers(age, 24)
Comments¶
- Purpose: Adding notes to explain code
- Syntax/Usage: # symbol
Types of comments¶
- Full-line comments
1 2
# number of seconds in 42:42 seconds = 42 * 60 + 42 - End-of-line comments
- The standard says 2 spaces befor the comment # in end of line comments.
1miles = 10 / 1.61 # 10 kilometers in miles
- The standard says 2 spaces befor the comment # in end of line comments.
Best practices¶
- Document non-obvious features
- Explain WHY, not what
- Avoid redundant comments
- Use good variable names to reduce need for comments
Debugging¶
Types of errors¶
- Syntax errors
- Related to program structure
- Prevent program from running
- Example: Illegal variable names
- Runtime errors (exceptions)
- Occur during program execution
- Example: Using unsupported operators
- Semantic errors AKA Logic errors
- Program runs but doesn’t do what’s intended
- Example: Incorrect order of operations
Additional Notes on Variables and Statements not Covered by the Book¶
- Type Hints/Annotations (introduced in Python 3.5) were already mentioned above in Argument Errors section.
- F-strings or Format Strings (introduced in Python 3.6) were already mentioned above in the Variable Printing section.
-
Walrus operator := (introduced in Python 3.8)
- Allows assignment within expressions
1 2
if (n := len(data)) > 10: print(f"List is too long ({n} elements, expected <= 10)")
1 2 3
name = "Alice" age = 30 print(f"{name} is {age} years old") - Allows assignment within expressions
-
Underscores in numeric literals (introduced in Python 3.6) just to make large numbers simpler to read.
1million = 1_000_000