0% found this document useful (0 votes)
16 views32 pages

Brief Overview of Python

The document provides an overview of programming languages, focusing on Python as a high-level, interpreted language known for its simplicity and versatility. It covers key features, applications, and basic concepts such as tokens, identifiers, variables, data types, and sequence types like lists and tuples. Additionally, it explains how to write and execute Python programs, including the use of a Python interpreter and the rules for naming identifiers.

Uploaded by

vishwa dev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views32 pages

Brief Overview of Python

The document provides an overview of programming languages, focusing on Python as a high-level, interpreted language known for its simplicity and versatility. It covers key features, applications, and basic concepts such as tokens, identifiers, variables, data types, and sequence types like lists and tuples. Additionally, it explains how to write and execute Python programs, including the use of a Python interpreter and the rules for naming identifiers.

Uploaded by

vishwa dev
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

A program is a set of instructions that tells a computer what to do in order to

complete a specific task.


The language used to write these instructions is called a programming language.
💬 What is a Programming Language?
A programming language is a formal language consisting of a set of instructions
and rules used to communicate with a computer and write programs that
perform specific tasks.
It allows programmers to write code that can be translated into machine
language (binary code) which the computer can understand and execute.
Some popular programming languages include:
Python C C++ Java JavaScript
What is Python?
Python is a high-level, interpreted, and general-purpose programming language.
It is known for its simplicity, readability, and flexibility, which makes it ideal for
both beginners and professionals.
Python was created by Guido van Rossum in 1991 and is maintained by the
Python Software Foundation (PSF).
⚙️ Key Features of Python
Easy to Learn and Read:
Python uses simple, English-like syntax, making it easy to learn even for
beginners.
High-Level Language:
Programmers don’t need to manage memory or understand complex system
architecture — Python takes care of it automatically.
Interpreted Language:
Python executes code line by line using an interpreter. This makes debugging
easier.
Portable:
Python programs can run on different operating systems (Windows, macOS,
Linux) without modification.
Extensive Libraries:
Python has thousands of built-in and external libraries for various applications
(e.g., NumPy, Pandas, TensorFlow, Flask).
🧩 Uses and Applications of Python
Python is one of the most widely used programming languages today because of its
versatility. It is used in many fields such as:

Field Application

Software Development Creating desktop and mobile applications

Building dynamic websites using frameworks like


Web Development
Django and Flask

Analyzing and visualizing data using Pandas, NumPy,


Data Science & Analytics
and Matplotlib

Developing intelligent systems with TensorFlow,


Machine Learning & AI
Keras, and Scikit-learn

Automating repetitive tasks (e.g., file handling, data


Automation / Scripting
entry)

Game Development Creating simple games using Pygame

Writing scripts for network scanning, data


Cybersecurity
encryption, and security testing

Internet of Things (IoT) Controlling hardware devices and sensors

🐍 Why the Name “Python”?


Guido van Rossum created the Python programming language in 1991.

He wanted to design a language that was:


1). Easy to learn
2). Simple to use
3). Powerful and practical for solving real-world problems

At that time, most existing programming languages were too complex and
difficult for beginners. Guido aimed to create a language that was clear, readable,
and enjoyable to use.

Interestingly, the name “Python” did not come from the snake.

Guido was a big fan of a British comedy television show called “Monty Python’s
Flying Circus.” He chose the name “Python” because he wanted the language to
be fun, creative, and less serious — just like the show.
Working with Python
To write and execute a Python program, we need a Python Interpreter.
The interpreter is the software that reads and executes the Python code line by
line.
⚙️ Ways to Use Python
There are two main ways to use Python:
1). Install Python on your computer
You can download it from the official website: https://www.python.org.
After installation, you can write and run Python programs on your system.
2). Use an Online Python Interpreter
If you don’t want to install Python, you can use online interpreters such as:
1.Replit (https://replit.com)
2.Programiz (https://www.programiz.com/python/online-compiler/)
3.Google Colab or Jupyter Notebook (for advanced users).

💻 Python Interpreter (Python Shell)


The Python interpreter is also known as the Python Shell.
When you open it, you will see a symbol like this: >>>
This symbol is called the Python Prompt.
It indicates that the interpreter is ready to accept commands.
You can type Python statements or expressions directly after the prompt, and the
interpreter will execute them immediately.

🧩 Modes of Running Python Programs


Python programs can be run in two modes:
1). Interactive Mode:
In this mode, you type commands directly at the Python prompt (>>>).
The interpreter executes each line immediately and shows the result.
This mode is useful for testing small pieces of code or learning Python quickly.
Example:
>>> print("Hello, Python!")
Hello, Python!

1). Interactive Mode:


In this mode, you write your Python code in a text file and save it with a “.py”
extension. Then you run the entire file at once.
This mode is used for larger programs or projects.

Example:
# Filename: hello.py
print("Welcome to Python Programming!")
Tokens in Python
Tokens are the smallest units or building blocks of a Python program.
In simple terms, tokens are like the words, symbols, and punctuation marks in a
programming language — just as sentences in English are made up of words, a
Python program is made up of tokens.

🧩 Types of Tokens in Python


Python has five main types of tokens:

Type of Token Description Example

Reserved words in Python that


have special meaning and if, else, for, while, class,
1. Keywords
purpose. They cannot be used as def, import, etc.
variable names.

Names given to variables,


2. Identifiers a, sum, student_name
functions, classes, or objects.

Fixed values or data used in a


3. Literals 5, 3.14, "Hello", True
program.

Symbols used to perform


4. Operators operations on variables and +, -, *, /, =, ==
values.

Symbols that structure the


5. Punctuators /
program, separating statements (), {}, [], :, ,, .
Delimiters
or defining blocks.

Example
# Simple program to add two numbers
a=5
b=3
sum = a + b
print("The sum is:", sum)

# Simple program to add two numbers ==> comment


a, b, sum, print ==> Identifiers
=,+ ==> operators
(, ), : ==> Punctuators
5, 3, "The sum is:", sum ==> Literals
Identifiers
An identifier is the name given to variables, functions, classes, or objects in a
Python program.
It helps programmers uniquely identify different elements of a program.
📘 Rules for Naming Identifiers
✅ Can include letters, digits, and underscores (_) only
Identifiers may contain A–Z, a–z, 0–9, and the underscore ( _ ) symbol.
No other special symbols (like @, $, or -) are allowed.
Examples:
✔️ Valid: my_var, student1, total_score
❌ Invalid: my-var, total$, score%
🚫 Cannot start with a number
Identifiers must begin with a letter or an underscore, not a digit.
Examples:
✔️ Valid: age1, student2, _count
❌ Invalid: 1age, 2student, 3value

⚠️ Cannot use Python keywords


Reserved words like if, else, for, while, class, def, etc., cannot be used as
identifiers.
Keywords have special meaning in Python, so using them as names will
cause an error.
Example:
❌ Invalid: if = 5, class = "A"
✔️ Valid: if_value = 5, class_name = "A"
🔤 Case-Sensitive
Python is case-sensitive, which means that names with different letter
cases are treated as different identifiers.
Examples:
Age, age, and AGE are three different identifiers.

⛔ No Spaces Allowed
Identifiers cannot contain spaces between words.
Use an underscore (_) to separate words instead.
Examples:
✔️Valid: first_name, total_marks
❌ Invalid: first name, total marks

Choose meaningful names to make code easier to understand.


Example: use student_name instead of sn.
Python allows very long identifiers, but it’s good practice to keep them short and
clear.
Variables
A variable is an identifier (name) used to store a value in a Python program.
The value of a variable can change during program execution.
⚡ Key Points
A variable must be a valid identifier (follow naming rules).
The data stored in a variable can be of different types, such as integer, float,
string, etc.
Example:
age = 20 # Integer
gender = 'M' # String (single character)
message = "Keep Smiling" # String (text)
price = 987.9 # Float

You can change the value of a variable anytime in the program.

age = 20
print(age) # Output: 20

age = 25
print(age) # Output: 25

Basic Questions:
1.Write a Python program to find the sum of two numbers.
2.Write a Python program to find the area of a rectangle given that its length is 10
units and breadth is 20 units.
3.Write a Python program to swap two numbers.
4.Write a Python program to find the square of a number.
5.Write a Python program to calculate the simple interest given principal = 1000,
rate = 5, and time = 2 years.
6.Write a Python program to find the average of three numbers.
7.Write a Python program to convert temperature from Celsius to Fahrenheit. (Use
formula: F = (C × 9/5) + 32)
8.Write a Python program to find the perimeter of a square when side = 15 units.
9.Write a Python program to print the product of two numbers.
Data Types
Every value in Python belongs to a specific data type.
A data type tells Python:
What kind of data a variable can hold (text, number, etc.)
What kind of operations can be performed on that data.

Numbers
The number data type in Python is used to store numerical values only.
Numbers can be used for mathematical calculations, comparisons, and other
operations.
Python classifies numbers into three types:
1.Integers (int)
2.Floating-point numbers (float)
3.Complex numbers (complex)

1️⃣ Integers (int):


An integer is a whole number without any fractional or decimal part.
It can be positive, negative, or zero.
In Python, integers are represented using the int data type.
Example:

quantity = 10 # Positive integer


temperature = -10 # Negative integer
age = 15 # Positive integer
loss = -500 # Negative integer
score = 0 # Zero
population = 1380000000 # Large integer
2️⃣ Float (float)
A float (short for floating-point number) is a number that has a decimal point.
Floats can represent real numbers, including fractions, and can also be written
in scientific notation.
Example:

average_marks = 88.75
temperature_celsius = 36.5
height_in_meters = 1.72
price_of_item = 99.99
area_of_circle = 78.54
interest_rate = 7.25
distance_travelled = 154.6

3️⃣ Complex (complex)


A complex number has two parts:
Real part
Imaginary part (denoted with j in Python, not i as in mathematics)
Complex numbers are represented using the complex data type in Python.
Example:
voltage_signal = 5 + 2j
impedance_value = 12.5 - 3.5j
waveform_output = 0 + 7j
complex_frequency = 50 + 0j
electrical_current = -2 + 4j

Boolean Data Type


The Boolean data type represents only two possible values:
True
False
Boolean values are case-sensitive and must be written with a capital T or F:
✅ Correct: True, False
❌ Incorrect: true, false (this will cause an error)
Boolean values are a subtype of integers in Python:
True is treated as 1
False is treated as 0
Example:
is_raining = True
is_sunny = False
print(is_raining) # Output: True
print(type(is_sunny)) # Output: <class 'bool'>
print(True + 1) # Output: 2 (True = 1)
print(False + 5) # Output: 5 (False = 0)
Sequence Data Types
A sequence is an ordered collection of items in which each item can be accessed by
its index.
Python provides several built-in sequence types. The most commonly used are:
1). String (str) 2). List (list) 3). Tuple (tuple)

1️⃣ String (str)


A string is a sequence of characters.
Strings are immutable, meaning once created, they cannot be changed.
Strings can be enclosed in single quotes ' ' or double quotes " ".
Each character in a string can be accessed using its index, starting from 0.
Example:

name = "Python"
print(name) # Output: Python
print(name[0]) # Output: P (first character)
print(name[3]) # Output: h (fourth character)

Accessing Elements in Python Sequences:


In Python, elements of sequence data types (like strings, lists, and tuples) can be
accessed using indices.
An index is a number that specifies the position of an item inside a sequence.
⚡ Types of Indices
1). Positive Indices:
Count positions from the start of the sequence.
Indexing starts at 0.
Example: 0, 1, 2, …
2). Negative Indices
Count positions from the end of the sequence.
The last element has an index of -1.
Example: -1, -2, -3, …
3). Mixed Indices (Slicing)
Combine positive and negative indices to extract a portion of the sequence.
Syntax: sequence[start:end] (includes start, excludes end)
Example:
name = "Python"
# Access using positive index
print(name[0]) # Output: P (first character)
# Access using negative index
print(name[-1]) # Output: n (last character)
# Access using slicing (mixed indices)
print(name[1:4]) # Output: yth (characters from index 1 to 3)
Lists
A list is an ordered collection of items in Python.
Lists can store multiple items, and these items can be of different data types
(numbers, strings, other lists, etc.).
1.Ordered – The order of items in a list is preserved.
2.Mutable – You can change, add, or remove items after creating the list.
3.Enclosed in Square Brackets [ ] – Items are separated by commas.
4.Can contain different data types – e.g., integers, strings, floats, or even other
lists.
💻 Example:
fruits = ["apple", "banana", "cherry", "date", "mango"]

# Positive Indexing
print(fruits[0]) # Output: apple
print(fruits[2]) # Output: cherry

# Negative Indexing
print(fruits[-1]) # Output: mango
print(fruits[-3]) # Output: cherry

# Slicing (Sublist)
print(fruits[1:4]) # Output: ['banana', 'cherry', 'date']
print(fruits[:3]) # Output: ['apple', 'banana', 'cherry']
print(fruits[2:]) # Output: ['cherry', 'date', 'mango']

Tuples
A tuple is an ordered collection of items in Python.
Tuples can store multiple items of different data types, such as numbers, strings,
lists, or even other tuples.
1.Ordered – The order of items is preserved.
2.Immutable – Once created, the elements of a tuple cannot be changed, added,
or removed.
3.Enclosed in Parentheses ( ) – Items are separated by commas.
4.Can contain different data types – e.g., integers, strings, floats, or even lists.

Example:
# Creating a tuple of fruits
fruits = ("apple", "banana", "cherry", "date", "mango")

# Printing the tuple


print(fruits)
# Output: ('apple', 'banana', 'cherry', 'date', 'mango')
Sets
A set is an unordered collection of unique items in Python.
1.Unordered: Items in a set do not have a specific order.
2.Unique: Duplicate elements are automatically removed.
Example:
# Creating a set using curly braces
fruits = {"apple", "banana", "cherry", "mango", "orange"}

# Printing the set


print(fruits)
# Output (order may vary): {'banana', 'apple', 'mango', 'cherry', 'orange'}

# Creating a set using set() function


numbers = set([1, 2, 3, 2, 4])
print(numbers)
# Output: {1, 2, 3, 4} (duplicates removed)

Dictionaries in Python
A dictionary is an unordered collection of key-value pairs in Python.
Keys must be unique and immutable
==> Examples of valid keys: string, number, tuple
==> Examples of invalid keys: list, set, dictionary
Values can be of any data type
==> Examples: string, number, tuple, list, set, or even another dictionary
Dictionaries are enclosed in curly braces { }.
Key-value pairs are separated by a colon : .

Example:

# Creating a dictionary
student = {
"name": "Alice",
"age": 15,
"city": "New York"
}

# Printing the dictionary


print(student)

# Output: {'name': 'Alice', 'age': 15, 'city': 'New York'}


Operators in Python
An operator is a symbol that performs a specific operation on one or more
values.
The values on which operators act are called operands.

num = 5
result = 10 + num

In this example:
+ is the operator
10 and num are operands

Types of Operators in Python


Python supports several types of operators:
1). Arithmetic Operators:
Used to perform mathematical operations like addition, subtraction, multiplication,
etc.
Example: +, - , *, /, //, %, ** .

a = 10
b=3
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)
print("Floor Division:", a // b)

2). Relational (Comparison) Operators


Used to compare two values and return either True or False.
Example: >, <, >=, <=, ==, != .

x = 10
y = 20
print("The value of x is:", x)
print("The value of y is:", y)
print("------------------------------------")
print("Is x equal to y? :", x == y)
print("Is x not equal to y? :", x != y)
print("Is x greater than y? :", x > y)
print("Is x less than y? :", x < y)
print("Is x greater than or equal to y? :", x >= y)
print("Is x less than or equal to y? :", x <= y)
3). Logical Operators
Used to combine two or more conditional statements.
Example: and , or, not

Operator Description Example Result

Returns True if both conditions are


and True
(5 > 2 and 10 > 5) TRUE

Returns True if at least one condition


or is True
(5 > 10 or 3 < 8) TRUE

Reverses the result (True →


not not(5 > 2) FALSE
False, False → True)

a = 10
b=5
c = 20
print("The value of a is:", a)
print("The value of b is:", b)
print("The value of c is:", c)
print("------------------------------------")
print("Condition 1: (a > b) and (a < c) →", (a > b) and (a < c))
print("Condition 2: (a > b) or (a > c) →", (a > b) or (a > c))
print("Condition 3: not(a == 10) →", not(a == 10))
4). Membership Operators
Membership operators are used to check whether a value is present in a sequence
such as a string, list, tuple, or dictionary.
They return either True or False.

Operator Description Example Result

Returns True if the value is


in 'a' in 'apple' TRUE
present in the sequence

Returns True if the value is 'b' not in


not in TRUE
not present in the sequence 'apple'

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


print("List of fruits:", fruits)
print("------------------------------------")
print("Is 'apple' in the list? :", "apple" in fruits)
print("Is 'grape' in the list? :", "grape" in fruits)
print("Is 'orange' not in the list? :", "orange" not in fruits)
print("Is 'banana' not in the list? :", "banana" not in fruits)
Operator Precedence in Python
When an expression contains more than one operator, Python follows operator
precedence to determine the order of evaluation.
Operators with higher precedence are evaluated before those with lower
precedence.
Parentheses () can be used to change the order of evaluation — expressions
inside parentheses are evaluated first.
If operators have the same precedence, Python evaluates them from left to right
(except for exponentiation **, which is right to left).

Precedence Operator(s) Meaning

1 () Parentheses

2 ** Exponentiation

3 *, /, //, % Multiplication, Division, Floor Division, Modulus

4 +, - Addition, Subtraction

1). 6+2×(5−3) 2). (8+2)×(9−4)/5 3). (18//3)+(23)×2

eval():
The eval() function in Python is a built-in function that evaluates a string as a
Python expression and returns the result of that expression.
Example -1: Example -2:
expression = "6+2×(5−3)" expression = "(8+2)×(9−4)/5"
result = eval(expression) result = eval(expression)
print(result) print(result)

Example -3: Example -4:


expression = "10 + 2 * (6 - 4)" expression = "(18//3)+(23)×2"
result = eval(expression) result = eval(expression)
print(result) print(result)
Input and Output in Python
Python provides built-in functions to take input from the user and to display output
on the screen.
Input
Sometimes, a program needs information from the user — such as a name, age, or a
choice.
In Python, the input() function is used to take input from the user through a device
like a keyboard.
The input() function always returns data as a string, no matter what the user
types (numbers, letters, or symbols).
You can convert the input to other types like int or float if needed.
Example:
name = input("Enter your name: ")
print("Hello,", name)

Example:

age = input("Enter your Age: ")


print("Your age is,", age)

type():
The type() function in Python is a built-in function that is used to determine and
return the data type of an object or value.
It helps identify whether a variable is an integer, float, string, list, tuple,
dictionary, or any other type.

age = input("Enter your Age: ")


print("Your age is,", age)
print("The data type of age is:", type(age))

# Taking input from the user


name = input("Enter your name: ")

# Displaying the entered name


print("Hello,", name)

# Displaying the data type of the variable 'name'


print("The data type of 'name' is:", type(name))
Output
Python uses the print() function to display data or results on the screen.
It can display text, numbers, variables, or even the result of expressions.
Syntax:
print(value1, value2, ..., sep=' ', end='\n')
value1, value2, ... → The data, variables, or expressions you want to display.
sep (optional) → Separator between multiple values. Default is a space ' '.
end (optional) → Specifies what to print at the end. Default is a newline \n.

Example:

#Printing Strings
print("Hello, Python!") # Output: Hello, Python!

#Printing Numbers and Expressions


print(10) # Output: 10
print(5 + 3) # Output: 8
print(10 * 2.5) # Output: 25.0

# Printing Multiple Values


a = 10
b = 20
print("Sum of a and b is", a + b) #Sum of a and b is 30

#Using Custom Separator (sep)


print("Python", "Java", "C++", sep=" | ") #Python | Java | C++

#Changing End Character (end)


print("Hello", end="! ")
print("Welcome to Python") #Hello! Welcome to Python

#Printing Variables and Expressions Together


name = "Karun"
age = 18
print("Name:", name, "| Age:", age) #Name: Karun | Age: 18

#Printing Multi-line Strings


print("""Python is easy.
It is powerful.
It is widely used.""")

OUTPUT: Python is easy.


It is powerful.
It is widely used.
Debugging in Python
When we write a program, it may not always work correctly.
Sometimes
the program may not run properly.
the program may give incorrect results.
Finding and fixing these problems is called debugging.

Types of Errors in Python:


1). Syntax Errors 2). Logical Errors 3). Runtime Errors

Syntax Errors:
A syntax error happens when the Python code violates the rules of the language.

Example 1: Missing Parenthesis Example 2: Wrong Indentation

print("Hello World" if True:


# Error: SyntaxError print("Hello")
# Error: IndentationError

Logical Errors (Semantic Errors)


A logical error occurs when the program runs without crashing but produces wrong
output.
Example: Calculating the average of two numbers (10 and 12)
num1 = 10
num2 = 12
average = num1 + num2 / 2
print("Average:", average)

OUTPUT: Average: 16.0 (Wrong!)

Runtime Errors
A runtime error occurs while the program is running, even if the code is syntactically
correct. These happen because of invalid operations or values.
Example 1: Example 2:
num = 10 numbers = [1, 2, 3]
den = 0 print(numbers[5])
print(num / den) # Error: IndexError
# Error: ZeroDivisionError
print(x) # Error: NameError
data = {"name": "Alice"}
print(data["age"]) # Error: KeyError num = 5
text = "Hello"
file = open("data.txt", "r") print(num + text) # Error: TypeError
# Error: FileNotFoundError
Functions in Python
A function is a block of code that performs a specific task.
A function is defined once but can be executed (called) multiple times in a
program.
A function is executed only when it is called.

Python functions are broadly categorized into two types:

1). Predefined Functions (Built-in Functions)


These functions are already provided by Python.
Programmers can use them directly without defining them.
They make programming easier by performing common tasks.
Examples of Built-in Functions: print(), input(), len(), max(), int(), sum()
# Taking input from the user
name = input("Enter your name: ") # input() → takes user input

# Displaying output
print("Hello", name) # print() → displays output

# Finding the length of the string


length = len(name) # len() → returns length of string

# Displaying the result


print("Your name has", length, "letters.")

OUTPUT:
Enter your name: Karunakar
Hello Karunakar
Your name has 9 letters.

2). User-defined Functions:


User-defined functions are functions created by the programmer to perform specific
tasks.
They help in reusing code and make the program organized and readable.
A user-defined function is created using the def keyword.
The function is executed only when it is called.

Syntax
def function_name(parameters):
# block of statements
# code to be executed
return value # optional
Example: Function to Find Square of a Number

# Function definition
def square(num):
result = num * num
return result # returns the square value

# Function calls
print("Square of 4 is:", square(4))
print("Square of 9 is:", square(9))

OUTPUT:
Square of 4 is: 16
Square of 9 is: 81

Python Programs Using Functions


1.Write a Python function to find the sum of two numbers.
2.Write a Python function to calculate the area of a rectangle (length = 10 units,
breadth = 20 units).
3.Write a Python function to swap two numbers.
4.Write a Python function to find the square of a number.
5.Write a Python function to calculate simple interest (principal = 1000, rate = 5,
time = 2 years).
6.Write a Python function to find the average of three numbers.
7.Write a Python function to convert temperature from Celsius to Fahrenheit
8.Use the formula: F = (C × 9/5) + 32
9.Write a Python function to find the perimeter of a square (side = 15 units).
10.Write a Python function to print the product of two numbers.
Control Statements in Python
Control statements in Python are used to manage the flow of execution within a
program.
They allow us to decide which statements to execute, how many times to execute
them, or to skip/terminate certain parts of the code.
Types of Control Statements in Python

Type Description

Statements are executed one after another in the


Sequential Statements
order they appear.

Execute code based on a condition (e.g., if, if-else, if-


Conditional Statements
elif-else).

Looping (Range-based) Execute a block of code repeatedly using loops (for,


Statements while).

Jump Statements Alter the flow of loops using break, continue, or pass.

Sequential Statements:
Sequential statements are the simplest form of control flow in Python.
They are executed one after another in the exact order they appear in the
program.
There is no branching (decision-making) or looping (repetition) involved.
Example:
a = 10 # First statement
b = 20 # Second statement
sum = a + b # Third statement
print("Sum:", sum) # Fourth statement

Conditional Statements:
Conditional statements allow a program to make decisions and execute different
blocks of code based on certain conditions.
They control the program flow by checking a condition (True/False) and deciding
which part of the code should run.

if statement Executes a block of code only if a condition is True.

if-else Executes one block of code if the condition is True, else executes
statement another block.
if-elif-else Checks multiple conditions in sequence and executes the block for
ladder the first True condition.
Nested if An if statement inside another if statement to check further
statements conditions.
if Statement
The if statement in Python is a conditional statement that allows a program to execute
a block of code only if a specified condition is True.
If the condition evaluates to False, the code block is skipped.
It is used for decision-making in programs.
Syntax:
if condition:
# statement -1
# statement -2
# statement -3
# statement -4
# statement -5
# statement -6
# statement -7
Example:
age = 18
if age >= 18:
print("You are eligible to vote.")

OUTPUT: You are eligible to vote.

Simple If Statement Questions


1.Write a Python program to check whether a given number is positive.
2.Write a Python program to print "Welcome" if the entered password is "admin".
3.Write a Python program to check if a given number is divisible by 5.
4.Write a Python program to check if a person is eligible to vote (age ≥ 18).
5.Write a Python program to check if a given number is even.

if-else Statement:
The if-else statement lets a program choose between two blocks of code:
If the condition is True, the code inside the if block runs.
If the condition is False, the code inside the else block runs.

Syntax:
if condition:
# statement -1
# statement -2
else:
# statement -3
# statement -4
# statement -5
# statement -6
# statement -7
Example 1: Check if a number is even or odd
num = 7
if num % 2 == 0:
print("Even Number")
else:
print("Odd Number")

Example 2: Check voting eligibility


age = 16
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")

Simple If else Statement Questions


1.Write a Python program to check whether a given number is positive or negative
using an if-else statement.
2.Write a Python program to print "Welcome" if the entered password is "admin",
otherwise print "Incorrect password" using an if-else statement.
3.Write a Python program to check if a given number is divisible by 5. Print
"Divisible by 5" if True, otherwise print "Not divisible by 5" using an if-else
statement.
4.Write a Python program to check if a person is eligible to vote (age ≥ 18). Print
"Eligible to vote" if True, otherwise print "Not eligible to vote" using an if-else
statement.
5.Write a Python program to check if a given number is even or odd. Print "Even" if
the number is even, otherwise print "Odd" using an if-else statement.

if-elif-else Ladder:
The if-elif-else ladder is used when you have multiple conditions to check, but you
want only one block of code to execute—the first one that is true.

Syntax:
if condition1:
# block executed if condition1 is True
elif condition2:
# block executed if condition2 is True
elif condition3:
# block executed if condition3 is True
...
else:
# block executed if none of the above conditions are True
Example: Grading System
Write a Python program to input marks and print marks = 85
the grade as follows:
90 and above → Grade A if marks >= 90:
75 to 89 → Grade B print("Grade A")
60 to 74 → Grade C elif marks >= 75:
Below 60 → Grade D print("Grade B")
elif marks >= 60:
print("Grade C")
elif marks >= 50:
print("Grade D")
else:
print("Fail")

Write a Python program to classify the weather based on temperature:


If the temperature is greater than 35, display "Hot".
If the temperature is greater than 20 but less than or equal to 35, display
"Warm".
If the temperature is greater than 10 but less than or equal to 20, display
"Cool".
Otherwise, display "Cold".

Write a Python program to calculate discount based on the purchase amount:


Above 5000 → 20% discount
3000 to 5000 → 15% discount
1000 to 2999 → 10% discount
Below 1000 → No discount
Write a Python program to input BMI value and print category:
BMI < 18.5 → Underweight
18.5 to 24.9 → Normal
25 to 29.9 → Overweight
30 and above → Obese

Write a program to input percentage and display result:


75 and above → Distinction
60 to 74 → First Class
50 to 59 → Second Class
Below 50 → Fail

Write a program to calculate charges based on units:


Up to 100 units → ₹2 per unit
101-200 units → ₹3 per unit
Above 200 units → ₹5 per unit
Nested If Statements
A nested if is an if statement inside another if statement. It is used when one
condition depends on another.

Syntax:
if condition1:
if condition2:
# executes only if both condition1 and condition2 are True

Example 1: Positive and divisible by 3


num = 15

if num > 0: # First condition: check if number is positive


if num % 3 == 0: # Nested condition: check if divisible by 3
print("Positive and divisible by 3")

Example 2: Age and Eligibility


age = 20
has_id = True

if age >= 18: # First condition: check age


if has_id: # Nested condition: check ID
print("Eligible to vote")
else:
print("Cannot vote without ID")
else:
print("Not eligible to vote")

Simple Nested If Statement Questions


1.Write a Python program to check if a number is positive and also even.
2.Write a Python program to check if a person is eligible to vote (age ≥ 18), and if
eligible, check whether the person is also eligible for a driving license (age ≥ 21).
3.Write a Python program to check if a student passed the exam (marks ≥ 40), and
if passed, check whether the student got distinction (marks ≥ 75).
4.Write a Python program to check if a number is divisible by 3, and if it is, check
whether it is also divisible by 5.
5.Write a Python program to check if a person is a senior citizen (age ≥ 60), and if
yes, check whether the person is also eligible for a pension card (age ≥ 65).
Looping (Range-based) Statements in Python
Looping statements are used to repeat a block of code multiple times.
They help avoid writing the same code again and again, making programs efficient
and compact.
Types of Loops in Python
Python provides two main types of looping statements:
1.while loop
2.for loop

while loop
The while loop executes a block of code as long as a condition is true. When the
condition becomes false, the loop stops automatically.
A while loop needs:
Initialization (set a starting value).
Condition (checked before each iteration).
Update (change value so the loop can stop, usually increment or decrement).
Syntax: Initialization
while condition:
# code block
Update (Increment/Decrement)
else:
#code block

Example-1: Example-1: Example-1:

i=1 i=1 i = 10
while i <= 5: while i <= 5: while i >= 5:
print("Hello Python") print(i) print(i)
i=i+1 i=i+1 i=i-1

Simple while loop Questions


1.Write a Python program to print numbers from 1 to 10 using a while loop.
2.Write a Python program to print all even numbers between 1 and 20 using a
while loop.
3.Write a Python program to print the first 10 odd numbers using a while loop.
4.Write a Python program to calculate the sum of numbers from 1 to 50 using a
while loop.
5.Write a Python program to print the multiplication table of a number (input
from the user) using a while loop.
6.Write a Python program to count down from 10 to 1 using a while loop.
for loop
The for loop is used to iterate over a sequence (like a list, string, or range of
numbers).
It executes the block of code a fixed number of times.

Syntax: for variable in sequence:


# block of code

Example 1: Example 1:
Iterating through a string Find the sum of all numbers in a list
course = "PYTHON" numbers = [2, 4, 6, 8, 10]
for ch in course: total = 0
print(ch) for i in numbers:
total = total + i
print(total)

What is range() in Python?


The for loop is used to iterate over a sequence (like a list, string, or range of
numbers).
It executes the block of code a fixed number of times.
Syntax: range(start, stop, step)
start → (optional) starting number (default = 0)
stop → (required) number where the sequence ends (but stop not included)
step → (optional) difference between numbers (default = 1)
Example: Using stop value only Example: Using start and stop values
for i in range(5): for i in range(3, 8):
print(i) print(i)

Example: Using start, stop, and step values


for i in range(2, 11, 2):
print(i)

Simple while loop Questions


1.Write a Python program to print numbers from 1 to 10 using a for loop.
2.Write a Python program to print all even numbers between 1 and 20 using a for
loop.
3.Write a Python program to print the first 10 odd numbers using a for loop.
4.Write a Python program to calculate the sum of numbers from 1 to 50 using a for
loop.
5.Write a Python program to print the multiplication table of a number (input
from the user) using a for loop.
6.Write a Python program to count down from 10 to 1 using a for loop.
Nested Loop:
A nested loop is a loop inside another loop.
The outer loop runs first.
For each iteration of the outer loop, the inner loop runs completely.
This continues until the outer loop finishes.
Syntax: for outer_variable in range(start, stop, step):
# Code of outer loop

for inner_variable in range(start, stop, step):


# Code of inner loop

# Code after inner loop


# Code after outer loop

Example 1: Simple nested loop OUTPUT:


for i in range(1, 4): # Outer loop
for j in range(1, 6): # Inner loop
print("*", end="")
print() # New line after inner loop

Example 2: Print a number pattern OUTPUT:


for i in range(1, 4):
for j in range(1, i+1):
print(j, end=" ")
print()

Example 2: Print an inverted right-angled triangle OUTPUT:


for i in range(5, 0, -1):
for j in range(i):
print("*", end="")
print()

Example 2: Print a multiplication table (1 to 5) OUTPUT:


for i in range(1, 6): # Outer loop
for j in range(1, 6): # Inner loop
print(i*j, end="\t")
print()
Jump Statements in Python
Jump statements are used to alter the normal flow of a loop or program. Python
provides three jump statements:
break
continue
pass
break Statement:
The break statement is used to terminate the loop immediately, regardless of
whether the loop condition is still True.
Once break is executed, the program exits the loop and continues with the next
statement after the loop.
It is commonly used when you want to stop a loop early, for example, when a
certain condition is met.
Syntax: for variable in iterable:
if condition:
break

Example:
# Find the first number divisible by 7 in the range from 1 to 20
for i in range(1, 20):
if i % 7 == 0:
print(f"{i} is the first number divisible by 7 in the range from 1 to 20.")
break
OUTPUT: 7 is the first number divisible by 7 in the range from 1 to 20.

Example 2:
# Search for a specific item in a list and stop when found

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


search_item = "mango"

for fruit in fruits:


if fruit == search_item:
print(f"{fruit} found in the list. Stopping the search.")
break

OUTPUT: mango found in the list. Stopping the search.


continue Statement:
The continue statement is used to skip the current iteration of a loop and move to
the next iteration immediately.
Unlike break, it does not stop the loop completely.
It is often used when you want to ignore certain values or conditions in a loop.
Syntax: for variable in iterable:
if condition:
continue
# Code here executes only if condition is False

Example 1: Skip even numbers OUTPUT:


# Print all odd numbers from 1 to 10 1
for i in range(1, 11): 3
if i % 2 == 0: 5
continue # skip even numbers 7
print(i) 9

Example 2: Skip certain words in a list OUTPUT


fruits = ["apple", "banana", "cherry", "mango", "orange"] apple
for fruit in fruits: cherry
if fruit == "banana":
mango
continue # skip banana
print(fruit) orange
pass Statement:
The pass statement is used to do nothing.
It is a placeholder where Python expects a statement syntactically, but no action
is needed.
It is commonly used in empty loops, functions, or conditional blocks during
development.
Syntax: if condition:
pass

Example: i = 10
if i % 2 == 0:
pass # do nothing for even numbers

Example: def future_function():


pass # To be implemented later
print("This program runs even with an empty function.")
Q5. Categorise the following errors in Python
Classify each as Syntax Error, Logical Error, or Runtime Error:
a) 25 / 0
b) num1 = 25; num2 = 0; num1 / num2
Hint: Think about when Python will raise an error while running the code.

Q6. Python program to calculate Amount Payable on Simple Interest


Formula:

Where:
1). P = Principal
2). R = Rate of Interest per annum
3). T = Time in years
Task: Take P, R, T as input from the user and calculate Amount Payable.
Q7. Python program to repeat a string
Write a program to repeat the string "GOOD MORNING" n times, where n is an
integer entered by the user.

Q8. Python program to calculate average of 3 numbers


Write a program to find the average of three numbers entered by the user.

Q9. Write a Python program that asks the user to enter their name and age. Print a
message addressed to the user stating the year in which he/she will turn 100
years old.
Q10. What is the difference between else and elif constructs in an if statement in
Python?
Q11. Find the output of the following program segments:

12Q. Schools use Student Management Information System (SMIS) to manage


student-related data. This system provides facilities for:

Recording and maintaining personal details of students


Maintaining marks scored in assessments and computing results
Keeping track of student attendance
Managing many other student-related records

You might also like