Core Concepts

SA
StudyAI
AI-generated study notes
· Published Updated Free model

From the Python Programming Basics curriculum

TL;DR

Python programming revolves around fundamental building blocks like variables, data types, and control flow. Understanding these helps you store information, define its nature, and direct your program's actions. Mastering these core concepts is essential for writing any functional Python code.

1. The Mental Model

Think of programming like giving instructions to a very precise, but not very smart, assistant. You need to tell it exactly what information to remember, what kind of information it is, and then the exact steps to follow to achieve a goal.

2. The Core Material

Variables

Variables are like named storage boxes in your computer's memory. You use them to hold pieces of information (data). When you assign a value to a variable, Python remembers that value under that name.

# Here, 'name' is a variable holding the string "Alice"
name = "Alice" 

# 'age' is a variable holding the integer 30
age = 30       

# You can change the value stored in a variable
age = age + 1  # Now 'age' holds 31

Data Types

Every piece of information has a "type" that tells Python what kind of data it is and what operations can be performed on it. Python handles most type assignments automatically (it's "dynamically typed").

Common data types:
* Integers (int): Whole numbers (e.g., 10, -5, 0).
* Floating-point numbers (float): Numbers with decimal points (e.g., 3.14, -0.5).
* Strings (str): Sequences of characters, enclosed in single or double quotes (e.g., "hello", 'Python').
* Booleans (bool): Represent True or False. Used for logic.
* Lists (list): Ordered, mutable (changeable) collections of items (e.g., [1, 2, "apple"]).
* Dictionaries (dict): Unordered, mutable collections of key-value pairs (e.g., {"name": "Bob", "age": 25}).

type_example_int = 10
type_example_float = 3.14
type_example_string = "Hello"
type_example_bool = True
type_example_list = [1, "two", 3.0]
type_example_dict = {"item": "notebook", "quantity": 2}

print(type(type_example_int))    # Output: <class 'int'>
print(type(type_example_string)) # Output: <class 'str'>

Operators

Operators are special symbols that perform operations on values and variables.

  • Arithmetic: +, -, *, /, // (integer division), % (modulo), ** (exponentiation).
  • Comparison: == (equal to), != (not equal to), <, >, <=, >=. These return True or False.
  • Logical: and, or, not. Used to combine boolean expressions.
x = 10
y = 3
print(x + y)    # 13
print(x / y)    # 3.333...
print(x == y)   # False
print(x > y and y > 0) # True

Control Flow (If/Else Statements)

Miniature caution cone on a computer keyboard symbolizing data security and control.
Photo by Fernando Arcos on Pexels

Control flow statements determine the order in which your program's instructions are executed. if, elif (else if), and else statements allow your program to make decisions.

graph TD
    A["Start: Check a condition"] --> B{Condition 1 is True?};
    B -- Yes --> C["Execute Code Block 1"];
    B -- No --> D{Condition 2 is True?};
    D -- Yes --> E["Execute Code Block 2"];
    D -- No --> F["Execute Code Block 3 (Else)"];
    C --> G["End of conditional logic"];
    E --> G;
    F --> G;
temperature = 25

if temperature > 30:
    print("It's hot outside!")
elif temperature > 20: # This runs if the first 'if' is False
    print("It's a pleasant day.")
else: # This runs if both 'if' and 'elif' are False
    print("It's a bit cool.")

3. Worked Example

Let's say you want to calculate the total cost of an item, including tax, and then decide if it's expensive.

item_price = 15.50  # Price of the item
tax_rate = 0.08     # 8% tax rate
is_luxury_item = True # Is it considered a luxury item?

# Calculate the tax amount
tax_amount = item_price * tax_rate

# Calculate the total cost
total_cost = item_price + tax_amount

print(f"Item price: ${item_price:.2f}")
print(f"Tax amount: ${tax_amount:.2f}")
print(f"Total cost: ${total_cost:.2f}")

# Check if it's expensive based on total cost and if it's a luxury item
if total_cost > 20 and is_luxury_item:
    print("This is an expensive luxury item!")
elif total_cost > 18:
    print("This item is somewhat expensive.")
else:
    print("This item is reasonably priced.")

# Output for this example:
# Item price: $15.50
# Tax amount: $1.24
# Total cost: $16.74
# This item is reasonably priced.

4. Key Takeaways

  • Variables are named containers for storing data in your programs.
  • Data types like int, float, str, bool, list, and dict define what kind of data variables hold.
  • Python automatically determines the data type of a variable when you assign a value to it.
  • Operators (+, ==, and) allow you to perform calculations and make comparisons.
  • if/elif/else statements control which code blocks execute based on conditions.
  • Indentation is crucial in Python; it defines code blocks for if statements and functions.
  • Comments (lines starting with #) help explain your code for others and your future self.

Common Mistakes to Avoid:
- Forgetting that == checks for equality, while = assigns a value.
- Mismatched indentation, which causes IndentationErrors.
- Trying to perform arithmetic operations on incompatible types (e.g., adding a number to a string without conversion).
- Using keywords as variable names (e.g., if = 5).
- Not defining a variable before trying to use it.

5. Now Try It

Create a Python script that asks the user for their name and age. Store these in appropriate variables. Then, use an if/else statement to print a message: "You are an adult." if the age is 18 or higher, and "You are a minor." otherwise. Finally, print a greeting including their name and the message. Success looks like your program correctly identifying adults and minors and printing a personalized greeting.

Try it yourself: Layers of the Earth in 3D

Frequently asked about Core Concepts

Python programming revolves around fundamental building blocks like variables, data types, and control flow. Understanding these helps you store information, define its nature, and direct your program's actions. Read the full notes above for the details.

Core Concepts is a core topic in Python Programming Basics. Most exam papers test it via a mix of definitions, worked examples, and applied problems. The notes above cover the high-yield sub-topics, common pitfalls, and the kind of questions examiners typically set.

Yes — every note in the StudyAI Campus Hub is free to read in full, right here on this page, with no account needed. If you clone the plan into your own dashboard, the free plan shows a preview of each note there; Basic and above unlock the full notes in your dashboard, along with practice quizzes, flashcards and offline study. You can always come back here to read the complete note for free.
Continue with
Advanced Review

Study this next


Get the full Python Programming Basics curriculum

Clone the complete plan to your dashboard for unlimited AI-generated notes, practice quizzes, and a personalised revision schedule.

Save this course free