Friday, September 19, 2025

7.6 Introduction to Python Programming

  7.6 Introduction to Python Programming


7.6 Introduction to Python Programming

 

Python

v Python is a high-level, interpreted, programming language introduced by Guido van Rossum in 1991.

v It is popular because

-        It has a simple and beginner-friendly syntax.

-        It is versatile and can be used in many fields like web development, AI, and data science.

v It provides a wide range of built-in tools and libraries, saving time and effort for programmers. Python is widely used in web development, data science, machine learning, artificial intelligence, automation, game development, and cybersecurity.

v Python is beginner-friendly because its syntax is simple and close to everyday English.

v Python uses indentation (spaces at the beginning of a line) instead of braces { } to define blocks of code. This is unique because it increases readability and makes programs easier to understand.

 

Features of Python

  1. Easy to read and write – Python uses simple and clear syntax, making programs easy to write, understand, and debug.
  2. Versatile – Python can be applied in many fields such as automation, web development, game creation, data science, artificial intelligence, and machine learning.
  3. Beginner-friendly – Because of its simple structure and readability, Python is an excellent first programming language for new learners.
  4. Extensive standard library – Python comes with a wide collection of built-in modules and functions, allowing programmers to perform many tasks without writing code from scratch.
  5. Rich ecosystem – Along with the standard library, Python has thousands of external libraries and frameworks (such as Django, NumPy, and TensorFlow) that make it powerful for advanced programming.

 

Advantages of Python

  1. Python is simple and easy to learn, even for beginners.
  2. It is cross-platform, meaning the same code can run on Windows, Linux, and macOS.
  3. Python is open-source and free, supported by a large global community.
  4. Programs in Python are usually shorter and faster to develop, saving time and effort.
  5. It is widely used in modern and emerging fields such as artificial intelligence, data science, automation, and web applications.

 

Disadvantages of Python

  1. Python is slower than compiled languages like C, C++ or Java because it is interpreted line by line.
  2. It is not ideal for mobile application development, where other languages like Java or Kotlin are preferred.
  3. Python uses more memory, which makes it less efficient for very large or resource-heavy programs.
  4. Because Python uses dynamic typing, some errors may only appear at runtime, which can cause problems if not carefully tested.

 

 

Installation process of Python

The Python installation process involves downloading Python from its official website, running the installer, selecting installation options, and verifying installation by checking the version in Command Prompt or Terminal.

  1. Download Python
    • Visit the official website: https://www.python.org.
    • Go to the Downloads section and choose the version suitable for your operating system (Windows, macOS, or Linux).
  2. Run the Installer
    • Open the downloaded setup file.
    • In Windows, make sure to tick the option “Add Python to PATH” before continuing (this makes Python accessible from the command line).
  3. Choose Installation Type
    • Select Install Now for default settings (recommended for beginners).
    • Or choose Customize Installation if you want to select specific options.
  4. Installation Process
    • The installer will copy Python files to your system.
    • Wait until the progress bar completes and the installation finishes.
  5. Verify Installation
    • Open Command Prompt (Windows) or Terminal (macOS/Linux).
    • Type: python --version
    • If installed correctly, it will display the installed Python version (e.g., Python 3.12.0).

 

Download and Install a Suitable IDE for Python

An IDE (Integrated Development Environment) is software that provides tools to write, edit, and run programs easily. For Python, some popular IDEs are IDLE, PyCharm, VS Code, Jupyter Notebook.

Download and Install VS Code for Python

  1. Download VS Code
    • Go to the official website: https://code.visualstudio.com.
    • Click Download for your operating system (Windows, macOS, or Linux).
  2. Run the Installer
    • Open the downloaded setup file.
    • Accept the license agreement and choose Next.
    • Select Add to PATH and Create Desktop Icon (recommended).
    • Click Install.
  3. Open VS Code
    • Launch the program after installation.
  4. Install Python Extension
    • Click on the Extensions icon (left sidebar).
    • Search for Python and install the extension published by Microsoft.
  5. Configure Python Interpreter
    • Press Ctrl + Shift + P (or Cmd + Shift + P on Mac).
    • Type Python: Select Interpreter.
    • Choose the Python version you installed earlier.
  6. Create and Run Your First Program
    • Make a new file: hello.py.
    • Write: print("Hello, World!")
    • Save the file.
    • Run it by clicking Run in VS Code, or in the terminal with:

python hello.py

7.7 Basic Syntaxes in Python

 

Syntax

·        Syntax refers to the set of rules that define how code must be written so that the computer can understand and execute it.

·        The basic syntax rules in Python include case sensitivity, indentation, use of comments, variables, print statement, and input statement. These rules make Python simple, readable, and easy for beginners.

 

Comments in Python

Comments in Python are non-executable text that help programmers explain code, make notes, or increase readability. They can be written as single-line (using #) or multi-line (using triple quotes - ''' or """ ).

 

Types of Comments in Python

  1. Single-line Comment
    • Example:

# This is a single-line comment

print("Hello, World!")  # This prints a message

  1. Multi-line Comment
    • Example:

'''This is a

multi-line

comment in Python'''

print("Welcome")

Indentation

  • Python uses indentation (spaces or tabs) instead of braces { } to define code blocks.
  • Example:

if 5 > 2:

    print("Five is greater than two")

 

Case Sensitivity

  • Python treats uppercase and lowercase letters as different.
  • Example:

name = "Alex"

print(name)    # Works

print(Name)    # Error, because "Name" ≠ "name"

 

Variables and Assignment

  • A variable is created when a value is assigned with =.
  • Example:

x = 10

name = "Alice"

 

Print Statement

  • Used to display output on the screen.
  • Example:

print("Hello, World!")

 

Input Statement

  • input() is used to take user input.
  • Example:

name = input("Enter your name: ")

print("Hello", name)

 

Keywords

Keywords are reserved words in Python that have predefined meaning and cannot be used as variable names, function names, or identifiers. There are 35 keywords in Python 3 such as if, else, while, def, class, True, False, and None.

7.8 I/O statements and string formatting

 

Input/Output statements (I/O)

I/O (Input/Output) statements in Python are the commands used to take input from the user and display output to the screen.

  • Input Statement → input() function is used to read data from the user. The data is always taken as a string by default.
  • Output Statement → print() function is used to show information, results, or messages to the user.

 

Print Statement

The print statement in Python is used to display information on the screen. We use a ‘print’ statement to display the output of data that we want to show.

 

Example: print(“Hello, Python!”)

 

Input Function

The ‘input’ function allows to provide input to the program. We can give data to the program as we need.

 

Example: number = input(“Enter number: ”)

 

String Formatting

String formatting in Python is the process of displaying variables and values together with text in a structured way.

It can be done using commas in print(), the format() method, or modern f-strings. For example:

 

Different Ways of String Formatting

 

Using % Operator (Old Style)

This is the old style of string formatting, where we use % to insert values into a string.

Example:

name = "Charlie"

age = 22

message = "My name is %s and I am %d years old." % (name, age)

print(message)

Output

My name is Charlie and I am 22 years old.

 

Using format( ) Method (New-style formatting)

The format( ) method allows to insert values into a string using curly braces {} as placeholders.

 

Example 1:

name = "Bob"

age = 30

message = "My name is {} and I am {} years old.".format(name, age)

print(message)

 

Output

My name is Bob and I am 30 years old.

We can also use numbered or named placeholders

 

Example 2:

message = "My name is {0} and I am {1} years old.".format(name, age)

print(message)

 

Example 3:

name = "Alex"

age = 15

print("My name is {} and I am {} years old.".format(name, age))

 

Using commas in print( )

Easiest method but adds spaces automatically.

 

Example:

name = "Alex"

age = 15

print("My name is", name, "and I am", age, "years old.")

 

Output:

My name is Alex and I am 15 years old.

 

Formatted string literals (Using f-strings)

This is the most widely used method in string formatting in the current time. In formatted string literal we use ‘f’ before the string and embedding expressions inside { }.

It is the most popular method of using string format. It was introduced in Python 3.6.

 

Example 1:

name = "Alice"

age = 25

message = f"My name is {name} and I am {age} years old."

print(message)

 

Output

My name is Alice and I am 25 years old.

 

Example 2:

name = "Alex"

age = 15

print(f"My name is {name} and I am {age} years old.")

 

7.9 Data types and variables

 

Data type

A data type is the classification of data that specifies the type of value a variable can hold and determines the operations that can be performed on that data. Python automatically assigns the data type when a value is stored in a variable. In Python, common data types include int (integers), float (decimal numbers), str (text), and bool (True/False values).

 

 

Python supports several data types:

1.      int (integer): Whole numbers without decimals. Example: 10, -25.

2.      float (floating point): Numbers with decimals. Example: 3.14, -0.5.

3.      str (string): A sequence of characters written inside single or double quotes. Example: "Hello", 'Python'.

4.      bool (boolean): Logical values True or False, often used in decision-making.

 

Identifier

An identifier is the name given to variables, functions, classes, or other objects in Python so that they can be identified and used in a program.

 

Rules for Identifiers

  1. Must begin with a letter (A–Z, a–z) or an underscore _.
  2. Cannot start with a number.
  3. Can contain letters, digits, and underscores (e.g., student_1).
  4. Cannot use keywords like if, else, class as identifiers.
  5. Python identifiers are case-sensitive (name, Name, and NAME are different).

 

Valid identifiers

A1, B34, First_Name, x_1 etc.

 

Invalid identifiers

1A, 34BA,198, int, print first-name. def etc.

 

Variables in Python

A variable in Python is a name given to a memory location used to store data.
The value of a variable can change during the execution of a program.

 

Key Points about Variables

  • A variable is created when we assign a value using =.
  • Python does not need you to declare the type of variable (it decides automatically based on the value).
  • Variables make it easy to reuse and process data in programs.

 

Rules for Naming Variables

  1. Must begin with a letter or underscore _.
  2. Cannot start with a number.
  3. Can contain letters, digits, and underscores.
  4. Cannot use Python keywords like if, class, while.
  5. Case-sensitive (age, Age, and AGE are different).

Examples:

age = 15          # integer variable

name = "Alex"     # string variable

pi = 3.14         # float variable

is_active = True  # boolean variable

print(name, age)

Term

Meaning

Example

Variable

A name used to store data (value can change)

x = 10

Identifier

The name given to a variable, function, or object

x, student_name

Keyword

Predefined reserved word with special meaning

if, while, class

7.10 Concept of Type Casting

 

Type Casting (Type Conversion)

Type casting in Python is the process of converting one data type into another. It can be implicit, where Python converts automatically (e.g., int to float), or explicit, where the programmer converts manually using functions like int(), float(), or str(). For example, x = int("100") converts the string "100" into an integer.

 

Types of casting

·        Implicit casting

·        Explicit casting

 

Implicit casting

Implicit type casting is the automatic conversion of data type by Python, such as converting an integer into a float during calculations.

 

Examples:

x = 10 # integer

y = 5.5 # float

z = x + y # the integer ‘x’ is cast to a float for the addition.

print(z)

 

Explicit casting

Explicit type casting is the manual conversion of one data type into another by the programmer using functions such as int(), float(), and str().

 

Common Casting Functions in Python

·        int(): Converts a value to an integer.

·        float(): Converts a value to a float.

·        str(): Converts a value to a string.

·        bool(): Converts a value to a boolean (True or False).

 

Example:

int(x): Converts x to an integer.

x = 3.14

y = int(x)  # Converts float to int (removes decimal part)

print(y)     # Output: 3

 

x = 25

y = str(x)    # Converts integer to string

print(y)      # Output: "25"

 

7.11 Operators and Expressions: Arithmetic, Relational, Logical, Assignment

 

Operators

An operator in Python is a symbol that is used to perform specific operations on values or variables, such as arithmetic calculation, comparison, logical decision-making, or assignment of values.

 

 

Arithmetic Operators

Arithmetic operators are symbols in Python that are used to perform basic mathematical operations such as addition, subtraction, multiplication, division, remainder, and power.

 

List of Arithmetic Operators

Operator

Meaning

Example

Result

+

Addition

10 + 5

15

-

Subtraction

10 - 5

5

*

Multiplication

10 * 5

50

/

Division (float)

10 / 3

3.33

//

Floor Division (whole)

10 // 3

3

%

Modulus (remainder)

10 % 3

1

**

Exponent (power)

2 ** 3

8

 

Example:

Simple program to find the sum of the two number for the user input

num1 = float(input(“Enter first number: “))

num2 = float(input(“Enter second number: “))

sum = num1 + num2

print(“The sum of {0} and {1} is {2}”.format(num1, num2, sum))

 

Relational operator

A relational operator in Python is a symbol used to compare values or expressions.
It shows the relationship between them and always returns a Boolean result — either True or False.

 

List of Relational Operators

Operator

Meaning

Example

Result

==

Equal to

5 == 5

True

!=

Not equal to

5 != 3

True

> 

Greater than

10 > 3

True

< 

Less than

3 < 10

True

>=

Greater than or equal to

10 >= 10

True

<=

Less than or equal to

3 <= 5

True

 

Logical operator

A logical operator in Python is used in decision making to combine one or more conditions. It returns a Boolean value (True or False) based on the logic applied. The main logical operators are and, or, and not. There are 3 main logical operators, ‘and’, ‘or’, and ‘not’.

 

AND Operator

Both the conditions must be true for the result to be true in the “and” operator.

Example: x = (5<2) and (5>3)

Result: False

 

 

 

 

Truth Table for ‘and’ Operator

Condition A

Condition B

A and B

True

True

True

True

False

False

False

True

False

False

False

False

 

OR Operator

Only one of the conditions needs to be true for the result to be true in the “or” operator.

Example: (5<2) or (5>3)

Result: True’

 

Truth Table for ‘or’ Operator

Condition A

Condition B

A or B

True

True

True

True

False

True

False

True

True

False

False

False

 

NOT  Operator

The logical operator “not” provides the opposite result of a given condition.

Example: not(5<2)

Result: True

 

Truth Table for not Operator

Condition A

not A

True

False

False

True

 

Assignment operator

An assignment operator in Python is used to assign values to variables. Some assignment operators also perform an operation (like add, subtract, multiply) and then assign the result back to the variable.

 

List of Assignment Operators

Operator

Meaning

Example

Result

=

Assign value

x = 10

x = 10

+=

Add and assign

x = 5; x += 3

x = 8

-=

Subtract and assign

x = 5; x -= 2

x = 3

*=

Multiply and assign

x = 4; x *= 2

x = 8

/=

Divide and assign

x = 10; x /= 2

x = 5.0

%=

Modulus and assign

x = 10; x %= 3

x = 1

**=

Exponent (power) and assign

x = 2; x **= 3

x = 8

//=

Floor divide and assign

x = 10; x //= 3

x = 3

 

 

 

Expression

An expression in Python is a combination of values, variables, operators, and functions that is evaluated to produce a result.

Example:

x = 10

y = 5

z = x + y     # arithmetic expression

print(z)      # 15

 

 x + y → is an expression.

The result is 15.

 

Other examples:

  • 10 > 5 → relational expression → result: True
  • (5 > 3) and (2 < 7) → logical expression → result: True

 

Algebraic Expression (Maths)

Python Expression (Code)

Meaning / Example

( x + y )

x + y

Addition of two numbers

( x - y )

x - y

Subtraction of two numbers

( x \times y )

x * y

Multiplication

( \dfrac{x}{y} )

x / y

Division (float result)

( \lfloor \dfrac{x}{y} \rfloor )

x // y

Floor division (quotient only)

( x \bmod y )

x % y

Modulus (remainder)

( x^y )

x ** y

Exponent (power)

 

Exam Tip:

  • In algebra, we use symbols like × and ^.
  • In Python, we use * for multiplication and ** for exponent.

 

Operands

An operand is a value, constant, or variable on which an operator performs an action. For example, in x + y, the operands are x and y, while + is the operator.

Example: add = 5 + 3

Here, ‘5’ and ‘3’ are operands and ‘+’ is an operator, and it is performing an ‘addition’ operation.

 

7.12 Conditional statement (if, elif, else)

A conditional statement in Python is a control structure used in decision making. It allows the program to test a condition and execute a block of code if the condition is True, and optionally execute another block if the condition is False. he main conditional statements are if, if–else, and if–elif–else.

For example:

if age >= 18:

    print("Eligible to vote")

else:

    print("Not eligible")

 

 

 

 

Types of Conditional Statements in Python

 

if statement - Executes a block only if the condition is True.

 

Syntax:

if condition:

    # Code to execute if condition is true

 

Example:

age = 18

if age >= 18:

    print("You are eligible to vote")

 

if–else statement - If the condition is true, one block of code is executed; otherwise, another block is executed.

 

Syntax:

if condition:

    # Code to execute if condition is true

else:

    # Code to execute if condition is false

 

Example:

age = 16

if age >= 18:

    print("You can vote")

else:

    print("You cannot vote")

 

if–elif–else statement: Checks multiple conditions. If one condition is true, the corresponding block of code will execute. If none are true, the else block will execute.

 

Syntax:

if condition1:

    # Code to execute if condition1 is true

elif condition2:

    # Code to execute if condition2 is true

else:

    # Code to execute if none of the conditions are true

 

Example:

Checking the number’s category, whether it is positive, negative or zero.

user_number = int(input(“Enter a number: “))

if user_number > 0:

    print(“The number is positive.”)

elif user_number == 0:

    print(“The number is zero.”)

else:

    print(“The number is negative.”)

 

Nested if Statements: A nested if statement means placing one if inside another. It is used when a decision depends on multiple conditions, step by step.

 

Syntax:

if condition1:

    #code to be executed if condition1 is True

        if condition2:

            #code to be executed if condition 2 is True

        else:

           #code to be executed when condition2 is False

else:

    #code to be executed when condition1 and condition2 are False

 

Example:

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

if age >= 16:

    print(“You are eligible for citizenship.”)

    if age >= 18:

       print(“You are eligible to cast a vote.”)

    else:

       print(“You are not eligible to cast vote.”)

else:

    print(“You are a minor.”)

 

7.13 Iteration (for and while)

Iteration in Python means the repeated execution of a block of code as long as a condition is True or for a fixed number of times. It is also called a loop.

The two main types are for loop (used when the number of iterations is known) and while loop (used when iterations depend on a condition). For example, for i in range(5): print(i) prints numbers from 0 to 4.

 

Types of iterations

·        for loop

·        while loop

 

For Loop

A for loop in Python is a control structure used for iteration. It executes a block of code repeatedly for each item in a sequence (such as a list, string, or range). It is mostly used when the number of repetitions is known.

 

Syntax:

for variable in sequence:

    # Code to execute

 

Example:

# Iterating over a range of numbers from 0 to 4

for i in range(5):

    print(i)

 

 

 

Example:

#Using for loop to print “jump” five times

for x in range(5):

     print(“Jump!”)

 

Example:

# Iterating over a list

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:

    print(fruit)

 

While Loop

A while loop in Python is a control structure that repeats a block of code as long as a given condition is True. It is mainly used when the number of iterations is not known in advance.

Syntax:

while condition:

    # Code to execute

 

Example:

# Using while loop to print numbers from 0 to 4

i = 0

while i < 5:

    print(i)

    i += 1  # Incrementing the value of i to avoid infinite loop

 

Example 2 (infinite loop warning!):

while True:

    print("This will run forever!")

Example 3:

x = 1 

while x <= 5: 

    print(x) 

    x += 1 

# prints numbers from 1 to 5.

 

Difference between for loop and while loop

Aspect

for loop

while loop

Definition

Repeats a block of code for each item in a sequence or for a fixed number of times.

Repeats a block of code as long as a condition is True.

Use Case

Used when the number of iterations is known.

Used when the number of iterations is not known in advance.

Syntax

for i in range(n):

while condition:

Control

Controlled by a sequence (like range, list, string).

Controlled by a condition (True/False).

Risk of Infinite Loop

Normally does not create infinite loops.

May create infinite loops if the condition never becomes False.

Example

for i in range(5): print(i)

x=1; while x<=5: print(x); x+=1

pass Statement

The pass statement in Python is a dummy statement that performs no action. It is used as a placeholder when a statement is required but no code needs to be executed. For example, if x > 5: pass allows the program to run without producing an error even though the block is empty.

The pass statement in Python is a null statement.

 

Syntax:

if condition:

    # Some code here

else:

    pass # Nothing happens in the “else” case

 

Example:

for i in range(5):

    if i == 2:

        pass  # Do nothing if i is 2

    else:

        print(i)

 

Output:

0

1

3

4

 

In this example, when i is equal to 2, the pass statement is executed, which does nothing, so the loop continues without printing 2.

 

continue Statement

The continue statement in Python is used in loops to skip the current iteration and immediately continue with the next one. For example, in a loop from 1 to 5, if continue is used when i == 3, the number 3 will be skipped from the output.

 

Example:

 

for i in range(5):

    if i == 2:

        continue  # Skip the rest of the code when i is 2

    print(i)

 

Output:

 

0

1

3

4

 

Here, when i == 2, the continue statement skips the print(i) and moves to the next iteration of the loop, so 2 is not printed.

 

break Statement

The break statement in Python is used to terminate a loop immediately, regardless of the loop condition. It is often used when a particular condition is met and no further iterations are needed. For example, in a loop from 1 to 5, if break is used when i == 3, the loop will stop after printing 1 and 2.

 

Example:

 

for i in range(5):

    if i == 3:

        break  # Exit the loop when i is 3

    print(i)

 

Output:

 

0

1

2

 

In this case, when i == 3, the break statement causes the loop to terminate, and no further numbers are printed.

 

Comparison Table: break, continue, and pass

Statement

Definition

Effect in Loop

Example Use

break

Terminates the loop immediately, even if the condition is still True.

Exits the loop completely and control goes to the first statement after the loop.

Stop a loop when a certain value is found.

continue

Skips the current iteration and moves to the next iteration of the loop.

Loop continues, but the remaining code in the current iteration is ignored.

Skip printing a number when condition matches.

pass

A null statement; does nothing. Used as a placeholder when a statement is required but no action is needed.

No effect on loop execution. Just a dummy statement.

Keep a loop or if block empty without error.

 

7.14 Lists and Dictionary

 

Python list

A list in Python is an ordered, mutable collection of elements, written inside square brackets [ ] and separated by commas. Lists can store values of the same or different data types in a single variable.

Features of Lists

  • Ordered → elements keep their position (index starts from 0).
  • Mutable → elements can be changed after creation.
  • Can hold mixed data types (numbers, strings, booleans).
  • Allows duplicate values.

 

1. Creating a List

  • Using square brackets:

numbers = [1, 2, 3, 4, 5]

fruits = ["apple", "banana", "cherry"]

mixed = [1, "apple", 3.14, True]

empty = []

  • Using the list() constructor:

thislist = list(("apple", "banana", "cherry"))

 

2. Accessing Elements

  • Lists use indexing (starts at 0).

print(fruits[0])     # apple

print(fruits[-1])    # cherry (last element)

 

3. Modifying a List

  • Lists are mutable → items can be changed, added, or removed.

numbers[0] = 10

fruits.append("orange")       # add at end

fruits.insert(1, "grape")     # insert at position

fruits.remove("banana")       # remove by value

removed = fruits.pop(2)       # remove by index

 

4. List Length

print(len(fruits))   # number of elements

 

5. Looping Through a List

for fruit in fruits:

    print(fruit)

 

6. List Slicing

fruits = ["apple", "grape", "cherry", "orange"]

print(fruits[1:3])   # ['grape', 'cherry']

print(fruits[:2])    # ['apple', 'grape']

print(fruits[2:])    # ['cherry', 'orange']

 

7. Concatenation & Repetition

list1 = [1, 2, 3]

list2 = [4, 5, 6]

print(list1 + list2)   # [1,2,3,4,5,6]

print(list1 * 2)       # [1,2,3,1,2,3]

 

8. List Comprehension

squares = [x**2 for x in range(5)]

print(squares)    # [0, 1, 4, 9, 16]

 

evens = [x for x in range(10) if x % 2 == 0]

print(evens)      # [0, 2, 4, 6, 8]

 

9. Nested Lists

nested = [1, [2, 3], 4, [5, 6]]

print(nested[1])      # [2, 3]

print(nested[1][0])   # 2

 

 

 

10. Common List Methods

Method

Use

append(x)

Add item at end

insert(i,x)

Insert at index

remove(x)

Remove item by value

pop(i)

Remove item by index

sort()

Sort list ascending

reverse()

Reverse list order

clear()

Remove all items

 

Python Dictionary

A dictionary in Python is an unordered, mutable collection of key–value pairs, written inside curly braces { }. Each element has a key and its associated value, and values are accessed using the keys.

 

1. Creating a Dictionary

# Syntax

my_dict = {key1: value1, key2: value2, key3: value3}

 

# Example

fruit_colors = {"apple": "red", "banana": "yellow", "cherry": "red"}


2. Accessing Values

print(fruit_colors["apple"])          # red

print(fruit_colors.get("orange", "Not found"))  # Not found


3. Adding or Modifying Items

fruit_colors["orange"] = "orange"   # Add new

fruit_colors["banana"] = "green"    # Modify existing


4. Removing Items

del fruit_colors["cherry"]     # delete by key

removed = fruit_colors.pop("apple") # removes and returns value

print(removed)  # red


5. Dictionary Properties

  • Unordered → items have no fixed order.
  • Mutable → items can be added, changed, or deleted.
  • Keys must be unique.
  • Values can be of any data type.

6. Dictionary Methods

Method

Description

keys()

Returns all keys

values()

Returns all values

items()

Returns all key–value pairs

update()

Merges another dictionary

clear()

Removes all items

pop(key)

Removes and returns value by key

popitem()

Removes last inserted item


7. Dictionary Length

print(len(fruit_colors))   # Number of key–value pairs


8. Looping through a Dictionary

for key, value in fruit_colors.items():

    print(key, ":", value)


9. Dictionary Comprehension

squares = {x: x**2 for x in range(5)}

print(squares)  # {0:0, 1:1, 2:4, 3:9, 4:16}


10. Nested Dictionaries

students = {

  "John": {"age": 25, "grade": "A"},

  "Anna": {"age": 22, "grade": "B"}

}

print(students["Anna"]["grade"])   # B


11. Merging Dictionaries

dict1 = {"apple": "red", "banana": "yellow"}

dict2 = {"cherry": "red", "orange": "orange"}

dict1.update(dict2)   # merge into dict1


Difference between List and Dictionary in Python

Aspect

List

Dictionary

Definition

Ordered collection of elements stored inside square brackets [ ].

Unordered collection of key–value pairs stored inside curly braces { }.

Access Method

Elements are accessed using index numbers (starting from 0).

Elements are accessed using keys.

Structure

Single collection of values.

Collection of key–value pairs.

Mutability

Mutable (elements can be changed).

Mutable (items can be added, changed, or removed).

Duplicates

Allows duplicate elements.

Keys must be unique (values may repeat).

Example

fruits = ["apple", "banana", "cherry"]

fruit_colors = {"apple":"red", "banana":"yellow"}

 


 

Features of List in Python

  1. A list is an ordered collection of items.
  2. Created using square brackets [ ].
  3. Supports indexing and slicing (index starts at 0).
  4. Lists are mutable → elements can be changed after creation.
  5. Can store different data types in one list (e.g., numbers, strings).
  6. Allows duplicate elements.
  7. Supports useful methods like append(), insert(), remove(), sort(), etc.

Features of Dictionary in Python

  1. A dictionary is an unordered collection of key–value pairs.
  2. Created using curly braces { }.
  3. Elements are accessed using keys, not indexes.
  4. Keys must be unique, but values can be repeated.
  5. Dictionaries are mutable → key–value pairs can be added, modified, or removed.
  6. Can hold values of different data types.
  7. Supports useful methods like keys(), values(), items(), update(), pop(), etc.

 

7.15 Uses of Library functions : String Functions (center, upper, lower, Len), Numeric and mathematical (sum, pow, round, abs, sqrt, Int)

 

Function

A function in Python is a block of reusable code that performs a specific task. Functions help to reduce repetition, make programs modular, and improve readability.

Types of Functions

1. Built-in Functions

Built-in functions are the functions that come predefined in Python. They are always available for use without writing extra code.

Examples:

  • len() → returns length of a list or string
  • sum() → adds all numbers in a list
  • print() → displays output

numbers = [1, 2, 3]

print(len(numbers))   # 3

print(sum(numbers))   # 6

2. User-defined Functions

User-defined functions are functions that are created by the programmer using the def keyword. They allow code reuse and modular programming.

Example:

def square(x):

    return x * x

print(square(4))   # 16

Difference between Built-in and User-defined Functions

Aspect

Built-in Functions

User-defined Functions

Definition

Predefined functions that come with Python.

Functions created by the programmer using the def keyword.

Availability

Always available to use directly.

Available only after being defined in the program.

Ease of Use

Saves time since no coding is required.

Gives flexibility to design your own logic.

Examples

print(), len(), sum(), abs().

def add(a, b): return a+b, def square(x): return x*x.

Library function

Library functions are predefined functions stored in Python’s standard libraries (modules). They are used by importing the library and help programmers perform common tasks without writing code from scratch..

 

String Function

·        A string function is a built-in function that is used to manipulate or process string data.

·        These functions perform various operations like changing the case of letters, finding the length of a string, concatenating strings, and more.

 

center(width, fillchar): Centers the string within the given width, padding it with a specified character (default is a space).

Example:

text = "Hello"

print(text.center(10, "*"))  # Output: '**Hello***'

 

upper( ): Converts all characters in the string to uppercase.

Example:

text = "hello"

print(text.upper( ))  # Output: 'HELLO'

 

lower( ): Converts all characters in the string to lowercase.

Example:

text = "hello"

print(text.lower( ))  # Output: 'hello'

 

len(): Returns the length of the string (i.e., the number of characters).

Example:

text = "Hello"

print(len(text))  # Output: 5

 

Numeric Functions

These functions are part of Python's built-in capabilities or from the math module to manipulate numeric values.

 

sum(iterable): Returns the sum of all elements in an iterable (e.g., a list).

Example:

numbers = [1, 2, 3, 4, 5]

print(sum(numbers))  # Output: 15

 

abs(x): Returns the absolute value of a number.

Example:

print(abs(-5))  # Output: 5

print(abs(3.5))  # Output: 3.5

 

round(x, n): Rounds a number x to n decimal places (default is 0).

Example:

print(round(3.14159, 2))  # Output: 3.14

print(round(3.5))  # Output: 4

 

 

pow(x, y): Returns x raised to the power of y (i.e., x^y).

Example:

print(pow(2, 3))  # Output: 8 (2^3)

 

int(x): Converts a number or string to an integer.

Example:

print(int(3.7))  # Output: 3

print(int("42"))  # Output: 42

 

min( ) and max( )Function: Returns the smallest (minimum) or largest(maximum) value from the given iterable or from multiple values passed as arguments.

Example:

numbers = [3, 1, 4, 1, 5, 9, 2, 6]

print(min(numbers))  # Output: 1

 

Mathematical Functions (from math module)

These functions are provided by the math module and perform more advanced mathematical operations.

 

math.sqrt(x): Returns the square root of x.

Example:

import math

print(math.sqrt(16))  # Output: 4.0

 

math.factorial(x) : Returns the factorial of a number x (i.e., x! = x * (x - 1) * (x - 2) * ... * 1).

Example:

import math

print(math.factorial(5))  # Output: 120 (5! = 5 * 4 * 3 * 2 * 1)

 

math.pi : Provides the mathematical constant π (approximately 3.14159).

Example:

import math

print(math.pi)  # Output: 3.141592653589793

 

math.sin(x) and math.cos(x): Return the sine and cosine of x (where x is in radians).

Example:

import math

print(math.sin(math.radians(30)))  # Output: 0.5

print(math.cos(math.radians(60)))  # Output: 0.5

 

math.log(x, base): Returns the logarithm of x to the given base. If the base is not specified, it returns the natural logarithm (base e).

Example:

import math

print(math.log(10))  # Output: 2.302585092994046 (natural log of 10)

print(math.log(100, 10))  # Output: 2.0 (logarithm base 10 of 100)

 


7. Programming Concept (Python)

  7. Programming Concept (Python)

 


7.1 Introduction to Programming Language

Introduction to Programming Concepts: Python and Beyond

Welcome to the world of programming! Whether you're aspiring to become a software developer, a data scientist, or simply curious about how computers work, understanding programming is essential. In this post, we’ll cover the basics of programming, focusing on Python, one of the most popular and beginner-friendly programming languages.


1. What is a Programming Language?

programming language is a set of instructions used to communicate with a computer and tell it what to do. Just like how humans speak different languages to communicate with each other, we use programming languages to communicate with computers. These languages allow us to create software, apps, games, websites, and much more!

Some examples of popular programming languages include:

  • Python

  • Java

  • C++

  • PHP


2. What is Programming?

Programming is the process of writing specific instructions for a computer to follow in order to complete a task. These instructions are written in a programming language, and once the computer understands them, it executes them to carry out operations such as calculations, data processing, or user interactions.


3. Who is a Programmer?

programmer is a person who writes code (computer programs). They are the ones who develop the software and tools we use every day. Programmers can specialize in creating websites, apps, games, or even control systems for machinery.


4. Syntax in Programming

Every programming language has rules for how instructions should be written. These rules are called syntax. Just like in grammar, incorrect syntax in programming will cause errors, and the computer won’t be able to understand your instructions.


5. Types of Programming Languages

Programming languages are divided into two main types:

High-Level Programming Languages

  • High-level languages are easier for humans to understand and use. These languages are written using English-like words and symbols.

  • They need to be translated into machine language (which computers understand) by a compiler or interpreter.

  • Examples: PythonJavaC++PHP

Low-Level Programming Languages

  • Low-level languages are closer to the machine’s binary code (0s and 1s), which is directly understood by computers.

  • These languages are harder for humans to read, but they can give more control over hardware and performance.

  • Examples: Machine Language (binary code), Assembly Language

High-level languages are great for beginners because:

  • They are easier to understand and write.

  • They use English-like syntax, making it more approachable.

  • They require less time to learn and focus more on solving problems than writing complex code.


6. Programming Tools: Flowchart and Algorithm

Before jumping into writing code, it's helpful to plan out how your program will work. This is where algorithms and flowcharts come in.

Algorithm

An algorithm is a step-by-step set of instructions designed to solve a specific problem. It’s like a recipe in cooking—each step must be followed to achieve the desired result.

Example:

  1. Start

  2. Take two numbers as input

  3. Add the two numbers

  4. Display the result

  5. Stop

Flowchart

flowchart is a visual representation of an algorithm. It uses shapes like rectangles, diamonds, and arrows to represent different actions and decisions in the process.

Key Shapes in a Flowchart:

  • Oval: Start or End

  • Rectangle: Process or Task

  • Diamond: Decision or Condition

  • Arrow: Flow direction

Flowcharts help make complex processes easier to understand and visualize before writing the code.


7. Coding, Testing, and Debugging

Coding

Coding is the process of writing instructions for a computer in a programming language. The written instructions are called code, and they tell the computer exactly what to do.

Testing

After writing the code, it’s important to test the program to make sure it works as expected. Testing involves running the program and checking for any errors (called bugs). It’s essential to identify and fix these bugs before using the program in real-world scenarios.

Debugging

Debugging is the process of finding and fixing errors in the code. Bugs can occur due to simple mistakes, like missing a comma or using the wrong variable. Debugging ensures that the program runs smoothly and reliably.


8. Compiler vs. Interpreter

When you write code in a high-level language, the computer needs to translate it into machine language (binary code). This translation is done using a compiler or an interpreter.

Compiler

compiler translates the entire code into machine language all at once. It is fast but requires the entire program to be written before it can be translated.

  • Examples: JavaCC++

Interpreter

An interpreter translates the code line-by-line as it runs, making it easier to debug but slower compared to a compiler.

  • Examples: PythonRubyJavaScript


9. Python: A Beginner-Friendly Programming Language

Python is one of the most popular high-level programming languages. It’s widely used for web development, data analysis, artificial intelligence (AI), automation, and much more. Python is known for its simplicity and readability, making it perfect for beginners.

Key Features of Python:

  • Easy Syntax: Python uses simple, English-like syntax that is easy to read and understand.

  • Versatile: Python can be used for web development, software development, data science, and automation.

  • Community Support: There is a large and active Python community, offering plenty of resources and libraries to help you.


10. Conclusion: Get Started with Python!

Now that you understand the basics of programming and Python, you’re ready to start creating your own programs! Remember, the key to becoming a good programmer is practice. Start by writing simple programs, like a calculator or a to-do list, and slowly move on to more complex projects as you improve.

Next Steps:

  • Install Python on your computer and start writing your first Python program.

  • Explore Python’s simple syntax, like printing text and doing math.

  • Try solving basic problems using algorithms and flowcharts before jumping into coding.

  • Keep testing and debugging your code until it works perfectly.

With Python’s beginner-friendly design and easy syntax, you’re well on your way to becoming a skilled programmer. Happy coding!