Popular Searches
Popular Course Categories
Popular Courses

Writing, Executing, and Debugging Your First Python Program

Writing, Executing, and Debugging Your First Python Program

Python Installation and Development Environment Setup

Writing, Executing, and Debugging Your First Python Program

Course: Python Training Course

Topic: Writing, Executing, and Debugging Your First Python Program

Course Link: Python Training Course – JustAcademy

Demo Link: Register for a Course Demo

Website: JustAcademy Official Website


1. Introduction to Writing, Executing, and Debugging Python Programs

Python is a high-level programming language used to develop websites, automate repetitive tasks, analyze data, build applications, and create artificial intelligence solutions. Learning how to write, execute, and debug a Python program is one of the first essential steps in becoming a Python developer.

Writing a program means creating instructions that solve a problem. Executing a program means running those instructions through the Python interpreter. Debugging means identifying, understanding, and correcting errors that prevent the program from producing the expected result.

These three activities are closely connected. Developers write code, execute it to observe its behavior, inspect unexpected results, correct the underlying problems, and run the program again.

Learning Objectives

  • Understand the basic structure of a Python program.
  • Create and save a Python source file.
  • Write Python statements, variables, expressions, and functions.
  • Execute Python programs using IDLE and a terminal.
  • Understand program output and user input.
  • Identify syntax errors, runtime errors, and logical errors.
  • Use error messages and tracebacks to find problems.
  • Apply debugging techniques such as print debugging and breakpoints.
  • Use Python's built-in debugger, pdb.
  • Test and improve a program until it produces the expected output.

2. Understanding the Python Program Development Process

A Python program usually passes through several stages, from understanding a problem to testing and maintaining the finished solution.

Stage Description Example
Problem analysis Understand the task and identify the required result. Calculate the total price of purchased products.
Planning Determine the inputs, processing steps, and expected outputs. Read quantity and price, multiply them, and display the total.
Writing code Translate the solution into Python statements. Use variables, arithmetic operators, and print().
Execution Run the source code using the Python interpreter. Execute a file named total_price.py.
Testing Check the program using different input values. Test small quantities and larger quantities.
Debugging Identify and fix errors discovered during testing. Correct an incorrect calculation formula.
Maintenance Improve the program or update it when requirements change. Add discount calculations or input validation.

3. Understanding the Structure of a Python Program

A Python program is composed of statements, expressions, variables, functions, and other language constructs. A simple program may contain only a few lines, while a larger application can contain many files and modules.

3.1 Your First Python Program

Create a file named hello.py and enter the following code:

print("Hello, World!")
print("Welcome to Python programming.")
print("I am learning to write Python programs.")

Expected Output

Hello, World!
Welcome to Python programming.
I am learning to write Python programs.

The print() function displays information in the output. Each statement prints one line because the default behavior of print() is to end with a newline.

3.2 Important Components

  • Statements: Instructions that Python executes, such as assignments and function calls.
  • Expressions: Combinations of values and operators that produce a value.
  • Variables: Names that refer to objects or values used by a program.
  • Functions: Reusable blocks of code that perform specific tasks.
  • Comments: Explanatory text that Python ignores during normal execution.
  • Indentation: Whitespace used to define code blocks in constructs such as functions and loops.

4. Setting Up Your Python Development Environment

Before writing and executing a Python program, make sure a compatible Python interpreter is installed and accessible. You can use IDLE, a terminal, or a code editor such as Visual Studio Code or PyCharm.

4.1 Verify Python Installation

Open Command Prompt or PowerShell on Windows, or Terminal on macOS or Linux.

On Windows, try:

python --version

If the Python launcher is available, you can also try:

py --version

On macOS or Linux, a common command is:

python3 --version

The terminal should display the installed Python version. The exact command depends on your installation and operating system.

4.2 Choose a Code Editor

Tool Purpose Suitable For
Python IDLE Provides a basic editor and interactive shell. Beginners and small programs.
Visual Studio Code Provides code editing, extensions, and debugging features. General development and larger projects.
PyCharm Provides an IDE with Python-focused development tools. Structured Python applications.
Terminal Runs Python commands and scripts directly. Command-line workflows and automation.

5. Writing Your First Python Program

Writing a Python program begins with understanding what the program should accomplish. Start with a small task, choose meaningful variable names, write the required statements, and save the code in a file.

5.1 Example: Displaying Personal Information

name = "Aarav"
age = 21
course = "Python Programming"

print("Name:", name)
print("Age:", age)
print("Course:", course)

Expected Output

Name: Aarav
Age: 21
Course: Python Programming

5.2 Explanation

  • name stores a string.
  • age stores an integer.
  • course stores another string.
  • print() displays the labels and their corresponding values.

Python does not require variable type declarations for simple assignments. It determines the type of each object at runtime.

5.3 Adding Comments

Comments explain the purpose of code and begin with the # character.

# Store the student's details
name = "Aarav"
age = 21

# Display the information
print(name)
print(age)

Comments are useful when they explain why a decision was made or clarify a non-obvious part of the program. Avoid comments that merely repeat what a clear line of code already says.

6. Working with Variables and Data Types

Variables allow programs to store and reuse information. Selecting appropriate data types helps ensure that calculations and operations behave as intended.

6.1 Example Program

product_name = "Notebook"
quantity = 4
price = 35.50
is_available = True

print("Product:", product_name)
print("Quantity:", quantity)
print("Price:", price)
print("Available:", is_available)

6.2 Common Python Data Types

Data Type Example Use
int 10 Whole numbers.
float 35.50 Floating-point numbers.
str "Notebook" Text.
bool True True or false conditions.
list ["pen", "book"] An ordered, mutable collection.
dict {"name": "Aarav"} Key-value data.

7. Accepting Input from the User

The input() function allows a Python program to receive information entered by a user. It returns the entered value as a string, so numeric input often needs to be converted before calculations can be performed.

7.1 Example: Greeting the User

name = input("Enter your name: ")
print("Hello,", name)
print("Welcome to Python!")

Sample Output

Enter your name: Riya
Hello, Riya
Welcome to Python!

7.2 Converting Input into Numbers

number1 = int(input("Enter the first integer: "))
number2 = int(input("Enter the second integer: "))

total = number1 + number2

print("Sum:", total)

The int() function converts suitable text into an integer. If the user enters text that cannot be interpreted as an integer, Python raises a ValueError.

8. Using Operators in a Python Program

Operators allow Python programs to perform calculations, comparisons, and logical operations.

8.1 Arithmetic Operators

a = 20
b = 6

print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor division:", a // b)
print("Remainder:", a % b)
print("Power:", a ** 2)

Expected Output

Addition: 26
Subtraction: 14
Multiplication: 120
Division: 3.3333333333333335
Floor division: 3
Remainder: 2
Power: 400

8.2 Comparison Operators

age = 20

print(age >= 18)
print(age == 20)
print(age != 15)

Comparison operators return Boolean values: True or False. They are commonly used in conditional statements and loops.

9. Controlling Program Flow with Conditions

Conditional statements allow a program to make decisions based on values or expressions. The if, elif, and else keywords are used to create conditional branches.

9.1 Example: Checking Eligibility

age = int(input("Enter your age: "))

if age >= 18:
    print("You are an adult.")
else:
    print("You are under 18.")

9.2 How It Works

  • The program asks the user to enter an age.
  • int() converts the input to an integer.
  • The if condition checks whether the age is at least 18.
  • Python executes the first block when the condition is true.
  • Otherwise, Python executes the else block.

Python uses indentation to identify the statements that belong to each block. Inconsistent indentation can cause an error or change the program's behavior.

10. Repeating Tasks with Loops

Loops execute a block of code repeatedly. The for loop is commonly used to iterate over a sequence, while the while loop continues as long as its condition remains true.

10.1 Example: For Loop

for number in range(1, 6):
    print(number)

Output

1
2
3
4
5

10.2 Example: While Loop

count = 1

while count <= 3:
    print("Count:", count)
    count += 1

The variable count increases after every iteration. This allows the condition to become false and the loop to stop.

11. Creating and Using Functions

A function is a reusable block of code that performs a particular task. Functions help divide a large program into smaller, easier-to-understand components.

11.1 Example: Addition Function

def add_numbers(a, b):
    return a + b

result = add_numbers(10, 20)
print("Sum:", result)

Output

Sum: 30

11.2 Understanding the Code

  • def begins a function definition.
  • add_numbers is the function name.
  • a and b are parameters.
  • return sends the calculated value back to the caller.
  • add_numbers(10, 20) calls the function with two arguments.

Using functions makes testing easier because each function can be checked independently with different inputs.

12. Saving a Python Program

A Python source file normally uses the .py extension. Saving a program in a file allows you to execute it repeatedly without re-entering the code.

12.1 Saving a Program in IDLE

  1. Open Python IDLE.
  2. Select File > New File.
  3. Write your Python code in the editor window.
  4. Select File > Save or File > Save As.
  5. Choose a suitable folder.
  6. Enter a filename such as first_program.py.
  7. Save the file.

12.2 Organizing Your Project

For a simple project, use a structure such as:

python-practice/
    first_program.py
    calculator.py
    student_result.py

For larger projects, you may add separate folders for source modules, tests, documentation, and other resources.

13. Executing a Python Program

Once the code is saved, you can execute it using IDLE, a terminal, or an editor with Python support.

13.1 Running a Program in IDLE

  1. Open the saved Python file in the IDLE editor.
  2. Save any recent changes.
  3. Select Run > Run Module.
  4. In standard IDLE setups, you can commonly press F5.
  5. Check the Shell window for program output or error messages.

13.2 Running a Program on Windows

Open Command Prompt or PowerShell and navigate to the directory containing the file.

cd path\to\your\project
python first_program.py

If your installation uses the Python launcher, you can also try:

py first_program.py

13.3 Running a Program on macOS or Linux

cd path/to/your/project
python3 first_program.py

Use the command appropriate for your installation. If Python reports that the file cannot be found, confirm the working directory and the exact filename.

13.4 Understanding Program Output

When a program runs successfully, it performs its instructions and displays output wherever the program sends it. For simple beginner programs, output usually appears in the terminal or IDLE Shell.

If the program accepts input, it may pause until the user enters the requested values. If an error occurs, Python may display a traceback describing where execution failed.

14. What Is Debugging?

Debugging is the systematic process of locating, understanding, and correcting defects in a program. A program can execute without crashing and still contain a logical error that produces an incorrect answer.

Debugging is not simply changing lines until the program appears to work. It involves observing the program, identifying a reproducible problem, examining relevant values and execution steps, making a justified correction, and testing the result again.

14.1 Why Debugging Is Important

  • It helps identify the causes of incorrect results.
  • It reduces the time spent searching for defects.
  • It improves program reliability and maintainability.
  • It helps developers understand how their code executes.
  • It can reveal invalid inputs and overlooked edge cases.
  • It prevents small mistakes from becoming larger problems.

15. Types of Errors in Python

Understanding the type of error is an important first step toward fixing it. Beginner Python programs commonly encounter syntax errors, runtime exceptions, and logical errors.

Error Type Description Example Typical Solution
Syntax error Python cannot parse the code. Missing colon after an if statement. Correct the syntax and punctuation.
Runtime error An exception occurs while the program executes. Dividing a number by zero. Inspect the traceback and handle the invalid operation.
Logical error The program runs but produces an incorrect result. Using addition instead of multiplication. Review the algorithm and verify calculations.
Input error The input does not match the expected format or range. Entering letters when an integer is required. Validate input and handle conversion errors.
Environment error The program cannot find a required file, module, or resource. Importing a package that is not installed in the active environment. Verify file paths, interpreter selection, and dependencies.

16. Understanding Syntax Errors

A syntax error occurs when Python cannot interpret the code because it does not follow the language's grammar.

16.1 Example of a Syntax Error

if 10 > 5
    print("Ten is greater")

The condition is missing a colon at the end of the if statement.

16.2 Corrected Code

if 10 > 5:
    print("Ten is greater")

16.3 Common Causes of Syntax Errors

  • Missing colons after if, for, while, or function definitions.
  • Unclosed quotation marks.
  • Missing or mismatched parentheses and brackets.
  • Misspelled Python keywords.
  • Incorrect indentation in compound statements.

When a syntax error appears, read the error message and inspect the indicated line. The actual mistake may sometimes be on the preceding line, particularly when a string or bracket has not been closed.

17. Understanding Runtime Errors and Exceptions

A runtime error occurs while Python is executing a program. Many runtime problems are represented by exceptions, which can sometimes be handled with try and except blocks.

17.1 Example: Division by Zero

number = 10
divisor = 0

result = number / divisor
print(result)

This program raises a ZeroDivisionError because division by zero is not allowed for ordinary numeric division in Python.

17.2 Corrected Code

number = 10
divisor = 0

if divisor != 0:
    result = number / divisor
    print("Result:", result)
else:
    print("Error: divisor cannot be zero.")

This version checks the divisor before performing the division.

17.3 Handling Invalid Numeric Input

try:
    age = int(input("Enter your age: "))
    print("Your age is:", age)
except ValueError:
    print("Please enter a valid whole number.")

The try block contains the operation that may fail. If the user enters text that cannot be converted to an integer, the except block handles the resulting ValueError.

Handle only exceptions that you can respond to meaningfully. Avoid using a broad exception handler to hide programming defects or silently ignore failures.

18. Identifying Logical Errors

A logical error occurs when the program runs but does not perform the intended calculation or operation. These errors can be harder to identify because Python may not display an exception.

18.1 Example of a Logical Error

Suppose a program should calculate the total cost of several products.

price = 50
quantity = 4

total = price + quantity
print("Total cost:", total)

The program runs, but the calculation is incorrect because total cost should be calculated by multiplying the price by the quantity.

18.2 Corrected Code

price = 50
quantity = 4

total = price * quantity
print("Total cost:", total)

Output

Total cost: 200

18.3 Ways to Find Logical Errors

  • Compare the output with the expected result.
  • Test the program with simple values that are easy to calculate manually.
  • Print intermediate values to inspect the calculation.
  • Check formulas, conditions, loop boundaries, and variable assignments.
  • Test boundary values and unusual but valid inputs.
  • Break complex calculations into smaller steps.

19. Reading Python Error Messages and Tracebacks

A traceback is a report that shows the sequence of function calls leading to an unhandled exception. It usually identifies the source file, line number, and exception type, and may include a description of the problem.

19.1 Example

def divide(a, b):
    return a / b

result = divide(10, 0)
print(result)

The program raises a ZeroDivisionError. The traceback identifies the line where division was attempted and the earlier call that passed the arguments.

19.2 How to Read a Traceback

  1. Start at the bottom of the traceback to identify the exception type and message.
  2. Read the file and line information to locate the failing operation.
  3. Follow the call sequence to understand how execution reached that line.
  4. Inspect the variables and inputs used by the operation.
  5. Correct the underlying cause and run the program again.

The last line often provides the clearest summary of the exception, but the preceding lines are important for identifying its origin.

20. Using print() for Debugging

Print debugging is a simple technique in which you add temporary print() statements to display variables and intermediate results. It is useful for beginners and for quickly investigating small programs.

20.1 Example

price = 120
quantity = 3
discount = 20

print("Price:", price)
print("Quantity:", quantity)
print("Discount:", discount)

subtotal = price * quantity
print("Subtotal:", subtotal)

total = subtotal - discount
print("Final total:", total)

Expected Output

Price: 120
Quantity: 3
Discount: 20
Subtotal: 360
Final total: 340

The printed values make it easier to see how the subtotal and final total are calculated.

20.2 Advantages of Print Debugging

  • Easy to understand and use.
  • Requires no additional debugging tool.
  • Useful for checking values and program flow.
  • Can quickly expose incorrect assumptions.

20.3 Limitations of Print Debugging

  • Too many print statements can make output difficult to understand.
  • Temporary statements may be forgotten in the final program.
  • Print statements do not automatically pause execution at a chosen line.
  • They may be less convenient for complex programs with many functions.

Remove unnecessary diagnostic output or replace it with suitable logging before delivering a program.

21. Debugging with Breakpoints

A breakpoint is a location where program execution pauses so that a developer can inspect the current state. Breakpoints are useful when the error depends on a particular sequence of statements or values.

21.1 Breakpoints in an Editor or IDE

  1. Open the Python source file in a debugger-enabled editor.
  2. Choose a line where you want execution to pause.
  3. Set a breakpoint using the editor's debugging interface.
  4. Start the program in debug mode.
  5. When execution pauses, inspect variables and the call stack.
  6. Step through the code to observe how values change.
  7. Continue execution or stop the debugging session.

21.2 What to Inspect at a Breakpoint

  • Values of local and global variables.
  • Function arguments.
  • The current line of execution.
  • The sequence of function calls.
  • Conditions that determine which branch runs.
  • Whether the values match the expected results.

22. Using Python's Built-in Debugger (pdb)

pdb is Python's built-in interactive source-code debugger. It can pause a program, execute code one step at a time, inspect variables, and help developers understand how execution reaches a problem. pdb is part of Python's standard library. See the official Python debugger documentation.

22.1 Debugging with breakpoint()

The built-in breakpoint() function can pause a program and enter the debugger when the default debugger configuration is in use.

def calculate_total(price, quantity):
    subtotal = price * quantity
    breakpoint()
    return subtotal

total = calculate_total(50, 4)
print("Total:", total)

When the program reaches breakpoint(), execution pauses and a debugger prompt normally appears in the terminal or execution console.

22.2 Common pdb Commands

Command Purpose
n or next Execute the next line without stepping into a called function.
s or step Execute the current line and step into a called function when applicable.
c or continue Continue execution until another breakpoint or program completion.
p variable Print the value of an expression or variable.
pp variable Pretty-print an expression or variable's value.
l or list Display source lines around the current location.
where or w Display the current call stack.
q or quit Quit the debugger.

22.3 Example Debugging Session

At the debugger prompt, you might inspect the current values:

(Pdb) p price
50
(Pdb) p quantity
4
(Pdb) p subtotal
200
(Pdb) n
(Pdb) c

These commands are illustrative. The exact prompt and available variable names depend on the program's current execution state.

22.4 Running a Script with pdb

You can start a script under the debugger from a terminal:

python -m pdb first_program.py

On systems where the Python 3 command is python3, use:

python3 -m pdb first_program.py

Use the command corresponding to the Python interpreter you intend to debug.

23. Debugging a Program Step by Step

A structured debugging process makes it easier to find the real cause of a problem instead of repeatedly changing code without a clear reason.

  1. Reproduce the problem: Run the program with the input that causes the unexpected behavior.
  2. Identify the expected result: Write down what the program should do.
  3. Observe the actual result: Compare the output with the expected result.
  4. Locate the suspicious code: Check the relevant function, expression, condition, or input.
  5. Inspect variable values: Use print statements, a debugger, or an appropriate logging method.
  6. Form a hypothesis: Identify a likely reason for the incorrect behavior.
  7. Make one focused change: Correct the underlying cause.
  8. Run the test again: Confirm that the original issue has been resolved.
  9. Test related cases: Check that the fix has not introduced another problem.
  10. Clean up: Remove temporary debugging statements and unused code.

24. Complete Example: A Simple Calculator

This beginner project combines variables, input, arithmetic, conditions, functions, and exception handling. It also demonstrates how to make a program more reliable by validating user input.

24.1 Source Code

def calculate(a, b, operator):
    if operator == "+":
        return a + b
    elif operator == "-":
        return a - b
    elif operator == "*":
        return a * b
    elif operator == "/":
        if b == 0:
            raise ZeroDivisionError("Cannot divide by zero.")
        return a / b
    else:
        raise ValueError("Unsupported operator.")

try:
    first = float(input("Enter the first number: "))
    operator = input("Enter an operator (+, -, *, /): ")
    second = float(input("Enter the second number: "))

    result = calculate(first, second, operator)
    print("Result:", result)

except ValueError as error:
    print("Input or operation error:", error)
except ZeroDivisionError as error:
    print("Calculation error:", error)

24.2 Sample Execution

Enter the first number: 20
Enter an operator (+, -, *, /): *
Enter the second number: 5
Result: 100.0

24.3 How the Program Works

  • The calculate() function receives two numbers and an operator.
  • Conditional statements choose the correct arithmetic operation.
  • The division branch checks for a zero divisor.
  • An unsupported operator raises a ValueError.
  • The main program converts numeric input to floating-point values.
  • The exception handlers display understandable messages for the errors they handle.

24.4 Debugging Practice

  • Enter valid numbers and test each supported operator.
  • Enter zero as the second number when using division.
  • Enter letters instead of a number and observe the error handling.
  • Enter an unsupported operator such as % and inspect the message.
  • Set a breakpoint inside calculate() and inspect the arguments.

Notice that the except ValueError block handles both invalid numeric conversions and unsupported operators in this example. A larger application could validate these cases separately to provide more specific feedback.

25. Common Debugging Problems and Their Solutions

Problem Possible Cause Solution
Program does not start Python is not installed correctly, or the command is unavailable. Verify Python installation and use the appropriate interpreter command.
SyntaxError Missing punctuation, invalid syntax, or an unclosed string. Review the indicated line and nearby lines.
NameError A variable or function name is undefined or misspelled. Check spelling, scope, and whether the name is defined before use.
TypeError An operation is incompatible with the supplied data types. Inspect types and convert values where appropriate.
ValueError A value has the wrong format for an operation. Validate input and handle conversion failures.
ZeroDivisionError A division operation uses zero as the divisor. Check the divisor or handle the exception.
Incorrect output The algorithm or calculation is wrong. Verify the logic and inspect intermediate values.
Unexpected loop behavior The loop condition or update step is incorrect. Check the condition, starting value, and iteration updates.
ModuleNotFoundError A required module is unavailable in the active environment. Check the selected interpreter and install the required package in the correct environment if needed.
FileNotFoundError A file path is incorrect or the file is missing. Check the working directory, filename, and file location.

26. Testing Your Python Program

Testing checks whether a program behaves as expected for different inputs and conditions. Debugging helps locate and correct defects, while testing provides evidence that the program works for the cases being checked.

26.1 Test Normal Inputs

Use typical, valid inputs to verify that the main functionality works correctly.

26.2 Test Boundary Values

Check values near important limits. For a program that determines whether a person is an adult at age 18, test ages 17, 18, and 19.

26.3 Test Invalid Inputs

Check how the program responds when users enter values in the wrong format, omit required information, or choose unsupported options.

26.4 Test Repeated Execution

Run the program more than once to check whether it depends on leftover state, temporary files, or assumptions from earlier executions.

26.5 Simple Test Table

Test Case Input Expected Behavior
Normal addition 10 and 5 Displays 15.
Zero value 0 and 5 Handles zero according to the calculation's rules.
Negative value -10 and 5 Calculates correctly if negative numbers are supported.
Invalid number Text instead of a number Displays a useful validation message.
Division by zero 10 divided by 0 Prevents an unhandled division error and explains the issue.

27. Best Practices for Writing and Debugging Python Code

  • Understand the problem before writing code.
  • Begin with a small working solution and add complexity gradually.
  • Use descriptive names for variables, functions, and files.
  • Follow Python's indentation rules consistently.
  • Break complex logic into small functions.
  • Use comments and docstrings where they clarify intent.
  • Read the full traceback instead of focusing only on the exception name.
  • Test edge cases and invalid inputs.
  • Use breakpoints or pdb when print statements are not sufficient.
  • Handle expected exceptions without hiding unrelated programming errors.
  • Remove temporary debugging code before finalizing the program.
  • Run tests after making changes to ensure existing behavior still works.
  • Keep the code readable and avoid unnecessary duplication.
  • Use version control for projects that need change tracking and collaboration.

28. Practical Exercises

Exercise 1: Hello World

Write a program that prints your name, your course, and a message welcoming users to Python programming.

Exercise 2: Basic Calculator

Accept two numbers and display their sum, difference, product, and quotient. Handle division by zero.

Exercise 3: Even or Odd

Ask the user for an integer and determine whether it is even or odd using the remainder operator.

Exercise 4: Grade Calculator

Accept marks and display a grade category based on defined thresholds. Test values at and around each threshold.

Exercise 5: Find a Logical Error

Write a program that calculates the average of three numbers. Deliberately change the formula to use the wrong divisor, observe the incorrect output, and correct it.

Exercise 6: Debug with pdb

Create a function that calculates the total price of an item. Insert breakpoint() before returning the total and inspect the input values and calculated result.

29. Mini Project: Student Result Management Program

Project Objective: Create a program that accepts a student's name and marks, calculates the average, and displays a result category. The program should validate the input and provide helpful error messages.

29.1 Source Code

def calculate_average(marks):
    return sum(marks) / len(marks)

def get_result_category(average):
    if average >= 75:
        return "Distinction"
    elif average >= 60:
        return "First Class"
    elif average >= 40:
        return "Pass"
    else:
        return "Needs Improvement"

try:
    student_name = input("Enter student name: ").strip()

    if not student_name:
        raise ValueError("Student name cannot be empty.")

    marks = []

    for subject in range(1, 4):
        mark = float(input(f"Enter marks for subject {subject}: "))

        if mark < 0 or mark > 100:
            raise ValueError("Marks must be between 0 and 100.")

        marks.append(mark)

    average = calculate_average(marks)
    category = get_result_category(average)

    print("\n--- Student Result ---")
    print("Student:", student_name)
    print("Average:", round(average, 2))
    print("Result:", category)

except ValueError as error:
    print("Invalid input:", error)

29.2 Project Features

  • Accepts the student's name.
  • Collects marks for three subjects.
  • Validates that each mark is within the range of 0 to 100.
  • Calculates the average using a separate function.
  • Uses another function to determine the result category.
  • Displays the average and result.
  • Handles invalid numeric input and validation errors.

29.3 Debugging Challenges

  • Test the program with marks of 0 and 100.
  • Enter a negative mark and verify the error message.
  • Enter a mark greater than 100.
  • Enter text instead of a numeric mark.
  • Test averages around 40, 60, and 75.
  • Temporarily change the average formula and use print statements or a breakpoint to find the mistake.

30. Interview Questions and Answers

Q1. What is a Python program?

Answer: A Python program is a set of instructions written in Python that the interpreter executes to perform a task.

Q2. How do you write your first Python program?

Answer: Create a Python source file, write a simple statement such as print("Hello, World!"), save the file with a .py extension, and run it using Python.

Q3. How do you execute a Python program?

Answer: You can run a program from IDLE, an IDE, or a terminal using the appropriate Python command, such as python first_program.py or python3 first_program.py.

Q4. What is debugging?

Answer: Debugging is the process of identifying, understanding, and correcting defects in a program.

Q5. What are the main types of programming errors?

Answer: Common categories include syntax errors, runtime errors or exceptions, and logical errors.

Q6. What is a syntax error?

Answer: A syntax error occurs when Python cannot parse code because it violates the language's syntax rules.

Q7. What is a runtime error?

Answer: A runtime error occurs during program execution. Examples include division by zero and attempting to convert invalid text into an integer.

Q8. What is a logical error?

Answer: A logical error occurs when a program runs but produces an incorrect result because its algorithm or logic is wrong.

Q9. What is a traceback?

Answer: A traceback shows the sequence of calls leading to an unhandled exception and helps identify the source location and type of the error.

Q10. What is print debugging?

Answer: Print debugging involves displaying variable values and intermediate results to understand the program's behavior.

Q11. What is a breakpoint?

Answer: A breakpoint is a location where a debugger pauses execution so the developer can inspect variables and follow the program step by step.

Q12. What is pdb?

Answer: pdb is Python's built-in interactive debugger. It supports stepping through code, inspecting values, and examining the call stack.

Q13. What does breakpoint() do?

Answer: It invokes the configured debugging mechanism and normally pauses execution in the debugger when the default configuration is used.

Q14. Why should functions be used in Python programs?

Answer: Functions organize code into reusable units, reduce duplication, improve readability, and make individual operations easier to test.

Q15. What is the difference between testing and debugging?

Answer: Testing checks whether a program behaves as expected for particular cases. Debugging investigates and corrects the causes of defects discovered during testing or execution.

Q16. How can you prevent invalid input from crashing a program?

Answer: Validate the input, convert it carefully, and handle expected exceptions such as ValueError with suitable error messages.

Q17. Why can a program run successfully but still be wrong?

Answer: Python may execute the code without errors even when the algorithm or calculation is incorrect. This is a logical error, which must be identified through inspection and testing.

Q18. What should you do after fixing a bug?

Answer: Rerun the original failing test, check related cases, and confirm that the correction has not introduced another problem.

31. Quick Revision Checklist

  • A Python program is a sequence of instructions executed by the interpreter.
  • Python source files commonly use the .py extension.
  • The print() function displays output.
  • The input() function reads user input as a string.
  • Variables store references to values or objects.
  • Conditions make decisions, and loops repeat instructions.
  • Functions organize reusable program logic.
  • Execution runs the program so its behavior can be observed.
  • Syntax errors prevent invalid code from being parsed.
  • Runtime exceptions occur during execution.
  • Logical errors produce incorrect behavior or results.
  • Tracebacks help identify where an exception occurred.
  • Print statements and breakpoints help inspect program state.
  • pdb provides interactive debugging tools.
  • Testing after a fix helps confirm that the program works as expected.

32. Conclusion

Writing, executing, and debugging your first Python program introduces the core habits required for effective software development. Writing code turns a problem into a set of instructions, execution reveals how those instructions behave, and debugging helps locate and correct mistakes.

By practicing with variables, user input, conditions, loops, functions, error handling, and debugging tools, beginners can build confidence and develop programs that are easier to understand, test, and maintain. Start with small programs, test them with different inputs, read error messages carefully, and improve the solution step by step.

Continue learning through the Python Training Course at JustAcademy, register through the course demo registration page, or explore other learning resources on the JustAcademy official website.

whatsapp