smartyfy.mrindigi.com

Python Master Course V2 — 003. Your First Python Program

Module 01 · Python foundations · Lesson 003 / 200

Your First Python Program

Write, run, understand and debug real Python programs—not just copy code. Build confidence in the editor, terminal and Python interpreter with practical exercises and a working mini-project.

Level: Beginner   •   Study: 60–90 minutes + practice   •   Prerequisite: Lesson 002

In this lesson · 15 sections + self-check
  1. ▶ Lesson video
  2. 01. Learning objectives
  3. 02. What really happens when a Python program runs?
  4. 03. Lab 1 — Create and execute hello.py
  5. 04. Lab 2 — Print text, numbers and results
  6. 05. Comments and readable code
  7. 06. Lab 3 — Store and reuse information
  8. 07. Lab 4 — Make the program interactive
  9. 08. Lab 5 — Format meaningful output with f-strings
  10. 09. Debugging laboratory — Learn from errors
  11. 10. Guided mini-project — Interactive shopping receipt
  12. 11. Practice tasks — Build without copying
  13. 12. Independent challenge — Study-session tracker
  14. 13. Knowledge check
  15. 14. Lesson summary and completion checklist
  16. Interactive self-check

▶ Lesson video

🎬 Video lesson 003

Video coming soon — dedicated player/link location reserved for this lesson.

VIDEO_URL_LESSON_003 — replace with an approved YouTube, Vimeo, or self-hosted video URL. Do not insert an empty iframe.

Video chapter plan: 00:00 Introduction · 03:00 Create your first file · 10:00 Understand print() · 19:00 Editor versus interpreter · 28:00 Input and output · 39:00 Debugging · 51:00 Mini-project.

01. Learning objectives

By the end of this lesson, you will be able to:

  • Create and save a Python source file with the .py extension.
  • Run a script from a code editor or terminal and inspect its output.
  • Explain what the Python interpreter does and distinguish source code from output.
  • Use print() with text, numbers and simple expressions.
  • Recognize comments, literal values, basic variables and user input without needing to master these topics yet.
  • Investigate SyntaxError, NameError and ValueError systematically.
  • Build and test a small interactive receipt generator.

Before you start

Lesson 002 should have given you a working Python 3 installation, an editor such as VS Code and the ability to open a terminal. Verify that one of these commands shows an installed Python 3 version:

python --version
# or on many Windows systems:
py --version
# or on many macOS/Linux systems:
python3 --version

These commands are alternatives, not commands you must run together. If one is unrecognized, try the appropriate alternative. You should see a Python 3 version; the exact version number can differ.

02. What really happens when a Python program runs?

Think of your code as a precisely written recipe. The source file holds the instructions. The Python interpreter reads and executes them. Some instructions calculate values; others display text or request input. The output is what the program actually produces.

The core flow: Write hello.py → save the file → execute it with Python → read the output → revise and rerun.

Important: A script file is not itself the same as a terminal command. A terminal invokes an interpreter to run the script, whereas your editor provides tools for writing and sometimes running the program. Both approaches execute Python code.

03. Lab 1 — Create and execute hello.py

Step A: Make a working folder

Reopen the smartyfy-python-lab folder created in Lesson 002 and select its .venv interpreter in your editor. Activate that environment in your terminal, or use its interpreter directly. Reuse this workspace so packages and scripts stay in the same environment. You can save separate scripts for each exercise.

Step B: Save this file

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

print("Hello, Python!")
print("Welcome to Smartyfy.")
print("Lesson 003: My first program")

Step C: Run it

In a terminal opened in the same folder, run the version appropriate to your computer:

python hello.py
# Without activation on Windows:
.\.venv\Scripts\python.exe hello.py
# Without activation on macOS/Linux:
.venv/bin/python hello.py

Comments beginning with # above are explanatory notes, not additional commands. Run exactly one of the three alternatives.

Expected output

Hello, Python!
Welcome to Smartyfy.
Lesson 003: My first program

Understand every part

print is a built-in Python function. Parentheses () contain the value or values passed to it. Quotation marks surround a string (text). Each call prints a line, and by default a newline follows it. If you see the expected three lines, you have successfully written and executed a complete program.

Try changing "Hello, Python!" to "Hello, world!". Save and rerun. Changing the file without saving it is a common reason old output keeps appearing.

04. Lab 2 — Print text, numbers and results

Not everything passed to print() is text. Python can print numeric values or the result of calculations. Copy and execute this example in output_demo.py:

print("Python can calculate:")
print(7 + 5)
print(20 - 8)
print(6 * 4)
print(15 / 2)

Expected results: the introductory text followed by 12, 12, 24 and 7.5 on separate lines. Notice the crucial difference:

print("7 + 5")  # prints the literal characters 7 + 5
print(7 + 5)    # calculates and prints 12

This distinction between text containing symbols and an expression to evaluate matters throughout programming.

Displaying several values

print("Course:", "Python Master Course V2")
print("Lesson number:", 3)
print("Sum:", 10 + 20)

Commas separate individual arguments; by default print() inserts a space between them. Later, you will learn how to control separators, line endings and formatted output.

05. Comments and readable code

A comment begins with # outside a string. The interpreter ignores the comment text. Use comments to explain why a non-obvious step exists, not to restate every visible operation.

# A simple price example for a training exercise
print("Notebook price:", 75)
print("Quantity:", 4)
print("Total:", 75 * 4)

Descriptive file names (hello.py, receipt.py) and consistent formatting also make code easier to maintain. In later lessons you will learn Python style conventions more deeply.

06. Lab 3 — Store and reuse information

Imagine replacing the same name in ten different lines. A variable lets you store a value under a meaningful name and reuse it. This lesson gives only an introduction; Lesson 005 covers variables in detail.

student_name = "Ananya"
lesson_number = 3
course = "Python Master Course V2"

print("Student:", student_name)
print("Course:", course)
print("Current lesson:", lesson_number)

The equals sign assigns a value. Python reads the variable name in print() and uses its stored value. A variable name is not printed literally unless you put it inside quotes.

Experiment: Change student_name once. Notice that the printed output updates without editing the print() statement.

07. Lab 4 — Make the program interactive

The built-in input() function prints a prompt, waits for the user to type something, and returns the response as a string. Try this in greeting.py:

name = input("What is your name? ")
city = input("Which city are you learning from? ")

print("Hello,", name)
print("Welcome to Python from", city)

Example interaction: If the learner enters Ravi and Hyderabad, the output includes Hello, Ravi and Welcome to Python from Hyderabad. Your output varies with your answers; that is expected.

A crucial type-conversion idea

Even if the user types 5, input() returns the string "5". You cannot assume it is already an integer. When numeric input is needed, convert explicitly:

age_text = input("Enter your age in whole years: ")
age = int(age_text)
print("Your age next year will be:", age + 1)

If the input is not a valid integer, int() raises ValueError. Later lessons cover validation and error handling; for now, enter a valid whole number such as 20.

08. Lab 5 — Format meaningful output with f-strings

Formatted string literals, called f-strings, allow values and expressions to appear inside text. Place an f immediately before the quoted string and enclose an expression in braces:

item = "Notebook"
price = 79.50
quantity = 3
total = price * quantity

print(f"Item: {item}")
print(f"Quantity: {quantity}")
print(f"Total price: ₹{total:.2f}")

Expected total: ₹238.50. The :.2f formatting instruction displays a numeric value using two digits after the decimal point. The currency symbol here is only presentation; later chapters discuss production-grade currency handling, including why floating-point arithmetic is not ideal for exact financial calculations.

09. Debugging laboratory — Learn from errors

Errors are a normal and valuable part of learning programming. Read the last line of a traceback first. It often tells you both the error type and the immediate problem. Then inspect the file name and line number.

Problem A: Missing closing parenthesis

print("Welcome"

This produces a SyntaxError because the expression is incomplete. Fix: print("Welcome").

Problem B: Name not defined

print(student_name)

If you never assigned student_name in this run, Python raises NameError. Fix: define the variable first or correct its spelling.

Problem C: Numeric text is not a number yet

quantity = input("Quantity: ")
print(quantity + 1)

This produces TypeError when you attempt to add an integer to a string. Fix: use int(quantity) before arithmetic, with valid numeric input.

Problem D: The terminal cannot find the script

If the terminal reports it cannot open hello.py, verify the current folder, file spelling, and extension; your editor may be saving the file elsewhere. Use your editor’s integrated terminal opened in the project folder to reduce path errors.

Professional debugging routine: Reproduce → read the full message → find the smallest failing line → form a hypothesis → change one thing → rerun → confirm the fix.

10. Guided mini-project — Interactive shopping receipt

Scenario: A small shop needs a script to accept the buyer name, item, unit price and quantity, then print a neat receipt. This project brings together output, input, conversion, variables, arithmetic and formatting.

Requirements

  1. Ask for the customer name and item name.
  2. Request the price for one item and the quantity.
  3. Convert numeric responses to suitable types.
  4. Calculate the total and display a readable receipt.
  5. Use exactly two decimal places when displaying the amount.

Complete runnable solution (receipt.py)

print("=== SMARTYFY SHOP RECEIPT ===")

customer = input("Customer name: ")
item = input("Item name: ")
unit_price = float(input("Price per item: "))
quantity = int(input("Quantity: "))

total = unit_price * quantity

print()
print("---------- RECEIPT ----------")
print(f"Customer : {customer}")
print(f"Item     : {item}")
print(f"Quantity : {quantity}")
print(f"Unit cost: ₹{unit_price:.2f}")
print(f"Total    : ₹{total:.2f}")
print("-----------------------------")
print("Thank you for shopping!")

Example test

Enter customer Meera, item Pen, price 12.50, and quantity 4. The result should show Quantity : 4, Unit cost: ₹12.50, and Total : ₹50.00.

Line-by-line walkthrough

  1. The header immediately identifies what the program does.
  2. input() gathers customer and item information as strings.
  3. float() converts a price entered as text into a numeric value.
  4. int() converts a whole-number quantity.
  5. unit_price * quantity computes the bill.
  6. print() inserts a blank line before the receipt header.
  7. f-strings place stored values in labels and display amounts to two decimal places.

Real-world engineering note

This is a learning receipt, not production billing software. It currently accepts negative prices/quantities and crashes on invalid numeric input. Professional financial software also requires reliable currency arithmetic, validation, tax rules and tests. Those topics appear in future lessons. For a classroom exercise, use valid, non-negative numeric values.

11. Practice tasks — Build without copying

1. Warm-up: Create profile.py to print your name, city and learning goal on three lines.

Hint

Use a separate print call for each line.

Show answer and explanation

Each call ends with a newline by default. Replace the example name, city, and goal with your own values.

print("Asha")
print("Hyderabad")
print("Build reliable Python programs")

2. Calculate: Display the result of 125 * 8 with a meaningful label.

Hint

Keep the expression outside quotes.

Show answer and explanation

Multiplication happens before print displays the value. The label explains what the number represents.

print("Calculated total:", 125 * 8)

3. Personalize: Update the greeting program so it welcomes a learner to a named course.

Hint

Store the changing information in variables.

Show answer and explanation

Variables let the greeting reuse the learner and course names; the comma separator adds spaces.

name = "Asha"
course = "Python Master Course V2"
print("Welcome", name, "to", course)

4. Format: Show three decimal places for the number 3.14159 using an f-string.

Hint

Use fixed-point formatting with precision 3.

Show answer and explanation

The display is 3.142. Formatting rounds the displayed value and does not assign a new value to the original variable.

value = 3.14159
print(f"{value:.3f}")

5. Modify: Enhance receipt.py with an additional line showing the course or store name.

Hint

Add a descriptive print statement before the receipt details.

Show answer and explanation

For example, add print("Store: Smartyfy Practice Shop") after the receipt heading. It changes presentation while retaining the original calculations.

6. Debug: Deliberately misspell a variable name, read the error, then fix it.

Hint

Compare the spelling in assignment and use.

Show answer and explanation

If you assign learner_name but print learner_nam, a fresh script raises NameError. Correct the spelling to match. The browser runner shares names on this page; reload it before testing an intentionally undefined name.

7. Stretch: Print an additional items remaining line after taking a starting stock and a purchased quantity (assume valid integers).

Hint

Convert both inputs, then subtract purchased quantity from starting stock.

Show answer and explanation

For stock 12 and purchased quantity 3, the remainder is 9. This introductory task assumes valid nonnegative integers and quantity no greater than stock; later validation should enforce those rules.

starting_stock = 12
purchased_quantity = 3
print("Items remaining:", starting_stock - purchased_quantity)

Recommended method: Predict expected behavior before executing each change; do not only check whether the program runs.

12. Independent challenge — Study-session tracker

Build study_tracker.py from a blank file. It should ask for the student’s name, lesson title and the number of minutes studied on two separate days. Convert the entered minutes to integers, calculate the total minutes and print a formatted study summary. Add a line showing the total hours as a decimal number.

Acceptance tests: If the learner reports 35 minutes on Day 1 and 45 minutes on Day 2, the total must be 80 minutes, and the decimal-hour total should be approximately 1.33 when formatted to two decimal places. Test a second pair of values, including zeros.

Reveal a possible solution after your own attempt
name = input("Learner: ")
lesson = input("Lesson: ")
day_one = int(input("Minutes on day 1: "))
day_two = int(input("Minutes on day 2: "))

total_minutes = day_one + day_two
total_hours = total_minutes / 60

print(f"Study summary for {name}")
print(f"Lesson: {lesson}")
print(f"Total: {total_minutes} minutes")
print(f"Hours: {total_hours:.2f}")

13. Knowledge check

1. What extension is normally used for a Python source file?

Hint

Think of the file suffix, not the interpreter name.

Show answer and explanation

Use .py, for example hello.py. Confirm the editor saved that exact filename; an accidental hello.py.txt is a text file with a different extension.

2. How does print("4 + 6") differ from print(4 + 6)?

Hint

Quotation marks change arithmetic into text.

Show answer and explanation

The first displays the characters 4 + 6. The second evaluates the addition and displays 10. Python does not calculate an expression merely because its symbols appear inside a string.

3. What does input() return?

Hint

Check the type even when the typed characters are digits.

Show answer and explanation

input() returns a string. Entering 5 gives "5", so arithmetic requires an explicit conversion when the contract expects a number.

4. What is the purpose of int() in a user-input program?

Hint

Distinguish conversion from validation.

Show answer and explanation

int() converts valid integer text to an integer so arithmetic can use it. Text such as "three" raises ValueError; robust programs must handle invalid input and enforce their allowed range.

5. What does :.2f mean inside an f-string?

Hint

The f means fixed-point display, not the f-string prefix.

Show answer and explanation

It formats a numeric value in fixed-point notation with two decimal places. For example, f"{7.5:.2f}" displays 7.50. Formatting the display does not change how the number was stored or calculated.

6. How can you tell a NameError from a SyntaxError?

Hint

One error is in grammar; the other occurs while looking up a name.

Show answer and explanation

SyntaxError means Python cannot parse the code, such as an unclosed parenthesis. NameError means syntactically valid code refers to a name that has not been defined in that execution. Inspect the exact error and line before choosing a fix.

7. Why must you save a script before you expect your newest changes to appear?

Hint

The interpreter runs the stored file.

Show answer and explanation

The terminal reads the saved script from disk. Unsaved editor changes are not in that file. Save, confirm the filename and folder, then rerun the same script.

8. Why is the receipt mini-project not yet suitable for real financial transactions?

Hint

Check money representation and invalid inputs.

Show answer and explanation

The demonstration uses float and assumes valid input. A real receipt needs exact monetary arithmetic or integer minor units, finite and nonnegative prices, positive integer quantities, and defined rounding and failure behavior. Later lessons build these contracts.

14. Lesson summary and completion checklist

You can now create a .py file, run it from a terminal, print different kinds of values, capture user input, format output with f-strings and investigate common errors. You also built an interactive script that solves a small business-style problem.

Mark yourself ready for Lesson 004 when you can: run hello.py without instructions; explain what each line prints; modify and test an interactive script; and use an error message to find a mistake.

Next topic: Lesson 004 — Understanding Python Syntax and Structure. You will learn indentation, statements, whitespace conventions, identifiers and how Python organizes code.

Apply what you learned

Interactive self-check

Choose an answer for each question, then check your work. You will see the correct answer and why it is correct.

1. What does input() return?
2. What does print(3 * 4) display?
3. Why use an f-string?
4. What is a helpful response to an error?
5. Why test an interactive program with several inputs?

This is a practice quiz. Results are saved on this browser when storage is available.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion and quiz results are stored on this browser.