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:

  1. Download: Visit the official Python website (python.org) and download the executable installer for Windows.
  2. Run Installer: Run the .exe file.
  3. 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 python command.
  4. 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):

PYTHON
>>> print("Hello, World!")
Hello, World!

Using a Script File (.py):

  1. Create a text file named hello.py.
  2. Write print("Hello, World!") inside it.
  3. 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:

PYTHON
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:

  1. Must start with a letter (a-z, A-Z) or an underscore (_).
  2. Cannot start with a number.
  3. Can contain alphanumeric characters and underscores (A-z, 0-9, and _).
  4. Case-sensitive: myVar, MyVar, and MYVAR are three different variables.
  5. Convention: Python developers typically use snake_case for variable names (e.g., user_name rather than userName).

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:

  1. Misspelling: Referring to message as mesage.
  2. Usage before Assignment: Trying to print a variable before the line of code where it is assigned.

Example of NameError:

PYTHON
# 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

  1. Integers (int): Whole numbers without a decimal point (e.g., 1, 100, -5).
  2. Floating-Point Numbers (float): Numbers with a decimal point (e.g., 1.0, 3.14, -0.01).
  3. Strings (str): Sequences of characters enclosed in quotes (e.g., "Hello", 'Python').
  4. Booleans (bool): Represents truth values (True or False).

The type() Function

You can determine the type of a value or variable using the built-in type() function.

PYTHON
>>> 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 in print().

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:

  1. Parentheses (): Highest precedence. Used to force order.
  2. Exponents **: Calculated next (Right-to-left associativity).
  3. Multiplication * and Division /, //, %: Calculated left-to-right.
  4. Addition + and Subtraction -: Calculated left-to-right.

Example:

PYTHON
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.

PYTHON
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.

PYTHON
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 of type(x) is passed directly as an argument to print().
  • 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:

PYTHON
# This computes the percentage of the hour that has elapsed
minutes = 45
percentage = (minutes * 100) / 60  # Calculate percentage
print(percentage)