Back to Python
2026-02-018 min read

Your First Python Program

Learn Your First Python Program step by step with clear examples and exercises.

Title: Your First Python Program

Why This Matters

Learning to write your first Python program is the foundation for mastering this versatile and widely-used programming language. It's essential for various purposes, such as automating repetitive tasks, data analysis, web development, artificial intelligence, and more. Understanding how to create a simple Python program will help you tackle larger projects and prepare you for real-world coding scenarios.

Python is known for its simplicity, readability, and extensive library support, making it an excellent choice for beginners and experienced developers alike. By writing your first Python program, you'll gain a solid understanding of the language's syntax and structure, which will serve as a stepping stone to more complex projects.

Prerequisites

Before diving into your first Python program, make sure you have the following prerequisites:

  1. Install Python on your computer: You can download Python from python.org and follow the installation instructions for your operating system.
  2. Familiarize yourself with basic Python syntax: Learn about variables, operators, functions, loops, and conditional statements to get a better understanding of Python's core concepts. You can find resources on this topic in various online tutorials or books.
  3. Understand how to run Python code: You can run Python code in an Integrated Development Environment (IDE), such as PyCharm, Visual Studio Code, or Jupyter Notebook, or directly from the command line/terminal. Consult your IDE's documentation for instructions on running Python scripts.

Core Concept

In this section, we'll walk through writing a simple Python program that adds two numbers using functions and variables.

def add_numbers(a, b):
"""
This function takes two arguments (a and b) and returns their sum.
"""
result = a + b
return result

Define the first number

num1 = 5

Define the second number

num2 = 3

Call the function and store the result

result = add_numbers(num1, num2)

Print the result

print("The sum of", num1, "and", num2, "is:", result)


Let's break down this code:

- We define a function called `add_numbers` that takes two arguments, `a` and `b`, and returns their sum. The docstring (the string in triple quotes at the beginning of the function definition) provides a brief description of what the function does.
- Inside the function, we perform the addition operation and store the result in the variable `result`.
- Next, we define two variables, `num1` and `num2`, with values of 5 and 3 respectively.
- We call the `add_numbers` function, passing `num1` and `num2` as arguments, and assign the returned result to a new variable called `result`.
- Finally, we print the result using the `print()` function, including the original numbers for clarity.

Worked Example

Now let's try running this code in your Python environment:

  1. Open an IDE or create a new file with the .py extension and paste the code above.
  2. Save the file (e.g., add_numbers.py).
  3. Run the script by selecting "Run" or "Run File" from the menu, depending on your IDE.
  4. You should see the following output:
The sum of 5 and 3 is: 8

Common Mistakes

  1. Syntax errors: Double-check that you have correctly spelled keywords (e.g., def, return) and follow proper indentation conventions. Incorrect indentation can lead to syntax errors, making it difficult to run your code.
  2. Incorrect function arguments: Make sure the number of arguments passed to a function matches the number expected by the function definition. If you pass too many or too few arguments, you'll encounter an error.
  3. Variable naming conflicts: Avoid using reserved words as variable names, such as print or def. Using these keywords as variables will cause syntax errors.
  4. Missing parentheses: Ensure that functions are called with proper parentheses (e.g., add_numbers(5, 3), not just add_numbers 5 3). Missing parentheses can lead to unexpected behavior or syntax errors.
  5. Forgotten return statements: If a function is supposed to return a value but doesn't have a return statement, it will return None. Make sure that all functions with a return statement actually return something.
  6. Variable assignment errors: Ensure that you are assigning values to variables correctly. For example, if you try to assign a string to an integer variable, Python will raise a TypeError.
  7. Improper use of operators: Be careful when using operators like == for comparison and = for assignment. Using them incorrectly can lead to logic errors in your code.
  8. Incorrect looping or conditional statements: Make sure that your loops and conditional statements are structured correctly, with proper indentation and syntax. Incorrect use of these constructs can result in infinite loops or unintended program behavior.
  9. Not handling exceptions: Python allows you to handle exceptions (errors) using try-except blocks. Failing to handle exceptions can cause your program to crash unexpectedly.
  10. Ignoring error messages: When your code encounters an error, Python will display an error message. Ignoring these messages and continuing to run the code without addressing the issue can lead to further errors or unintended behavior.

Practice Questions

  1. Modify the add_numbers function to subtract two numbers instead of adding them.
  2. Write a new Python program that multiplies two numbers using a separate function called multiply_numbers().
  3. Create a function called find_largest() that takes three arguments and returns the largest number.
  4. Write a Python program that calculates the factorial of a given number using a recursive function called factorial().
  5. Write a Python program that checks if a number is prime by defining a function called is_prime(). The function should take one argument, n, and return True if n is a prime number (i.e., only divisible by 1 and itself) and False otherwise.
  6. Write a Python program that calculates the Fibonacci sequence up to a given number using a recursive function called fibonacci(). The function should take one argument, n, and return the first n numbers in the Fibonacci sequence (0, 1, 1, 2, 3, 5, 8, ...).
  7. Write a Python program that generates a list of all prime numbers up to a given number using a function called generate_primes(). The function should take one argument, n, and return a list of all prime numbers up to (and including) n.

FAQ

  1. What is the purpose of indentation in Python?

Indentation in Python is used to define blocks of code, such as loops and functions. Each line within a block should be indented by the same number of spaces (usually 4). Proper indentation helps make the code more readable and easier to understand.

  1. Why does Python require parentheses when calling functions?

Parentheses are necessary when calling functions in Python because they help distinguish between variables, function names, and arguments. Without them, it can be difficult to determine whether a name refers to a variable or a function. Proper use of parentheses ensures that your code runs correctly.

  1. What is the difference between a variable and a constant in Python?

In Python, there are no built-in constants like in some other languages (e.g., const in C++). However, you can create "constants" by naming variables with all uppercase letters. While it's not enforced, this convention helps indicate that the variable should not be changed. Constants can make your code more readable and easier to maintain.

  1. What is the difference between a function and a method in Python?

A function is a standalone block of code that can take arguments and return values. A method is similar to a function but is associated with an object (e.g., a class instance). Methods have access to the object's attributes, whereas functions do not. Functions are called using their name, while methods are called using the dot notation, followed by the method name and any required arguments.

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

Both lists and tuples are ordered collections of items, but they differ in their mutability (i.e., whether you can change their contents). Lists are mutable, meaning you can add, remove, or modify items within a list. Tuples, on the other hand, are immutable, meaning once created, their contents cannot be changed.

  1. What is the difference between a dictionary and a set in Python?

A dictionary is a collection of key-value pairs, where each key uniquely identifies a value. A set is an unordered collection of unique items (no duplicate values). Dictionaries are mutable, while sets are immutable unless explicitly converted to a mutable set using the copy() method or creating a new set with the set() constructor and passing existing items as arguments.

  1. What is the purpose of a docstring in Python?

A docstring is a string that provides documentation for a function, class, or module in Python. It is defined at the beginning of the code block (usually on the first line) and enclosed in triple quotes (e.g., """). Docstrings help other developers understand the purpose, usage, and behavior of your code, making it more maintainable and easier to work with.

  1. What is the purpose of a module in Python?

A module is a file containing Python definitions and statements. It can contain functions, classes, variables, and more. Modules help organize your code into reusable units that can be imported and used in other scripts or programs. Importing a module allows you to access its contents without having to copy the entire code.

  1. What is the purpose of a package in Python?

A package is a collection of related modules organized within a directory structure. Packages help organize your code into larger units, making it easier to manage and reuse across multiple projects. To create a package, you need to create a directory containing an __init__.py file (which can be empty) and place your modules inside the directory.

  1. What is the purpose of a namespace in Python?

A namespace is a collection of variable bindings organized by name. In Python, each function, module, and class has its own namespace, which helps prevent naming conflicts between variables with the same name in different scopes. Namespaces also help make your code more modular and easier to manage.

Your First Python Program | Python | XQA Learn