0% found this document useful (0 votes)
5 views16 pages

BSC CS - Python - Chapter 1

The document provides an introduction to Python programming, covering its features such as being a high-level, open-source, and user-friendly language. It explains how to install Python, execute scripts using different environments, and outlines various data types and their syntax. Additionally, it discusses Python's internal components, exception handling, and includes examples of basic programming tasks.

Uploaded by

HARSH MISHRA
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)
5 views16 pages

BSC CS - Python - Chapter 1

The document provides an introduction to Python programming, covering its features such as being a high-level, open-source, and user-friendly language. It explains how to install Python, execute scripts using different environments, and outlines various data types and their syntax. Additionally, it discusses Python's internal components, exception handling, and includes examples of basic programming tasks.

Uploaded by

HARSH MISHRA
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
You are on page 1/ 16

13 B.Sc.

CS Sem - I 1 - Introduction to Python Programming

Features of Python: iii. Python is having a large collection of


modules.
1. High level programming language
i. High level language is closer to Human iv. Python provides modules for system calls,
language than machine language. file Input/Output, sockets and interfaces to the
GUI kit such as Tk.
ii. In other words high level language is
English like language and on the other hand 7. Extensible
low level language is a machine code in which If you are writing application in C and you are
instructions and data are directly executed by linking the Python interpreter into an

E
the CPU. application then you can use it as an extension
or command language for that application.

EG
2. Python is a free and open source language
Open-source software is computer software 8. Python is object oriented
that is released under a license in which the i. Python supports the object oriented

LL
copyright holder grants users the rights to use, programming concept.
study, change, and distribute the software and
its source code to anyone and for any purpose. ii. Object-oriented programming is a

O
programming paradigm based on the concept

C
3. Python is simple of objects, which can contain data and code:
i. There is no need of declaring variables in the data in the form of fields, and code in the form
python. of procedures.
EE
ii. In a single statement the user can express iii. In OOP, computer programs are designed
the complex operations. by making them out of objects that interact
R

with one another.


iii. It uses indentation for statement grouping.
EG

As in C and C++ we use opening and closing Installing Python


brackets. To install the python perform the following
steps:
.D

iv. Python offers more structure and support


for lengthy or big programs than batch files or 1.​ Go to http://www.python.org
shell scripts can offer.
.M

2.​ Click "Download".


4. Error checking and high level data type
.P

Python is having built in high level data types


for example dictionaries and flexible arrays.
IG

5. Platform independent language


i. Python is platform independent, it means
R

you can write your python program on any


operating system and you can run it on any
SH

machine which has python.

ii. Python run on any operating system like


windows, Unix, DOS etc. i. Download latest python version from the
6. User friendly given list for windows installer.
i. Python language is having the feature of ii. Install the program.
abstraction and hiding of the details which
make it more users friendly. iii. Double clicking a python script launches a
command-line window (cmd) for executing
ii. In Python you can divide your program into any python script. You can also use any IDE
modules that can be used in other python for the same.
programs.

1
2. Using an Integrated Development
Environment (IDE)

Popular IDEs for Python include PyCharm,


VS Code, and Jupyter Notebook.

PyCharm:

I.​ Open PyCharm.


Execution of a Python Program: II.​ Create or Open a Project.
i. The python file has .py extension.
III.​ Write or Open Your Python Script.
ii. Create a simple Python script called IV.​ Run the Script:

E
hello.py:
Right-click on the file in the project explorer

EG
print("Hello, World!") and select Run 'filename', or use the Run
button at the top.
iii. To execute this script, save the file as

LL
hello.py. VS Code:

I.​ Open VS Code.

O
1. Using the Command Line (Terminal)
II.​ Open Your Project Folder.

C
Windows: III.​ Open Your Python File.
IV.​ Run the Script:
EE
I.​ Open Command Prompt:
Press Ctrl + Shift + P to open the command
Press Win + R, type cmd, and hit Enter. palette, type Run Python File, and select it.
Alternatively, use the play button in the top
R

II.​ Navigate to the Directory: right of the editor.


EG

Use the cd command to change the directory to Jupyter Notebook:


where your Python file is located.
.D

I.​ Open Jupyter Notebook.


II.​ Create a New Notebook or Open an
cd path\to\your\directory Existing One.
.M

III.​ Write Your Python Code in a Cell.


III.​ Run the Python File: IV.​ Run the Cell:
.P

Use the python or python3 command followed Press Shift + Enter or click the Run button in
IG

by the name of your file. the toolbar.

python filename.py Flavours of Python:


R

Python has several flavors, which refer to


SH

different implementations of the Python


language. Each flavor serves different
purposes and offers unique features.

Here are some of the most well-known flavors of Python:

Flavor Description Features Use Case

CPython The default and most Highly compatible with Python


widely-used libraries and extensions. It is the General-purpose

2
implementation of reference implementation of the programming, most
Python, written in C. Python language. Known for its commonly used for
stability and extensive support. development.

Jython An implementation of Allows Python code to interact Situations where


Python designed to seamlessly with Java code. integration with Java
run on the Java Can use Java classes directly in applications or libraries
platform. Python code. is needed.

IronPython An implementation of
Python that targets the Fully integrated with .NET, Development of .NET

E
.NET Framework and allowing for the use of .NET applications or
Mono. libraries.Can be used to develop integration with .NET

EG
.NET applications using Python. libraries.

LL
PyPy An alternative Uses a Just-In-Time (JIT) Performance-critical
implementation of compiler to improve applications, where
Python which focuses performance. Compatible with execution speed is

O
on speed and existing Python code (though important.

C
efficiency. some C extensions might not
work).
EE
MicroPython A lean and efficient Small footprint, suitable for
implementation of microcontrollers. Supports a Embedded systems, IoT
R

Python 3 designed to subset of Python 3 features. devices, and other


run on resource-constrained
EG

microcontrollers and environments.


in constrained
environments.
.D
.M

Innards of Python: i. Compiler: Converts Python source code (.py


files) into bytecode (.pyc files).
.P

Understanding the innards of Python involves


looking at the internal components and a.​ Lexical Analysis: Breaks down the source
IG

architecture of the Python interpreter, code into tokens.


particularly CPython, the reference b.​ Parser: Analyzes the token stream to
implementation. generate a syntax tree (AST - Abstract
R

Syntax Tree).
SH

Here’s a breakdown of the key components: c.​ Code Generator: Converts the AST into
bytecode instructions.
1. Source Code
Written in C: CPython is primarily written in ii. Bytecode: An intermediate representation
the C programming language. of the source code, which is
platform-independent and executed by the
Open Source: The source code is freely Python virtual machine (PVM).
available, allowing developers to study and
modify it. 3. Python Virtual Machine (PVM)
Execution Engine: The PVM executes the
2. Interpreter Components bytecode instructions. It’s a stack-based virtual

3
machine where each instruction is executed Try-Except Blocks: Python uses try-except
one at a time. blocks for error handling, which allows
programs to handle runtime errors gracefully.
Main Loop: The PVM has a main loop that
fetches the next bytecode instruction, decodes Exception Hierarchy: Python has a built-in
it, and executes it. hierarchy of exceptions, providing a structured
way to handle different types of errors.
4. Memory Management
Object Model: Everything in Python is an Overview of Execution Flow
object, including data types and functions. The 1.​ Write Code: You write Python source code
object model manages the creation, in a .py file.
manipulation, and deletion of objects.

E
2.​ Compile to Bytecode: The Python

EG
Garbage Collection: Python uses reference compiler translates the source code into
counting and a cyclic garbage collector to bytecode, stored in .pyc files.
manage memory. When an object’s reference
count drops to zero, it is deallocated. 3.​ Execute Bytecode: The PVM executes the

LL
bytecode, interacting with the operating
6. Exception Handling system and hardware as necessary.

O
C
EE
R
EG

Comments: ii. These are actually multi-line strings that are


not assigned to any variable, so they are
i. Comments are used to add notes or
ignored by the interpreter.
explanations within your code.
.D

Example:
ii. They are ignored by the Python interpreter,
.M

so they don't affect how the code runs. There


are two types of comments in Python: '''​
single-line comments and multi-line This is a multi-line comment.​
.P

comments. It can span multiple lines.​


'''​
IG

Single-line Comments print("Hello, World!")

Single-line comments start with a # symbol.


R

Docstrings:
Everything after the # on that line is ignored
SH

by the interpreter. i. Docstrings (documentation strings) are a


special type of comment used to describe
Example: modules, classes, functions, and methods.

ii. They are written using triple quotes (''' or


# This is a single-line comment​
""") and can be accessed programmatically via
print("Hello, World!") # This is an inline
the __doc__ attribute.
comment
Example:
Multi-line Comments
i. Multi-line comments can be created using def greet(name):​
triple quotes (''' or """). """​

4
This function greets the person whose i. The second mode of IDLE is script mode. In
name is passed as a parameter.​ this mode you can write, edit, load and save
​ your Python program like a word processor.
Parameters:​
ii. You can also perform cut, copy, paste
name (str): The name of the person to
operation.
greet.​

iii. To open the window in script mode:
Returns:​
None​ a.​ Click on file menu on the interactive
"""​ window.
print(f"Hello, {name}!")​ b.​ Click on new file.

E
# Accessing the docstring​

EG
print(greet.__doc__)

LL
IDLE:

i. Python comes with a Graphical User

O
Interface (GUI) Integrated Development

C
Environment called IDLE.

ii. The IDLE helps the user to write the Experiment - 1


EE
program. It also enables the user to save and
edit their work. Data Types in Python:
R

1.​ Interactive mode: 1.​ Integer (int):


EG

i. In the interactive mode the user will tell the Represents whole numbers without a decimal
Python what to do and Python will do it point.
.D

immediately. Syntax: x = 5

ii. To open Python in interactive mode in x = 5​


print(type(x)) # Output: <class 'int'>
.M

windows, perform following steps:


.P

1.​ Click on start button 2.​ Float (float):


2.​ Click on Programs
Represents numbers with a decimal point.
IG

3.​ Click on Python version


4.​ Click on IDLE (Python GUI) Syntax: x = 5.7
x = 5.7​
R

iii. The open window is known as "Python print(type(x)) # Output: <class 'float'>
Shell". >>> is known as the command prompt.
SH

3.​ String (str):

Represents a sequence of characters.


Syntax: x = "Hello"
x = "Hello"​
print(type(x)) # Output: <class 'str'>

4.​ Boolean (bool):

2. Script mode: Represents True or False.


Syntax: x = True

5
x = True​ 1. Write a program that creates and prints
print(type(x)) # Output: <class 'bool'> integer and float variables.

2. Write a program that creates and prints


5.​ List (list): string variables.

Represents an ordered collection of items. 3. Write a program that creates and prints
Syntax: x = [1, 2, 3] boolean variables.
x = [1, 2, 3]​
print(type(x)) # Output: <class 'list'> 4. Write a program that creates and prints a
list.
6.​ Tuple (tuple):

E
5. Write a program that creates and prints a
tuple.

EG
Represents an ordered collection of items that
cannot be modified (immutable). 6. Write a program that creates and prints a
Syntax: x = (1, 2, 3) dictionary.

LL
x = (1, 2, 3)​
print(type(x)) # Output: <class 'tuple'> 7. Write a program that creates and prints a set.

O
8. Write a program that creates a variable with
7.​ Dictionary (dict): `None` value and prints it.

C
Represents a collection of key-value pairs. 9. Write a program that creates and prints a
EE
Syntax: x = {"key": "value"} complex number.
x = {"name": "John", "age": 30}​
print(type(x)) # Output: <class 'dict'> 10. Write a program that creates a list
R

containing various data types and prints it.


EG

8.​ Set (set):


Rules to Name the python variables:
Represents an unordered collection of unique
1. The variable name should begin with the
.D

items.
letter (a-z, A-Z) or underscore (_)
Syntax: x = {1, 2, 3}
.M

x = {1, 2, 3}​ 2. The other characters in the variable name


print(type(x)) # Output: <class 'set'> can be numbers, letters or underscore.
.P

9.​ NoneType (None): 3. Variable name can be of any length.


IG

Represents the absence of a value. 4. Keywords cannot be used as a variable


Syntax: x = None names.
R

x = None​ Python Keywords: False, None, True, and, as,


SH

print(type(x)) # Output: <class 'NoneType'> assert, async, await, break, class, continue, def,
del, elif, else, except, finally, for, from, global,
10.​Complex (complex): if, import, in, is, lambda, nonlocal, not, or,
pass, raise, return, try, while, with, yield.
Represents complex numbers with real and
imaginary parts. Input Function:
Syntax: x = 1 + 2j
Syntax:
x = 1 + 2j​
print(type(x)) # Output: <class 'complex'>
variable = input(prompt)
Home Work Exercise - 1
prompt: A string, representing a message to

6
display to the user. This parameter is optional. ii. The first element of this list is the name of
the script itself.
Example:
import sys​
name = input("Enter your name: ")​

print("Hello, " + name + "!")
# Print all command line arguments​
print("count of numbers:", len(sys.argv))​
Output Statement: print("Numbers:", sys.argv)​

Syntax:
# Access individual arguments​
if len(sys.argv) > 1:​

E
print(*objects, sep=' ', end='\n', print("First Number:", sys.argv[1])​

EG
file=sys.stdout, flush=False) ​
print("Addition total: ", sys.argv[1] +
●​ objects: The values to be printed. sys.argv[2])

LL
Multiple values can be separated by
commas.

O
●​ sep: String inserted between values,
default is a space.

C
●​ end: String appended after the last
value, default is a newline.
EE
●​ file: An object with a write method,
default is sys.stdout.
●​ flush: Whether to forcibly flush the
R

stream.
EG

Example:

# Basic usage of print​


.D

print("Hello, World!")​

.M

# Printing multiple objects​


print("Name:", "Alice", "Age:", 30)​
.P


# Custom separator and end​
IG

Using argparse:
print("apple", "banana", "cherry", sep=", ",
end=". ")​ The argparse module provides a more flexible
R

print("This is a new sentence.") and user-friendly way to handle command line


SH

arguments, including types and help messages.


Command Line Arguments:
Command line arguments in Python allow you import argparse​
to pass parameters to your Python script when ​
executing it from the command line. # Create the parser​
parser =
Using sys.argv: argparse.ArgumentParser(description="A
simple command line argument example")​
i. The sys module provides a list called argv

that contains command line arguments passed
# Add arguments​
to the script.

7
parser.add_argument('name', type=str, operator.
help='Your name')​
parser.add_argument('age', type=int, - It subtracts right hand operand
from the left hand operand.
help='Your age')​
​ * It multiplies values on either side
# Parse the arguments​ of the operator.
args = parser.parse_args()​
​ / It divides left hand operand by
right hand operand.
# Use the arguments​
print(f"Hello, {args.name}! You are % It divides left hand operand by

E
{args.age} years old.") right hand operand and returns
remainder.

EG
Save this script as script.py, and you can run it
** It performs exponential (power)
from the command line like this: calculation on operators.

LL
python script.py Alice 30 // Floor division - The division of
operands where the result is the

O
quotient in which the digits after
Output:

C
the decimal point are removed.
But if one of the operands are
negative, the result is floored, i.e.,
EE
Hello, Alice! You are 30 years old.
rounded away from zero (towards
negative infinity)
R

Operators in Python:
i. Operators are special symbols that represent
EG

Example:
calculation like addition and subtraction.
a = 34​
ii. The values which operator uses are called b = 23​
.D

operands. c = 0​
c = a + b​
For example: >>>2+3
.M

print("1. Addition result", c) #1. Addition


Here, 2 and 3 are the operands and the + is the result 57​
.P

operator. c = a - b​
print("2. Subtraction result", c) #2.
IG

Types of operators: Subtraction result 11​


1.​ Arithmetic c = a/b​
2.​ Comparison (Relational)
R

print("3. Division result", c) #3. Division


3.​ Assignment result 1.4782608695652173​
SH

4.​ Logical c = a%b​


5.​ Bitwise print("4. Modulus result", c) #4. Modulus
6.​ Membership result 11​
7.​ Identity a = 34​
b = 23​
1. Arithmetic Operators: c = a**b​
print("5. Exponential result", c) #5.
Operator Description Exponential result 8​
a = 20​
+ It adds values on either side of the b = 5​

8
c = a // b​ < If value of the left operand is less
print("6. Floor division result", c) #Floor than the value of right operand,
division result 4 then condition becomes true.

>= If value of the left operand is


Classwork Exercise - 1 greater than or equal to the value
1. Write a program to perform basic arithmetic of right operand, then condition
operations (addition, subtraction, becomes true.
multiplication, division) on two integers. <= If value of the left operand is less
2. Write a program to calculate the area and than or equal to the value of right
perimeter of a rectangle using float values for operand, then condition becomes

E
length and width. true.

EG
3. Write a program to concatenate two strings
and print the result. Example:
4. Write a program to convert a given

LL
a = 10​
temperature from Celsius to Fahrenheit and
b = 5​
vice versa.
c = a == b​

O
5. Write a program to swap two variables and
print(c) #False​
print their values before and after swapping.

C
c = a != b​
print(c) #True​
Homework Exercise - 2
EE
c = a > b​
1. Write a program to find the average of three
print(c) #True​
numbers entered by the user.
c = a < b​
R

2. Write a program to calculate the compound


print(c) #False
interest given the principal, rate, and time.
EG

3. Write a program to evaluate and print the


result of a complex arithmetic expression 3. Assignment Operators:
.D

involving multiple operators.


4. Write a program to check if a given number Operator Description
is even or odd using the modulo operator.
.M

5. Write a program to calculate the sum of the = It is used to assign the values of
digits of a given integer. right side operand to the left side
.P

operand.
IG

2. Comparison Operators: += It is used to add right operand to


the left operand and result is
assigned to the left operand.
R

Operator Description
SH

== If the values of two operands are -= The right operand gets subtracted
equal, then the condition becomes from the left operand and the
true. result is assigned to the left
operand.
!= If the values of two operands are
not equal, then condition becomes *= The right operand get multiplied
true. with the left operand and the
result is assigned to the left
> If value of the left operand is operand.
greater than the value of right
operand, then condition becomes /= The left operand is divided by the
true. right operand and the result is

9
assigned to the left operand. given by the right operand.

Example: Example:
a = 20​ print(bin(60)) #0b111097​
b = 15​ print(bin(13)) #0b1101​
c = 0​ print(60 & 13, bin(60 & 13)) #12 0b1100​
c = a + b​ print(60 | 13, bin(60 | 13)) #61 0b111101​
print(c) #35​ print(60 ^ 13, bin(60 ^ 13)) #49 0b110001​
c += a​ print(60 << 2, bin(60 << 2)) #240
print(c) # 55​ 0b11110000​

E
c *= a​ print(60 >> 3, bin(60 >> 2)) #7 0b1111

EG
print(c) #11.00​
c /= a​ 5. Logical Operators:
print(c) #55.0​

LL
c = 2​ Operator Description
c %= a​
And Logical AND - If both the

O
print(c) #2​ operands are true then condition

C
c **= a​ becomes true.
print(c) #1048576​
Or Logical OR - If any of the two
EE
c //= a​
print(c) #52428 operands are non-zero then
condition becomes true.
R

4. Bitwise Operators: Not Logical NOT - Used to reverse


EG

the logical state of its operand.


Operator Description

& It is a binary AND operator. This 6. Membership Operators:


.D

operator is used to copy a bit to


Operator Description
the result if it exists in both
.M

operands. in Evaluates to true if it finds a


variable in the specified sequence
| It is binary OR operator. It copies
.P

and false otherwise.


a bit if exists in any operand.
IG

not in Evaluates to true if it does finds a


^ It is binary XOR operator. It
variable in the specified sequence
copies a bit if it is set in one
and false otherwise.
operand but not both.
R
SH

~ It is binary Ones Complement Example:


operator. It is unary and has the
effect of ‘flipping bits’’ a = 10​
b = 20​
<< It is binary left shift operator. It list = [1,2,3,4,5]​
shifts the left operands value to ​
the left by the number of bits
print(a in list) #False​
given by the right operand.
print(b not in list) #True
>> It is binary right shift operator. It
shifts the left operands value to
6. Identity Operators:
the right by the number of bits

10
*, /, //, %, +, -, <<, >>, &, ^, |,==, !=, >, >=, <,
Operator Description
<=, is, is not, in, not in, and, or
is Evaluates to true if the variables
on either side of the operator Right-associative operators (evaluated from
point to the same object and false right to left):
otherwise.
**, =, +=, -=, *=, /=, //=, %=, **=, &=, |=, ^=,
Is not Evaluates to false if the variables >>=, <<=, not
on either side of the operator
point to the same object and true
Example:
otherwise.
# Addition and subtraction are

E
Example: left-associative​

EG
result = 10 - 2 + 3​
a = 30​ # Evaluation: (10 - 2) + 3​
b = 30​ # Result: 8 + 3 = 11​

LL
print(a is b) #True​ ​
print(a is not b) #False # Multiplication and division are

O
left-associative​
Precedence of Operators: result = 20 / 4 * 2​

C
# Evaluation: (20 / 4) * 2​
# Result: 5 * 2 = 10
EE
Level Category Operators

7 (high) exponent **
R

# Exponentiation is right-associative​
6 multiplication *,/,//,% result = 2 ** 3 ** 2​
EG

# Evaluation: 2 ** (3 ** 2)​
5 additional +,- # Result: 2 ** 9 = 512
.D

4 relational ==, !=, <=, >=,


<, >
result = 3 + 5 * 2 ** 2 - 8 / 4
.M

3 logical not
Exponentiation (**) has the highest
.P

2 logical and
precedence: 2 ** 2 evaluates to 4
IG

1 (low) logical or
Multiplication and Division (*, /): 5 * 4
evaluates to 20, 8 / 4 evaluates to 2.
R

Associativity of Operators: Addition and Subtraction (+, -): 3 + 20


SH

evaluates to 23, 23 - 2 evaluates to 21.


i. Associativity defines the direction in which
an expression is evaluated when operators of Thus, the final result of the expression is 21.
the same precedence appear in the same
expression. Experiment - 2

ii. Operators in Python are typically either


Classwork Exercise - 2
left-associative or right-associative.
1. Write a program to demonstrate the use of
Left-associative operators (evaluated from arithmetic operators (addition, subtraction,
right to left): multiplication, division, modulus,

11
exponentiation, floor division) and print the 1. The if Statement
results. i. The if statement evaluates a condition.
2. Write a program to compare two numbers
using comparison operators (==, !=, >, <, >=, ii. If the condition is true, the code block
<=) and print whether the conditions are True inside the if statement is executed.
or False.
3. Write a program to demonstrate the use of iii. It allows the program to make decisions
logical operators (and, or, not) with boolean and execute different actions based on the
values and print the results. condition.
4. Write a program to perform bitwise
operations (AND, OR, XOR, NOT, shift left, Syntax:

E
shift right) on two integer values and print the

EG
results. if condition:​
5. Write a program to demonstrate the use of # code to execute if condition is true
assignment operators (+=, -=, *=, /=, //=, %=,

LL
=, &=, |=, ^=, >>=, <<=) and print the results Example:
after each operation.

O
number = 5​

C
if number > 0:​
Homework Exercise - 3 print("The number is positive.")
EE
1. Write a program to show the precedence of
operators by evaluating and printing the result
of a complex expression involving multiple 2. The if … else Statement
R

operators (e.g., 3 + 4 * 2 / (1 - 5) ** 2 ** 3). i. The if … else statement evaluates a


EG

2. Write a program to illustrate the condition.


associativity of arithmetic operators by
evaluating and printing the result of ii. If the condition is true, the code block
.D

expressions like 10 - 3 - 2 and 10 / 2 / 2. inside the if statement is executed.


3. Write a program to demonstrate the use of
iii. If the condition is false, the code block
.M

the ternary operator (conditional expression) to


inside the else statement is executed.
assign a value based on a condition and print
.P

the result.
iv. This provides a way to handle alternative
4. Write a program to use the in and not in
actions.
IG

operators to check membership in a list and


print the results. Syntax:
5. Write a program to combine multiple
R

operators in a single expression to evaluate


if condition:​
SH

and print the result, explaining the precedence


# code to execute if condition is true​
and associativity rules applied.
else:​
# code to execute if condition is false
Control Statements:
i. Control statements in programming are used Example:
to manage the flow of execution in a program.
ii. They help in making decisions, executing
number = -3​
loops, and controlling the flow based on
if number > 0:​
various conditions.
print("The number is positive.")​

12
else:​ while condition:​
print("The number is non-positive.") # code to execute while condition is true

3. The if … elif … else Statement Example:


i. The if … elif … else statement allows for
multiple conditions to be checked sequentially. count = 1​
while count <= 5:​
ii. If a condition is true, its corresponding code print(count)​
block is executed, and the rest are skipped. If count += 1
none of the conditions are true, the code block

E
inside the else statement is executed. 5. Loop Statement - for loop

EG
iii. This allows for more complex i. The for loop iterates over a sequence (like a
decision-making. list, tuple, or range) and executes a block of

LL
code for each item in the sequence.
Syntax:
ii. It is useful for iterating a known number of

O
times or over a known sequence of elements.
if condition1:​

C
# code to execute if condition1 is true​ Syntax:
elif condition2:​
EE
# code to execute if condition2 is true​
for variable in sequence:​
else:​
# code to execute for each item in the
R

# code to execute if none of the


sequence
conditions is true
EG

Example:
Example:
.D

for i in range(1, 6):​


number = 0​
print(i)
.M

if number > 0:​


print("The number is positive.")​
.P

elif number == 0:​ 6. Infinite loop


print("The number is zero.")​ i. An infinite loop continues to execute
IG

else:​ indefinitely because the condition always


print("The number is negative.") evaluates to true.
R

4. Loop Statement - while loop ii. Such loops must be controlled or terminated
SH

manually.
i. The while loop repeatedly executes a block
of code as long as the specified condition iii. They are useful in scenarios where the loop
remains true. must run until an external condition is met or a
break statement is encountered.
ii. It is useful for situations where the number
of iterations is not known beforehand and Syntax:
depends on dynamic conditions.
while True:​
Syntax:
# code to execute indefinitely

13
Example: for i in range(3):​
print(i)​
while True:​ else:​
print("This will run forever unless print("Loop is done.")
stopped manually.")
9. break statement
7. Nested loop
i. The break statement is used to exit a loop
i. A nested loop is a loop inside another loop. prematurely when a specified condition is met.
The inner loop completes all its iterations for
each single iteration of the outer loop. ii. This allows for immediate termination of

E
the loop, skipping the remaining iterations.

EG
ii. This is useful for working with
multi-dimensional data structures, such as Syntax:
matrices.

LL
for variable in sequence:​
Syntax: if condition:​

O
break​
for outer_variable in outer_sequence:​ # more code

C
for inner_variable in inner_sequence:​
# code to execute for each combination
EE
Example:
of outer and inner variables

for i in range(5):​
R

Example: if i == 3:​
EG

break​
for i in range(1, 4):​ print(i)
for j in range(1, 4):​
.D

print(i, j)
10. continue statement
i. The continue statement skips the current
.M

8. The else suite


iteration of the loop and moves to the next
i. The else suite can be used with loops to iteration.
.P

execute a block of code after the loop


IG

completes all its iterations normally (i.e., not ii. It is useful for skipping over certain
terminated by a break statement). conditions within a loop without terminating
the entire loop.
R

ii. It is useful for post-loop processing.


Syntax:
SH

Syntax:
for variable in sequence:​
for variable in sequence:​ if condition:​
# code to execute for each item in the continue​
sequence​ # more code
else:​
# code to execute after the loop finishes Example:

Example: for i in range(5):​

14
if i == 2:​ 13. return statement
continue​ i. The return statement is used to exit a
print(i) function and optionally pass a value back to
the caller.
11. pass statement
ii. It allows functions to produce outputs and
i. The pass statement is a null operation; it end their execution at any point, returning
does nothing when executed. control to the point where the function was
called.
ii. It is used as a placeholder in situations
where a statement is syntactically required but Syntax:

E
no action is needed, such as in stubs or during

EG
code development. def function_name(parameters):​
# code​
Syntax:
return value

LL
if condition:​
Example:

O
pass​
# more code

C
def add(a, b):​
return a + b​
EE
Example:
result = add(3, 4)​
print(result)
for i in range(5):​
R

if i == 3:​
EG

pass # Placeholder for future code​ Experiment - 4


print(i)
.D

Classwork Exercise - 3
12. assert statement 1. Write a program that takes an integer input
i. The assert statement is used for debugging from the user and prints "Even" if the number
.M

purposes. is even.
2. Write a program that takes an integer input
.P

ii. It tests a condition and triggers an from the user and prints "Positive" if the
IG

AssertionError if the condition is false, number is greater than zero, otherwise prints
optionally displaying an error message. "Non-positive".
3. Write a program that takes an integer input
R

iii. It helps to catch and diagnose bugs early in from the user and prints "Positive", "Zero", or
the development process.
SH

"Negative" based on the value of the number.


4. Write a program that prints the numbers
Syntax: from 1 to 5 using a while loop.
5. Write a program that prints each character
assert condition, "optional error message" of a string entered by the user using a for loop.

Example: Homework Exercise - 3


1. Write a program that continuously takes
x = 10​ integer inputs from the user and prints them.
assert x > 5, "x should be greater than 5" The loop should only stop if the user enters the
number -1.

15
2. Write a program that prints a multiplication
table from 1 to 3 using nested loops.
3. Write a program that iterates through a list
of numbers and prints each number. After the
loop ends, print "Loop completed" using the
else suite.
4. Write a program that iterates through
numbers from 1 to 10 and prints each number.
If the number is 5, break the loop.
5. Write a program that iterates through
numbers from 1 to 5 and prints each number,

E
but skips the number 3.

EG
LL
O
C
EE
R
EG
.D
.M
.P
IG
R
SH

16

You might also like