Back to Python
2026-01-065 min read

Python Fundamentals

Learn Python Fundamentals step by step with clear examples and exercises.

Title: Mastering Python Fundamentals: A full guide

Why This Matters

Python is a versatile programming language that plays an essential role in various domains, including web development, data science, artificial intelligence, and more. Understanding Python fundamentals is crucial for beginners as it sets the foundation for more advanced concepts. This lesson will provide practical insights into Python basics, helping you write efficient code and solve real-world problems.

Prerequisites

Before diving into Python fundamentals, ensure you have a basic understanding of:

  1. Basic computer programming concepts such as variables, data types, operators, loops, and control structures.
  2. Familiarity with the command line or terminal (e.g., Windows Command Prompt, macOS Terminal, or Linux shell).
  3. A text editor like Sublime Text, Atom, Visual Studio Code, or Python's built-in IDLE for writing and running Python code.
  4. Basic understanding of file systems and how to navigate them using the command line/terminal.

Core Concept

Python Syntax and Structure

Python is an interpreted, high-level language known for its readability and simplicity. The syntax emphasizes code readability with the use of indentation to denote blocks of code.

print("Hello, World!") # Prints "Hello, World!"

Variables and Data Types

Python has several data types, including:

  1. Integers (e.g., 5, -23)
  2. Floating-point numbers (e.g., 3.14, 0.007)
  3. Strings (e.g., "Hello, World!", 'This is a single quote string.')
  4. Lists (e.g., [1, 2, 3], ["apple", "banana", "cherry"])
  5. Tuples (immutable lists, e.g., (1, 2, 3), ("apple", "banana", "cherry"))
  6. Dictionaries (e.g., {"name": "John", "age": 30})

Basic Input and Output

Python provides the built-in functions input() for user input and print() for displaying output:

user_input = input("Enter your name: ")
print("Hello, " + user_input + "!")

Control Structures

Python includes control structures such as conditional statements (if, elif, else) and loops (for, while). These help you make decisions and iterate through data.

Conditional statement example

age = 18

if age >= 18:

print("You are an adult.")

else:

print("You are a minor.")

For loop example

numbers = [1, 2, 3, 4, 5]

for number in numbers:

print(number)


#### Functions and Modules

Functions allow you to group related code together for reusability. Python also has a rich set of built-in modules that provide various functionalities, such as math, datetime, and os.

### Error Handling

Python uses exceptions to handle errors during runtime. Common exceptions include `NameError`, `TypeError`, `ZeroDivisionError`, and `IndexError`. You can use try-except blocks to catch and handle exceptions:

try:

Code that might raise an exception

result = 10 / 0

except ZeroDivisionError as e:

print("Caught a ZeroDivisionError:", e)

Worked Example

Let's create a simple program that calculates the factorial of a number using recursion:

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

number = int(input("Enter a positive integer: "))
if number < 0:
print("Invalid input. Please enter a positive integer.")
else:
result = factorial(number)
print("The factorial of", number, "is", result)

Common Mistakes

  1. Forgetting to close the parentheses in function calls (e.g., print Hello World)
  2. Using assignment operator instead of equality operator (e.g., x = x + 5 instead of x += 5)
  3. Misunderstanding Python's automatic type conversion (e.g., 1 + "2" -> "12")
  4. Ignoring the need for indentation (e.g., incorrectly grouping statements)
  5. Using a loop to iterate through an empty list or string
  6. Not handling exceptions appropriately or at all
  7. Forgetting to import necessary modules
  8. Misusing global and local variables
  9. Improperly naming variables (e.g., using reserved keywords)
  10. Not properly formatting output for readability

Practice Questions

  1. Write a Python program that calculates the sum of the numbers from 1 to 100 using a for loop and print the result.
  2. Create a program that checks if a given year is a leap year by checking whether it's divisible by 4 but not divisible by 100, or divisible by 400.
  3. Write a function that finds the maximum number in a list using a for loop and return the result.
  4. Implement a simple Caesar cipher encryption and decryption program that shifts each letter in a string k places to the right (k is an integer).
  5. Write a Python script that reads a file line by line, counts the number of words, and prints the total word count.
  6. Create a function that finds all common elements between two lists using a for loop and return the result as a new list.
  7. Implement a program that generates Fibonacci sequence up to n terms (n is an integer provided by the user).
  8. Write a Python script that sorts a list of dictionaries by their values in ascending order.
  9. Create a simple program that calculates the area and perimeter of different shapes, such as rectangle, square, and circle, using user input for dimensions.
  10. Implement a function that finds the longest common subsequence between two strings.

FAQ

  1. Why does Python use indentation instead of curly braces?

Python uses indentation to group statements because it makes the code more readable and easier to understand.

  1. What is the difference between a list and a tuple in Python?

A list is mutable, meaning you can change its contents, while a tuple is immutable, meaning its contents cannot be changed.

  1. Why does Python use snake_case instead of camelCase for variable naming?

Python uses snake_case because it's more readable and easier to understand when reading long variable names.

  1. What are some common built-in modules in Python?

Some common built-in modules include math, datetime, os, sys, random, re, collections, itertools, and urllib.

  1. How do I install additional libraries or modules in Python?

You can use pip (Python Package Installer) to download and install additional libraries by running the command pip install library_name in your terminal or command prompt.

  1. What is the difference between a list comprehension and a map function in Python?

List comprehensions are a concise way to create lists based on existing data, while the map function applies a given function to each item of an iterable and returns an iterator that yields the results.

  1. What is Python's built-in debugger?

Python's built-in debugger is called pdb (Python Debugger). You can use it by adding import pdb; pdb.set_trace() in your code at the point where you want to start debugging.

  1. What are decorators in Python?

Decorators are functions that take another function as an argument and extend or modify its behavior without explicitly binding them together. They provide a clean way to add functionality to existing objects at runtime.

  1. What is the purpose of the with statement in Python?

The with statement in Python is used for managing resources, such as files, connections, and locks. It ensures that resources are properly opened, closed, and cleaned up when they're no longer needed.

  1. What is generator syntax in Python?

Generator syntax allows you to create iterators in a more concise way using the yield keyword. Generators can be used for producing infinite sequences or large datasets without consuming excessive memory.

Python Fundamentals | Python | XQA Learn