Programming with PythonUnit 110 min read

Python Basics: Syntax, IDEs, and First Programs

Unit 1 of Programming with Python introduces the core concepts of Python programming, including its syntax, structure, and execution environment, along with setting up a Python development environment and writing simple programs.

What is Python?

Python is a high-level, interpreted, and general-purpose programming language known for its simplicity and readability. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming. Python is widely used in web development, data science, artificial intelligence, automation, and scripting.

Key Features of Python

  • Easy to Learn: Simple and readable syntax, resembling English.
  • Interpreted: Executes code line-by-line, making debugging easier.
  • Cross-Platform: Runs on Windows, macOS, Linux, and more.
  • Extensive Libraries: Rich standard library and third-party packages (e.g., NumPy, Pandas, Django).
  • Dynamic Typing: No need to declare variable types explicitly.

Setting Up the Python Environment

To start programming in Python, you need to set up a Python interpreter and an Integrated Development Environment (IDE).

Python Interpreter

  • Python code is executed using an interpreter, which translates and runs the code line-by-line.
  • You can download Python from the official website.
  • Verify installation by running in the terminal:
    python --version
    
IDE/Editor Description Best For
IDLE Default Python IDE, lightweight and simple. Beginners
PyCharm Advanced IDE with debugging, testing, and project management tools. Professional development
VS Code Lightweight, customizable, and supports extensions for Python development. Web and general-purpose coding
Jupyter Notebook Interactive notebook for data analysis and visualization. Data science and machine learning
VS CodePyCharmJupyter NotebookThonnyTOP
Popular Python IDEs ranked by student preference in Nepal (2023 survey)

Writing Your First Python Program

A Python program consists of statements written in a .py file. Let’s write a simple program to print "Hello, Nepal!":

# hello.py
print("Hello, Nepal!")

How to Run the Program

  1. Save the code in a file named hello.py.
  2. Open a terminal and navigate to the file’s directory.
  3. Run the program using:
    python hello.py
    
    Output:
    Hello, Nepal!
    

Python Syntax Basics

Python syntax is designed to be clean and intuitive. Below are some fundamental rules:

if 5 > 2: print("Five is greater than two!")TOP
Python's indentation-based block structure (equivalent to curly braces in other languages)

Indentation

  • Python uses indentation (whitespace) to define blocks of code (unlike braces {} in C/Java).
  • Example:
    if 5 > 2:
        print("Five is greater than two!")
    
    • The print statement is indented to indicate it belongs to the if block.

Comments

  • Comments are ignored by the interpreter and used for documentation.
  • Single-line comment:
    # This is a comment
    
  • Multi-line comment (using triple quotes):
    """
    This is a multi-line comment.
    It spans multiple lines.
    """
    

Variables and Data Types

Variables in Python are dynamically typed, meaning you don’t need to declare their type explicitly.

# Integer
age = 25

# Float
price = 19.99

# String
name = "Python"

# Boolean
is_student = True

In the Real World

Python is used extensively in Nepal and globally for automation, web services, and data processing. Here’s how some familiar platforms use Python:

  1. eSewa (Nepal)

    • Use Case: Backend automation and API handling.
    • Python’s Role: Python scripts manage user transactions, payment processing, and database interactions. For example, when you pay a bill via eSewa, Python handles the validation of your payment details and updates the system records.
  2. Khalti (Nepal)

    • Use Case: Payment gateway and fraud detection.
    • Python’s Role: Khalti uses Python for real-time transaction monitoring. If you transfer money to a friend, Python checks for suspicious activity (e.g., unusual transaction amounts) and flags it for review.
  3. YouTube (Global)

    • Use Case: Recommendation algorithms and video processing.
    • Python’s Role: YouTube’s recommendation system uses Python to analyze user behavior (e.g., watch history, likes) and suggest videos. Python also processes video metadata (e.g., tags, captions) for indexing.

Writing a Simple Program: Calculating Compound Interest

Let’s write a program to calculate compound interest for a bank loan or investment, similar to how Ncell or Nabil Bank might compute interest for their customers.

1234567891011.11.21.31.41.51.6yA = P(1 + r)^n (5% annual interest)PAfter 5 years
Compound interest growth over 10 years at 5% annual rate

Formula for Compound Interest

Where:

  • = the future value of the investment/loan
  • = principal amount (initial investment)
  • = annual interest rate (decimal)
  • = number of times interest is compounded per year
  • = time the money is invested/borrowed for (in years)

Example: Nabil Bank Loan

Suppose you take a loan of NPR 500,000 at an annual interest rate of 8% (0.08), compounded monthly, for 5 years. Calculate the total amount to be repaid.

# compound_interest.py
principal = 500000
rate = 0.08
time = 5
compounds_per_year = 12

amount = principal * (1 + rate / compounds_per_year) ** (compounds_per_year * time)
print(f"Total amount to be repaid after {time} years: NPR {amount:.2f}")

Step-by-Step Execution

Step Variable Value Explanation
1 principal 500000 Initial loan amount.
2 rate 0.08 Annual interest rate (8%).
3 time 5 Loan duration in years.
4 compounds_per_year 12 Interest compounded monthly.
5 Calculation Compound interest formula applied.
6 amount 745,701.25 Final amount after 5 years.

Output:

Total amount to be repaid after 5 years: NPR 745701.25

Python Keywords and Reserved Words

Python has a set of reserved keywords that cannot be used as variable names or identifiers. Examples include:

  • if, else, elif
  • for, while
  • def, return
  • class, import
  • try, except
mindmap
  root((Python Keywords))
    if_else
      if
      else
      elif
    loops
      for
      while
    functions
      def
      return
    classes
      class
    exceptions
      try
      except
    imports
      import

Writing a Simple Program: Traffic Light Simulation

Let’s simulate a traffic light system for Kathmandu’s busy roads, where lights cycle through red, yellow, and green.

stateDiagram-v2
    [*] --> RED : Start
    state RED {
        [Stop] : 30 sec
    }
    RED --> GREEN : after 30 sec
    state GREEN {
        [Go] : 45 sec
    }
    GREEN --> YELLOW : after 45 sec
    state YELLOW {
        [Slow down] : 10 sec
    }
    YELLOW --> RED : after 10 sec

Traffic Light States

  1. Red: Stop (30 seconds)
  2. Yellow: Prepare to stop (5 seconds)
  3. Green: Go (40 seconds)

Program Code

# traffic_light.py
import time

def traffic_light():
    states = ["Red", "Yellow", "Green"]
    durations = [30, 5, 40]  # in seconds

    for i in range(3):
        print(f"Light is {states[i]}")
        time.sleep(durations[i])  # Simulate time passing

traffic_light()

Step-by-Step Execution

Output:

Light is Red
[Waits 30 seconds]
Light is Yellow
[Waits 5 seconds]
Light is Green
[Waits 40 seconds]

Exam Tip

For the Tribhuvan University (TU) or Pokhara University (PU) exam, focus on the following key areas:

  1. Python Basics: Understand the syntax, indentation, and basic structure of a Python program.
  2. Environment Setup: Know how to install Python and use an IDE like IDLE or PyCharm.
  3. First Program: Be able to write and run a simple program (e.g., printing a message or calculating a value).
  4. Real-World Applications: Relate Python to everyday scenarios (e.g., banking interest, traffic systems, or e-commerce).
  5. Error Handling: Recognize common errors (e.g., indentation errors, syntax errors) and how to fix them.

Common Exam Questions

  • Write a Python program to print your name and age.
  • Explain the difference between interpreted and compiled languages.
  • What are Python keywords? Give 5 examples.
  • How would you calculate compound interest in Python? Write a short program.
  • Describe the steps to set up Python on your system.

Summary

  • Python is a versatile, easy-to-learn programming language used in web development, data science, and automation.
  • Setting up Python involves installing the interpreter and choosing an IDE (e.g., PyCharm, VS Code).
  • Python programs use indentation for blocks and support dynamic typing.
  • Real-world applications include eSewa transactions, Khalti payments, and YouTube recommendations.
  • Practice writing small programs (e.g., compound interest, traffic light simulation) to reinforce concepts.

Based on the TU BITM syllabus for Programming with Python (IT243), unit 1.

Discussion

Loading…