UNIT 5: INTRODUCTION TO PYTHON

Published on June 29, 2025 by @mritxperts

Complete Study Notes

What is Python?

Python is a high-level, interpreted programming language that was created by Guido van Rossum in 1991. It’s named after the British comedy group “Monty Python’s Flying Circus.” Python has become one of the most popular programming languages worldwide due to its simplicity and versatility.

Key Features of Python

1. Simple and Easy to Learn

  • Python has a clean, readable syntax that resembles natural English
  • Fewer lines of code compared to other programming languages
  • Perfect for beginners

2. Interpreted Language

  • Python code is executed line by line
  • No need to compile the program before running it
  • Errors can be detected and fixed easily

3. Free and Open Source

  • Python is completely free to use and distribute
  • Source code is available for modification

4. Cross-Platform

  • Python programs can run on Windows, Mac, Linux, and other operating systems
  • Write once, run anywhere philosophy

5. Extensive Libraries

  • Huge collection of built-in modules and libraries
  • Libraries for web development, data science, AI, machine learning, and more

Applications of Python

1. Web Development

  • Frameworks like Django and Flask
  • Used by companies like Instagram, Pinterest

2. Data Science and Analytics

  • Libraries like Pandas, NumPy, Matplotlib
  • Popular in research and business intelligence

3. Artificial Intelligence and Machine Learning

  • TensorFlow, PyTorch, Scikit-learn
  • Used in AI research and development

4. Desktop Applications

  • GUI development with Tkinter, PyQt
  • Cross-platform desktop software

5. Game Development

  • Pygame library for 2D games
  • Rapid prototyping of game concepts

6. Automation and Scripting

  • Task automation
  • System administration scripts

Installing Python

Windows:

  1. Visit python.org
  2. Download the latest Python version
  3. Run the installer
  4. Check “Add Python to PATH”
  5. Complete the installation

Verification: Open Command Prompt and type: python --version

Python Development Environment

1. IDLE (Integrated Development and Learning Environment)

  • Comes pre-installed with Python
  • Built-in editor with syntax highlighting
  • Interactive shell for testing code

2. Command Line Interface

  • Type python in terminal/command prompt
  • Interactive mode for quick testing
  • Exit using exit() or quit()

3. Text Editors and IDEs

  • PyCharm, Visual Studio Code, Sublime Text
  • Advanced features for larger projects

Basic Python Syntax

1. Comments

# This is a single-line comment

"""
This is a
multi-line comment
"""

2. Print Statement

print("Hello, World!")
print('Python is awesome!')

3. Variables and Data Types

Variables:

  • Container to store data values
  • No need to declare variable type
  • Case-sensitive
name = "Alice"
age = 15
height = 5.6
is_student = True

Data Types:

Integer (int):

  • Whole numbers: 1, 100, -50

Float:

  • Decimal numbers: 3.14, -2.7, 0.5

String (str):

  • Text data: “Hello”, ‘Python’, “123”

Boolean (bool):

  • True or False values

4. Type Function

print(type(25))        # <class 'int'>
print(type(3.14))      # <class 'float'>
print(type("Hello"))   # <class 'str'>
print(type(True))      # <class 'bool'>

Input and Output

Input Function:

name = input("Enter your name: ")
age = input("Enter your age: ")
print("Hello", name, "you are", age, "years old")

# Converting input to integer
age = int(input("Enter your age: "))

Output Function:

# Basic print
print("Hello World")

# Print multiple values
print("Name:", "Alice", "Age:", 15)

# Print with separator
print("A", "B", "C", sep="-")  # Output: A-B-C

# Print without newline
print("Hello", end=" ")
print("World")  # Output: Hello World

Operators

1. Arithmetic Operators

a = 10
b = 3

print(a + b)    # Addition: 13
print(a - b)    # Subtraction: 7
print(a * b)    # Multiplication: 30
print(a / b)    # Division: 3.333...
print(a // b)   # Floor Division: 3
print(a % b)    # Modulo: 1
print(a ** b)   # Exponentiation: 1000

2. Comparison Operators

print(10 == 10)  # Equal to: True
print(10 != 5)   # Not equal to: True
print(10 > 5)    # Greater than: True
print(10 < 5)    # Less than: False
print(10 >= 10)  # Greater than or equal: True
print(10 <= 5)   # Less than or equal: False

3. Logical Operators

print(True and False)   # False
print(True or False)    # True
print(not True)         # False

Control Structures

1. Conditional Statements (if-elif-else)

age = 16

if age >= 18:
    print("You are an adult")
elif age >= 13:
    print("You are a teenager")
else:
    print("You are a child")

2. Loops

For Loop:

# Loop through a range
for i in range(5):
    print(i)  # Prints 0, 1, 2, 3, 4

# Loop through a string
for letter in "Python":
    print(letter)

# Loop with start, stop, step
for i in range(1, 10, 2):
    print(i)  # Prints 1, 3, 5, 7, 9

While Loop:

count = 1
while count <= 5:
    print(count)
    count += 1  # Same as count = count + 1

Lists

Lists are ordered collections of items that can be changed.

# Creating lists
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = ["hello", 123, True, 3.14]

# Accessing elements
print(fruits[0])    # apple (first element)
print(fruits[-1])   # orange (last element)

# List methods
fruits.append("grape")      # Add to end
fruits.insert(1, "mango")   # Insert at index 1
fruits.remove("banana")     # Remove specific item
last_fruit = fruits.pop()   # Remove and return last item

# List length
print(len(fruits))

# List slicing
print(numbers[1:4])   # Elements from index 1 to 3
print(numbers[:3])    # First 3 elements
print(numbers[2:])    # From index 2 to end

Functions

Functions are reusable blocks of code.

# Defining a function
def greet(name):
    return f"Hello, {name}!"

# Calling a function
message = greet("Alice")
print(message)

# Function with multiple parameters
def add_numbers(a, b):
    return a + b

result = add_numbers(5, 3)
print(result)  # 8

# Function with default parameter
def introduce(name, age=15):
    print(f"My name is {name} and I am {age} years old")

introduce("Bob")        # Uses default age
introduce("Alice", 16)  # Uses provided age

String Operations

text = "Python Programming"

# String methods
print(text.upper())      # PYTHON PROGRAMMING
print(text.lower())      # python programming
print(text.title())      # Python Programming
print(len(text))         # Length of string

# String slicing
print(text[0:6])         # Python
print(text[:6])          # Python
print(text[7:])          # Programming

# String formatting
name = "Alice"
age = 15
print(f"My name is {name} and I am {age} years old")

Common Programming Patterns

1. Finding Maximum of Three Numbers

def find_max(a, b, c):
    if a >= b and a >= c:
        return a
    elif b >= a and b >= c:
        return b
    else:
        return c

result = find_max(10, 20, 15)
print(result)  # 20

2. Check if Number is Prime

def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

print(is_prime(17))  # True
print(is_prime(15))  # False

3. Calculate Factorial

def factorial(n):
    if n == 0 or n == 1:
        return 1
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

print(factorial(5))  # 120

Error Handling

try:
    age = int(input("Enter your age: "))
    print(f"You are {age} years old")
except ValueError:
    print("Please enter a valid number")
except Exception as e:
    print(f"An error occurred: {e}")

Best Practices for Python Programming

  1. Use meaningful variable names
    • Good: student_name, total_marks
    • Bad: x, data1
  2. Write comments for complex code
    • Explain what the code does and why
  3. Follow proper indentation
    • Python uses indentation to define code blocks
    • Use 4 spaces for each level of indentation
  4. Test your code frequently
    • Run small parts of code to check for errors
    • Use print statements to debug
  5. Keep functions small and focused
    • Each function should do one specific task

Sample Programs for Practice

1. Simple Calculator

def calculator():
    num1 = float(input("Enter first number: "))
    operator = input("Enter operator (+, -, *, /): ")
    num2 = float(input("Enter second number: "))
    
    if operator == '+':
        result = num1 + num2
    elif operator == '-':
        result = num1 - num2
    elif operator == '*':
        result = num1 * num2
    elif operator == '/':
        if num2 != 0:
            result = num1 / num2
        else:
            print("Error: Division by zero")
            return
    else:
        print("Invalid operator")
        return
    
    print(f"Result: {result}")

calculator()

2. Grade Calculator

def calculate_grade():
    marks = []
    subjects = ["Math", "Science", "English", "Social Studies", "Hindi"]
    
    for subject in subjects:
        mark = float(input(f"Enter marks for {subject}: "))
        marks.append(mark)
    
    total = sum(marks)
    average = total / len(marks)
    
    if average >= 90:
        grade = "A+"
    elif average >= 80:
        grade = "A"
    elif average >= 70:
        grade = "B"
    elif average >= 60:
        grade = "C"
    else:
        grade = "D"
    
    print(f"Total marks: {total}")
    print(f"Average: {average:.2f}")
    print(f"Grade: {grade}")

calculate_grade()

Important Points for Exams

  1. Python is case-sensitive: Name and name are different variables
  2. Indentation matters: Python uses indentation instead of curly braces
  3. String indexing starts from 0: First character is at index 0
  4. Division operator (/) always returns float, use (//) for integer division
  5. input() function always returns string, use int() or float() to convert
  6. Lists are mutable: Can be changed after creation
  7. Functions must be defined before calling: Define function before using it

Quick Reference

Data Type Conversion:

  • int() – Convert to integer
  • float() – Convert to float
  • str() – Convert to string
  • bool() – Convert to boolean

String Methods:

  • .upper() – Convert to uppercase
  • .lower() – Convert to lowercase
  • .strip() – Remove whitespace
  • .replace(old, new) – Replace text

List Methods:

  • .append() – Add to end
  • .insert() – Insert at position
  • .remove() – Remove specific item
  • .pop() – Remove and return item
  • .sort() – Sort the list

Conclusion

Python is an excellent first programming language due to its simplicity and readability. Master these basic concepts, practice regularly with small programs, and gradually work on more complex projects. Remember that programming is a skill that improves with practice, so don’t get discouraged by initial challenges.

The key to success in Python programming is to:

  • Understand the concepts thoroughly
  • Practice coding regularly
  • Debug errors patiently
  • Build projects to apply your knowledge
  • Keep learning new features and libraries

Good luck with your Python journey!