Variables and Data Types

  • Variables: Containers for storing data values. Example: x = 5.
  • Data Types: Different types of values that variables can hold.
    • Integers: Whole numbers (e.g., int)
    • Floats: Decimal numbers (e.g., float)
    • Strings: Text (e.g., str)
    • Booleans: True or False (e.g., bool)

Basic Operators

  • Arithmetic Operators: +,-, *, /, // (floor division), % (modulus), ** (exponentiation)
  • Comparison Operators: ==, !=, >, <, >=, <=
  • Logical Operators: and, or, not

Strings and String Operations

  • Creating Strings: Enclosed in single (’) or double quotes (").
  s = "Hello, World!"
  
  • String Operations:
    • Concatenation: s1 + s2
    • Repetition: s * n
    • Slicing: s[start:end]
    • Methods: .lower(), .upper(), .strip(), .replace(), .find()

Lists and Tuples

  • Lists: Ordered, mutable collections.

      my_list = [1, 2, 3, 4]
      
    • Operations: .append(), .remove(), .pop(), list[start:end]
  • Tuples: Ordered, immutable collections.

      my_tuple = (1, 2, 3, 4)
      
    • Operations: Similar to lists, but cannot be changed.

Dictionaries and Sets

  • Dictionaries: Unordered collections of key-value pairs.

      my_dict = {'name': 'Alice', 'age': 25}
      
    • Operations: .keys(), .values(), .items(), .get()
  • Sets: Unordered collections of unique elements.

      my_set = {1, 2, 3, 4}
      
    • Operations: .add(), .remove(), .union(), .intersection()

Input and Output

  • Input: Reading data from the user.
  name = input("Enter your name: ")
  
  • Output: Displaying data to the user.
  print("Hello, " + name)
  

Let me know if you want more details or examples on any of these topics!

Type Hints (Python 3.10+)

  def greet(name: str, times: int = 1) -> str:
    return (f"Hello, {name}! " * times).strip()

scores: list[int] = [85, 92, 78]
user: dict[str, str | int] = {"name": "Alice", "age": 30}
  

Run mypy to catch type errors before runtime:

  pip install mypy
mypy script.py
  

f-Strings for Formatting

  name = "Alice"
score = 95.5
print(f"{name} scored {score:.1f}%")
print(f"{'yes' if score >= 60 else 'no'}")
  

f-Strings are faster and more readable than % formatting or .format().

Truthiness and None

Empty collections, 0, None, and "" are falsy:

  items = []
if not items:
    print("List is empty")

value = data.get('key')  # returns None if missing
if value is not None:
    process(value)
  

Use is None / is not None — never == None.

Unpacking and Walrus Operator

  first, *rest = [1, 2, 3, 4]  # first=1, rest=[2,3,4]

if (n := len(data)) > 10:
    print(f"Large dataset: {n} items")
  

Practice Exercise

Write a program that:

  1. Asks for three test scores via input().
  2. Stores them in a list of floats.
  3. Prints the average, highest, and lowest score.
  4. Uses an f-string for formatted output.