Python Fundamentals

Module Objectives

By completing this module you will be able to:

  • Create and use variables in Python
  • Know the basic data types
  • Use arithmetic, comparison and logical operators
  • Control program flow with conditionals and loops

Why Start with the Fundamentals?

Think about when you learned to drive. Before hitting the road, you had to learn where the pedals were, how the steering wheel worked, what each gear did… Only after mastering these basic controls could you actually start driving.

Programming is the same. Before creating web applications, video games, or artificial intelligence, you need to master the fundamentals: how to store information, how to do calculations, how to make decisions, and how to repeat tasks. They are the “Lego pieces” you’ll use to build everything else.

In this chapter, you’ll learn these basic concepts. It may seem simple, but don’t underestimate it: every program, no matter how complex, is built from these fundamental pieces.


Variables and Assignment

Imagine you have a drawer where you store things. To find them easily, you put a label with a descriptive name: “invoices”, “photos”, “keys”… In programming, a variable works exactly the same way: it’s a name you give to a piece of data so you can use it later.

The beauty of Python is that you don’t need to tell it what type of thing you’re going to store. You simply give it a name, assign it a value, and Python takes care of the rest.

1# Variable assignment
2name = "Ana"
3age = 25
4height = 1.75
5is_student = True

Rules for Variable Names

Keep in mind
  • Must start with a letter or underscore (_)
  • Can only contain letters, numbers, and underscores
  • Are case-sensitive: name and Name are different
  • Cannot be Python reserved words (if, for, class, etc.)
 1# Valid names
 2my_variable = 1
 3_private = 2
 4camelCase = 3
 5CONSTANT = 4
 6
 7# Invalid names (would cause error)
 8# 2variable = 5      # Cannot start with number
 9# my-variable = 6    # Cannot contain hyphens
10# class = 7          # Is reserved word

Basic Data Types

Not all information is the same. Think about the different things you store at home: clothes go in the closet, food in the fridge, books on the shelf… Each type of thing needs its appropriate “container.”

In programming, it’s the same. Data types are the different “forms” that information can take:

  • Numbers for counting, measuring, and calculating (your age, the price of something, the temperature)
  • Text for words and messages (your name, an address, an email)
  • Booleans for yes/no answers (Is it on? Is the user an adult?)

Let’s look at each one in detail:

Numbers are probably the most intuitive data type. You use them to count things, do calculations, measure… Python distinguishes between whole numbers and decimal numbers.

Integers (int)

1x = 42
2y = -17
3z = 0
4large = 1_000_000  # Underscores can be used for readability

Floats (float)

1pi = 3.14159
2temperature = -40.5
3scientific = 1.5e-10  # Scientific notation

Text is fundamental: names, messages, addresses, passwords… everything you write is text. In programming, they’re called strings because they’re a “string” of characters one after another.

Strings (str)

1greeting = "Hello, world"
2name = 'Also with single quotes'
3multiline = """
4This text
5has multiple
6lines
7"""

String Operations

1text = "Python"
2print(len(text))        # 6 - length
3print(text.upper())     # PYTHON
4print(text.lower())     # python
5print(text[0])          # P - first character
6print(text[-1])         # n - last character
7print(text[0:3])        # Pyt - substring

Booleans are the simplest type: they can only be true (True) or false (False). They’re like a light switch: on or off, with no middle ground.

Although they seem simple, they’re fundamental. Every time your program needs to make a decision (“Is the user an adult?”, “Are there products in the cart?”), it uses booleans.

Boolean Values (bool)

1active = True
2completed = False
3
4# Comparison results
5is_greater = 5 > 3        # True
6is_equal = 10 == 10       # True
7is_different = "a" != "b" # True

The None Value

Sometimes you need to say “this has no value” or “I don’t know what value it will have yet.” It’s like when a field is empty in a form: it’s not that it has a blank space, it’s that it has nothing.

That’s what None exists for: it represents the absence of value.

1result = None
2
3def no_return():
4    print("This function returns nothing")
5    # Implicitly returns None
6
7value = no_return()
8print(value)  # None

Checking Variable Type

1x = 42
2print(type(x))  # <class 'int'>
3
4y = "text"
5print(type(y))  # <class 'str'>
6
7# Check if it's a specific type
8print(isinstance(x, int))   # True
9print(isinstance(y, str))   # True

Operators

Operators are the symbols you use to do things with data: add, subtract, compare, combine conditions… You already know most of them from school math, so this will feel familiar.

Arithmetic Operators

These are the everyday math operations, plus some extras that are very useful in programming:

Operator Description Example Result
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division 5 / 3 1.666…
// Floor division 5 // 3 1
% Modulo (remainder) 5 % 3 2
** Power 5 ** 3 125
1# Practical examples
2a, b = 17, 5
3
4print(f"Division: {a / b}")         # 3.4
5print(f"Floor division: {a // b}")  # 3
6print(f"Remainder: {a % b}")        # 2
7print(f"Power: {2 ** 10}")          # 1024

Comparison Operators

These operators ask questions and return yes/no answers (True or False). They’re the basis for your program to make decisions: “Is the user an adult?”, “Do they have enough money?”…

Operator Description
== Equal to
!= Not equal to
< Less than
> Greater than
<= Less than or equal
>= Greater than or equal
1x = 10
2
3print(x == 10)   # True
4print(x != 5)    # True
5print(x > 5)     # True
6print(x <= 10)   # True

Logical Operators

This is where things get interesting. In real life, you often combine conditions:

  • “I can go out to play if I finish my homework AND it’s sunny”
  • “I’ll go to the movies if there are tickets OR I can watch it streaming”
  • “I’ll go to the beach if it’s NOT raining”

Logical operators do exactly that:

Operator Meaning Real-life Example
and Both must be true “Is 18 years old AND has a license”
or At least one must be true “Is a child OR is retired”
not Inverts the condition “It’s NOT raining”
 1age = 25
 2has_license = True
 3
 4# Can drive if at least 18 years old AND has license
 5can_drive = age >= 18 and has_license
 6print(can_drive)  # True
 7
 8# Free access for under 12 OR over 65
 9free_access = age < 12 or age > 65
10print(free_access)  # False
11
12# Negation
13is_raining = False
14can_go_out = not is_raining
15print(can_go_out)  # True

Control Structures

Until now, your code executes line by line, from top to bottom, without deviation. But real programs need to make decisions and repeat tasks. That’s exactly what control structures do.

Conditionals: if, elif, else

Imagine you’re walking and you reach a fork in the road. Depending on some condition (Is it raining? Is there construction?), you choose one path or another.

graph TD
    A["Is it raining?"] -->|Yes| B["Take umbrella"]
    A -->|No| C["Go without umbrella"]
    B --> D["Leave the house"]
    C --> D

In Python, this is done with if (if), elif (else if…) and else (otherwise):

 1grade = 75
 2
 3if grade >= 90:
 4    print("Excellent")
 5elif grade >= 70:
 6    print("Good")
 7elif grade >= 50:
 8    print("Pass")
 9else:
10    print("Fail")
Indentation

In Python, indentation (spaces at the beginning of lines) is mandatory and defines code blocks. It’s recommended to use 4 spaces per level.

Ternary Operator

For simple one-line conditions:

1age = 20
2status = "adult" if age >= 18 else "minor"
3print(status)  # adult

For Loop

Imagine you have 10 shirts to fold. You wouldn’t write “fold shirt 1, fold shirt 2, fold shirt 3…” ten times. You’d say: “For each shirt in the pile: fold it.”

The for loop does exactly that: it repeats a block of code for each element in a sequence:

 1# Iterate over a list
 2fruits = ["apple", "banana", "cherry"]
 3for fruit in fruits:
 4    print(f"I like {fruit}")
 5
 6# Iterate a range of numbers
 7for i in range(5):
 8    print(i)  # 0, 1, 2, 3, 4
 9
10# range with start, end and step
11for i in range(0, 10, 2):
12    print(i)  # 0, 2, 4, 6, 8

While Loop

Unlike for, the while loop doesn’t know in advance how many times it will repeat. It simply says: “While this condition is true, keep repeating.”

It’s like saying: “Keep studying while you don’t understand the topic” or “Keep calling while they don’t answer.”

1counter = 0
2while counter < 5:
3    print(f"Counter: {counter}")
4    counter += 1
Beware of Infinite Loops

Make sure the while condition eventually becomes false, or the program will never end.

Loop Control: break and continue

Sometimes you need more control over your loops:

  • break: “Stop! Exit the loop right now” (like finding what you were looking for and stopping the search)
  • continue: “Skip this element and move to the next” (like skipping a song you don’t like)
 1# break: exits the loop completely
 2for i in range(10):
 3    if i == 5:
 4        break
 5    print(i)  # 0, 1, 2, 3, 4
 6
 7# continue: skips to next iteration
 8for i in range(5):
 9    if i == 2:
10        continue
11    print(i)  # 0, 1, 3, 4

Type Conversion

Sometimes you have data of one type but need it to be another. The most common example: when a user types something in a web form, it always arrives as text. If they typed “25” and you want to calculate their age in 10 years, you need to convert that “25” (text) to 25 (number).

Python lets you convert between types easily:

 1# To integer
 2x = int("42")       # From string to int: 42
 3y = int(3.7)        # From float to int: 3 (truncates)
 4
 5# To float
 6a = float("3.14")   # From string to float: 3.14
 7b = float(5)        # From int to float: 5.0
 8
 9# To string
10s = str(42)         # "42"
11t = str(3.14)       # "3.14"
12
13# To boolean
14bool(1)      # True (any number != 0)
15bool(0)      # False
16bool("")     # False (empty string)
17bool("text") # True (non-empty string)

Practical Exercises

Exercise 1: Age Classifier

Write a program that asks for the user’s age and shows:

  • “Child” if under 12 years old
  • “Teenager” if between 12 and 17 years old
  • “Adult” if between 18 and 64 years old
  • “Retired” if 65 years or older
 1age = int(input("How old are you? "))
 2
 3if age < 12:
 4    print("You are a child")
 5elif age < 18:
 6    print("You are a teenager")
 7elif age < 65:
 8    print("You are an adult")
 9else:
10    print("You are retired")
Exercise 2: Multiplication Table

Create a program that asks for a number and shows its multiplication table from 1 to 10.

1number = int(input("Enter a number: "))
2
3print(f"Multiplication table of {number}:")
4for i in range(1, 11):
5    result = number * i
6    print(f"{number} x {i} = {result}")
Exercise 3: Prime Number

Write a program that determines if a number is prime (only divisible by 1 and itself).

 1number = int(input("Enter a number: "))
 2
 3if number < 2:
 4    print(f"{number} is not prime")
 5else:
 6    is_prime = True
 7    for i in range(2, int(number ** 0.5) + 1):
 8        if number % i == 0:
 9            is_prime = False
10            break
11
12    if is_prime:
13        print(f"{number} is prime")
14    else:
15        print(f"{number} is not prime")

Quiz

🎮 Quiz: Python Fundamentals

0 / 0
Loading questions...

Previous: Introduction Next: Virtual Environment