Unit 1 - Notes
INT108
Unit 1: Setting up your Programming Environment; Variables, Expression and Statements
1. Setting up the Programming Environment
Python Versions
Python is an interpreted, high-level programming language. Understanding the version history is critical for compatibility.
- Python 2: Legacy version. Support officially ended in January 2020. It is significantly different from Python 3 regarding print statements and integer division.
- Python 3: The current standard. It is not backward compatible with Python 2. All modern development should use the latest stable release of Python 3 (e.g., 3.10, 3.11, etc.).
Python on Windows
Setting up Python on a Windows machine involves the following steps:
- Download: Visit the official Python website (python.org) and download the executable installer for Windows.
- Run Installer: Run the
.exefile. - Critical Step - PATH: Ensure you check the box labeled "Add Python to PATH" before clicking "Install Now". This allows you to run Python from the Command Prompt using the
pythoncommand. - Verification: Open Command Prompt (cmd) and type
python --version. If installed correctly, it will display the version number.
Running a ‘Hello World’ Program
The "Hello World" program is traditionally the first program written to verify that the language is installed and working correctly.
Using the Interactive Shell (IDLE or CMD):
>>> print("Hello, World!")
Hello, World!
Using a Script File (.py):
- Create a text file named
hello.py. - Write
print("Hello, World!")inside it. - Run it via terminal:
python hello.py.
2. Variables: Naming, Using, and Keywords
Naming and Using Variables
A variable is a name that refers to a value. It acts as a container for storing data values.
- Assignment: Variables are created the moment you assign a value to them using the assignment operator (
=). - Dynamic Typing: You do not need to declare the type (e.g., int, char) beforehand; Python infers it.
Example:
message = "Learning Python" # String assignment
n = 17 # Integer assignment
pi = 3.14159 # Float assignment
Variable Naming Rules
To write valid variable names, you must adhere to the following rules:
- Must start with a letter (a-z, A-Z) or an underscore (
_). - Cannot start with a number.
- Can contain alphanumeric characters and underscores (A-z, 0-9, and _).
- Case-sensitive:
myVar,MyVar, andMYVARare three different variables. - Convention: Python developers typically use snake_case for variable names (e.g.,
user_namerather thanuserName).
Keywords (Reserved Words)
Keywords are reserved words in Python that define the language's syntax and structure. You cannot use these as variable names.
Common Python Keywords:
False, None, True, and, as, assert, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield.
Avoiding NameError
A NameError occurs when you try to use a variable that has not been defined (assigned a value).
Common Causes:
- Misspelling: Referring to
messageasmesage. - Usage before Assignment: Trying to print a variable before the line of code where it is assigned.
Example of NameError:
# Incorrect
print(my_number)
my_number = 5
# Result: NameError: name 'my_number' is not defined
3. Values and Types
A value is one of the basic things a program works with, like a letter or a number. The type dictates how the interpreter treats the value.
Common Data Types
- Integers (
int): Whole numbers without a decimal point (e.g.,1,100,-5). - Floating-Point Numbers (
float): Numbers with a decimal point (e.g.,1.0,3.14,-0.01). - Strings (
str): Sequences of characters enclosed in quotes (e.g.,"Hello",'Python'). - Booleans (
bool): Represents truth values (TrueorFalse).
The type() Function
You can determine the type of a value or variable using the built-in type() function.
>>> type("Hello, World!")
<class 'str'>
>>> type(17)
<class 'int'>
>>> type(3.2)
<class 'float'>
>>> type("17") # Note: Numbers in quotes are strings
<class 'str'>
4. Statements, Operators, and Expressions
Statements
A statement is a unit of code that the Python interpreter can execute.
- Assignment Statement: Assigns a value to a variable (
x = 2). - Print Statement: Displays output (
print(x)). - Script vs. Interactive Mode: In interactive mode, typing an expression prints the value. In a script, an expression statement (like
x + 1) is evaluated but produces no output unless wrapped inprint().
Operators and Operands
- Operators: Special symbols that represent computations like addition and multiplication.
- Operands: The values the operator is applied to.
| Arithmetic Operators: | Operator | Name | Description | Example |
|---|---|---|---|---|
+ |
Addition | Adds values | 10 + 5 = 15 |
|
- |
Subtraction | Subtracts right from left | 10 - 5 = 5 |
|
* |
Multiplication | Multiplies values | 10 * 5 = 50 |
|
/ |
Division | Standard division (always returns float) | 10 / 2 = 5.0 |
|
// |
Floor Division | Division rounding down to nearest whole number | 10 // 3 = 3 |
|
% |
Modulus | Returns the remainder of division | 10 % 3 = 1 |
|
** |
Exponentiation | Raises left to power of right | 2 ** 3 = 8 |
Order of Operations (PEMDAS)
Python follows standard mathematical precedence rules. The acronym PEMDAS helps remember the order:
- Parentheses
(): Highest precedence. Used to force order. - Exponents
**: Calculated next (Right-to-left associativity). - Multiplication
*and Division/,//,%: Calculated left-to-right. - Addition
+and Subtraction-: Calculated left-to-right.
Example:
result = 2 * 3 - 1
# 2 * 3 is 6, then 6 - 1 is 5.
# Result: 5
result = 2 * (3 - 1)
# (3 - 1) is 2, then 2 * 2 is 4.
# Result: 4
5. Operations on Strings
While strings are text, Python allows specific mathematical operators to work on them, though the behavior is different from numbers.
Concatenation (+)
The + operator joins (concatenates) two strings end-to-end.
first = "Python"
second = "Programming"
full = first + " " + second
# Result: "Python Programming"
Repetition (*)
The * operator repeats a string a specified number of times. One operand must be a string, and the other must be an integer.
text = "Spam"
result = text * 3
# Result: "SpamSpamSpam"
Note: You cannot subtract (-) or divide (/) strings.
6. Composition and Comments
Composition
Composition is the ability to combine simple expressions and statements into compound statements and expressions. You can use the result of one expression as part of another.
Examples:
- Nesting functions:
print(type(x))— The result oftype(x)is passed directly as an argument toprint(). - Arithmetic inside arguments:
print(10 * 5)— The multiplication is performed, and the result is printed.
Comments
Comments are notes within the source code that are ignored by the interpreter. They are intended for programmers to understand what the code does.
- Single-Line Comments: Start with the hash character (
#). Everything after the#on that line is ignored. - Multi-Line Comments: While Python doesn't have a specific multi-line syntax, triple quotes (
'''or""") are often used for multi-line descriptions (docstrings), or multiple#lines are used.
Example:
# This computes the percentage of the hour that has elapsed
minutes = 45
percentage = (minutes * 100) / 60 # Calculate percentage
print(percentage)