Unit 1 Python Programming Notes
Unit 1 Python Programming Notes
What is Python?
Python is a high-level, cross-platform, and open-sourced programming language.
Introduction to Python
Python is a general-purpose, high-level, interpreted programming language that supports multiple
programming paradigms, including procedural, object-oriented, and functional programming, and is widely
used among the developers’ community. Python was mainly developed for emphasis on code readability,
and its syntax allows programmers to express concepts in fewer lines of code. It was developed by Guido
van Rossum during 1985- 1990. Python got its name from “Monty Python’s flying circus”. Python was
released in the year 2000.
Python is interpreted: Python is processed at runtime by the interpreter. You do not need to compile
your program before executing it.
Python is Interactive: You can actually sit at a Python prompt and interact with the interpreter directly
to write your programs.
Python is Object-Oriented: Python supports Object-Oriented style or technique of programming that
encapsulates code within objects.
Python is a Beginner's Language: Python is a great language for the beginner- level programmers
and supports the development of a wide range of applications.
The following are the primary factors to use python in day-to-day life:
Python is object-oriented: Structure supports such concepts as polymorphism, operation overloading
and multiple inheritance.
Indentation: Indentation is one of the greatest feature in python.
It’s free (open source): Downloading python and installing python is free and easy.
It’s Powerful: Dynamic typing, Built-in types and tools Library utilities, Third party utilities (e.g.
Numeric, NumPy, sciPy) Automatic memory management.
It’s Portable: Python runs virtually every major platform used today. As long as you have a compatible
python interpreter installed, python programs will run in exactly the same manner, irrespective of
platform.
It’s easy to use and learn: No intermediate compile, Python Programs are compiled automatically to
an intermediate form called byte code, which the interpreter then reads. This gives python the
development speed of an interpreter without the performance loss inherent in purely interpreted
languages. Structure and syntax are pretty intuitive and easy to grasp.
Interpreted Language: Python is processed at runtime by python Interpreter.
Interactive Programming Language: Users can interact with the python interpreter directly for
writing the programs.
Straight forward syntax: The formation of python syntax is simple and straight forward which also
makes it popular.
1|Pa ge
Features of Python
Applications of Python
Python Versions
Python has several major versions, with the most notable being:
Python 2.x: Legacy version; officially discontinued in January 2020.
Python 3.x: Current version with many improvements and features; recommended for all new
projects.
2|Pa ge
Installation of Python
Advantages:
Python, in interactive mode, is good enough to learn, experiment or explore.
Working in interactive mode is convenient for beginners and for testing small pieces of code.
Drawback:
We cannot save the statements and have to retype all the statements once again to re-run them.
3|Pa ge
Integrated Development Environments (IDEs) (Script mode)
we cannot save the statements for further use we can save the statements for further use and we
and we have to retype all the statements to re- no need to retype all the statements to re-run
run them. them.
We can see the results immediately. We cant see the code immediately.
Python Basics
Identifiers:
Definition: Identifiers in Python are names used to identify variables, functions, classes, modules,
and other objects in the code.
Rules to write an identifier:
Must start with a letter (a-z, A-Z) or an underscore ( _ ).
Can contain letters, digits (0-9), and underscores.
Case-sensitive (e.g., myVar and myvar are different).
Cannot be a Python Keyword
No special characters are allowed
Keywords:
Definition: Keywords in Python are reserved words that have special meanings and serve specific
purposes in the language syntax. Python keywords cannot be used as the names of variables, functions
and classes or any other identifier.
Examples:
True False None And
or not is If
4|Pa ge
else elif for while
Statement: A line of code that performs an action (e.g., assignments, function calls).
Expression: A combination of values and operators that evaluates to a value (e.g., 3 + 4).
Variables:
In Python, variables are containers, which is used to store data values. Python supports various datatypes,
including integers, floats, strings, and booleans. It represents the kind of value that tells what operations
can be performed on a particular data. Variables are created when we assign a value to them, using the
assignment operator (=).
Example:
var = "Saradavilas"
print(var)
Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the
reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals
or characters in these variables.
Output:
Rules for Python variables:
A variable name must start with a letter or the
Saradavilas underscore (_) character
college,Mysore
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
5|Pa ge
Variables Assignment in Python/Declaration and Initialization of Variables:
# An integer assignment
age = 45
# A floating point
salary = 1456.8
# A string
name = "John"
print(age)
print(salary)
print(name)
Output:
45
1456.8
John
We can re-declare the Python variable once we have declared the variable already.
# display
print("Before declare: ", Number)
Output:
6|Pa ge
Types of Variables:
There are two types of variables: Global variables and Local variables.
The scope of global variables is the entire program whereas the scope of local variable is limited to the
function where it is defined.
Example
def func():
x = "Python"
s = "test"
print(x)
print(s)
s = "BCA"
print(s)
func()
print(x)
Output:
In above program- x is a local variable whereas s is a global variable, we can access the
local variable only within the function it is defined (func() above) and trying to call local variable outside its
scope(func()) will through an Error as shown below −
Python
test
BCA
Local variables:
Local variables can only be reached within their scope(like func() above). Like in below program-
there are two local variables – x and y.
Example
def sum(x,y):
sum = x + y return sum print(sum(5, 10))
Output
The variables x and y will only work/used inside the function sum() and they don’t exist outside of the
function. So trying to use local variable outside their scope, might through NameError.
So obviously below line will not work.
7|Pa ge
File "[Link]", line 2 sum = x + y
^
IndentationError: expected an indented block
Global variables
A global variable can be used anywhere in the program as its scope is the entire program.
Let’s understand global variable with a very simple example
Example
z = 25
def func():
global z
print(z)
z=20
func()
print(z)
Output
25
20
A calling func(), the global variable value is changed for the entire program.
Below example shows a combination of local and global variables and function parameters –
Output
45 17 81 9
3
8|Pa ge
Assigning Values to Variables:
Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used
to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable.
For example −
a= 100
b = 1000.0
c = "John" print (a) print (b) print (c)
# An integer assignment
# A floating point
# A string
Multiple Assignment:
Python allows you to assign a single value to several variables simultaneously.
For example:
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables.
For example:
a,b,c = 1,2,"saradavilas“
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively,
and one string object with the value "john" is assigned to the variable c.
Output Variables:
The Python print statement is often used to output variables. Variables do not need to be
declared with any particular type and can even change type after they have been set.
x=5
x = "saradavilas "
print(x)
# x is of type int
# x is now of type str
Output
Saradavilas
Example:
name = input("Enter your name: ")
print("Hello,", name, "! Welcome!")
Output
Enter your name: GeeksforGeeks
Hello, GeeksforGeeks ! Welcome!
The code prompts the user to input their name, stores it in the variable "name" and
then prints a greeting message addressing the user by their entered name.
At its core, printing output in Python is straightforward, thanks to the print() function.
This function allows us to display text, variables and expressions on the console.
Let's begin with the basic usage of the print() function:
In this example, "Hello, World!" is a string literal enclosed within double quotes.
When executed, this statement will output the text to the console.
print("Hello, World!")
Output
Hello, World!
Printing Variables
We can use the print() function to print single and multiple variables. We can print
multiple variables by separating them with commas.
Example:
s = "Brad"
print(s)
s = "Anjelina"
age = 25
city = "New York"
print(s, age, city)
Output
Brad
Anjelina 25 New York
We are taking multiple input from the user in a single line, splitting the values entered
by the user into separate variables for each value using the split() method. Then,
it prints the values with corresponding labels, either two or three, based on the number
of inputs provided by the user.
Output
Enter two values: 5 10
Number of boys: 5
Number of girls: 10
Expressions:
Examples:
Y = x + 17
>>> x = 10
>>> z = x + 20
>>> z
30
>>> x = 10
>>> y = 20
>>> c = x + y
>>> c 30
A value all by itself is a simple expression, and so is a variable.
>>> y = 20
>>> y 20
Python also defines expressions only contain identifiers, literals, and operators. So,
Identifiers: Any name that is used to define a class, function, variable module, or object
is an identifier.
Literals: These are language-independent terms in Python and should exist independently in any
programming language. In Python, there are the string literals, byte literals, integer literals,
floating point literals, and imaginary literals.
Generator expression:
.
Conditional expression:
1. Constant Expressions: These are the expressions that have constant values only.
2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values, operators,
and sometimes parenthesis. The result of this type of expression is also a numeric value. The operators
used in these expressions are arithmetic operators like addition, subtraction, etc. Here are some
arithmetic operators in Python:
3. Integral Expressions: These are the kind of expressions that produce only integer results
after all computations and type conversions.
4. Floating Expressions: These are the kind of expressions which produce floating point
numbers as result after all computations and type conversions.
6. Logical Expressions: These are kinds of expressions that result in either True or False. It basically
specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal to 9. As we know it is
not correct, so it will return False. Studying logical expressions, we also come across some logical operators
which can be seen in logical expressions most often. Here are some logical operators in Python:
7. Bitwise Expressions: These are the kind of expressions in which computations
are performed at bit level.
Python Operators:
Operators are special symbols that perform some operation on
operands and returns the result. For example, 5 + 6 is an expression where
+ is an operator that performs arithmetic add operation on numeric left
operand 5 and the right side operand 6 and returns a sum of two operands
as a result.
Arithmetic Operators
Assignment Operators
Comparison Operators
Logical Operators
Identity Operators
Membership Test Operators
Bitwise Operators
Arithmetic Operators:
Arithmetic operators perform the common mathematical operation on the
numeric operands.
The arithmetic operators return the type of result depends on the type of
operands, as below.
14 | P a g e
Assume variable a holds 10 and variable b holds 20, then
Example:
a = 21
b = 10
c=0
c=a+b
print "Line 1 - Value of c is ", c
c=a–b
print "Line 2 - Value of c is ", c
c=a*b
print "Line 3 - Value of c is ", c
c=a/b
print "Line 4 - Value of c is ", c
c=a%b
print "Line 5 - Value of c is ", c
a=2
b=3
c = a**b
print "Line 6 - Value of c is ", c
a = 10
b=5
c = a//b
print "Line 7 - Value of c is ", c
Output:
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 8
Line 7 - Value of c is 2
Assignment Operators:
These operators are used to assign values to the variables.
15 | P a g e
Assume variable a holds 10 and variable b holds 20, then –
Example :
a = 21
b = 10
c=0
c=a+b
print "Line 1 - Value of c is ", c
c += a
print "Line 2 - Value of c is ", c
c *= a
print "Line 3 - Value of c is ", c
c /= a
print "Line 4 - Value of c is ", c
c = 2 c %= a
print "Line 5 - Value of c is ", c
c **= a
print "Line 6 - Value of c is ", c
c //= a
print "Line 7 - Value of c is ", c
16 | P a g e
Output:
Line 1 - Value of c is 31
Line 2 - Value of c is 52
Line 3 - Value of c is 1092
Line 4 - Value of c is 52
Line 5 - Value of c is 2
Line 6 - Value of c is 2097152
Line 7 - Value of c is 99864
Comparison Operators:
These operators compare the values on either sides of them and decide the relation among
them. They are also called Relational operators.
Example:
a = 21
b = 10
c=0
if ( a == b ):
print "Line 1 - a is equal to b"
else:
print "Line 1 - a is not equal to b"
if ( a != b ):
print "Line 2 - a is not equal to b"
else:
print "Line 2 - a is equal to b"
if ( a <> b ):
print "Line 3 - a is not equal to b"
else:
17 | P a g e
print "Line 3 - a is equal to b"
if ( a < b ):
print "Line 4 - a is less than b"
else:
print "Line 4 - a is not less than b"
if ( a > b ):
print "Line 5 - a is greater than b"
else:
print "Line 5 - a is not greater than b"
a = 5;
b = 20;
if ( a <= b ):
print "Line 6 - a is either less than or equal to b"
else:
print "Line 6 - a is neither less than nor equal to b"
if ( b >= a ):
print "Line 7 - b is either greater than or equal to b"
else:
print "Line 7 - b is neither greater than nor equal to b"
Output:
Line 1 - a is not equal to b
Line 2 - a is not equal to b
Line 3 - a is not equal to b
Line 4 - a is not less than b
Line 5 - a is greater than b
Line 6 - a is either less than or equal to b
Line 7 - b is either greater than or equal to b
Logical Operators :
The logical operators and, or and not are also referred to as boolean operators.
While and as well as or operator needs two operands, which may evaluate to true or false, not
operator needs one operand evaluating to true or false.
>>> a=50
>>> b=25
>>> a>40 and b>40
>>> a=50
>>> b=25
18 | P a g e
>>> a>40 or b>40
The not operator returns true if its operand is a false expression and returns false if it is true.
>>> a=10
>>> a>10
>>> not(a>10)
Identity Operators:
Identity operators compare the memory locations of two objects.
There are two Identity operators as explained below –
Example:
a = 20
b = 20
if ( a is b ):
print "Line 1 - a and b have same identity"
else:
print "Line 1 - a and b do not have same identity"
if ( id(a) == id(b) ):
print "Line 2 - a and b have same identity"
else:
print "Line 2 - a and b do not have same identity"
b = 30
if ( a is b ):
print "Line 3 - a and b have same identity"
else:
print "Line 3 - a and b do not have same identity"
if ( a is not b ):
print "Line 4 - a and b do not have same identity"
else:
print "Line 4 - a and b have same identity"
Output:
19 | P a g e
Line 1 - a and b have same identity
Line 2 - a and b have same identity
Line 3 - a and b do not have same identity
Line 4 - a and b do not have same identity
Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples.
There are two membership operators as explained below −
Example:
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
print "Line 1 - a is available in the given list"
else:
print "Line 1 - a is not available in the given list"
if ( b not in list ):
print "Line 2 - b is not available in the given list"
else:
print "Line 2 - b is available in the given list"
a=2
if ( a in list ):
print "Line 3 - a is available in the given list"
else:
print "Line 3 - a is not available in the given list"
Output:
Line 1 - a is not available in the given list
Line 2 - b is not available in the given list
Line 3 - a is available in the given list
20 | P a g e
Example:
a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
c=0
c = a & b; # 12 = 0000 1100
print "Line 1 - Value of c is ", c
c = a | b; # 61 = 0011 1101
print "Line 2 - Value of c is ", c
c = a ^ b; # 49 = 0011 0001
print "Line 3 - Value of c is ", c
Output:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61
Line 5 - Value of c is 240
Line 6 - Value of c is 15
21 | P a g e
Statements:
A statement is an instruction that the Python interpreter can execute. We have normally
two basic statements, the assignment statement and the print statement.
Some other kinds of statements that are if statements, while statements, and for statements
generally called as control flows.
Examples:
An assignment statement creates new variables and gives them values: x=10
expression is evaluated.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence
than +, so it first multiplies 3*2 and then adds into 7.
Example 1:
>>> 3+4*2 11
Multiplication gets evaluated before the addition operation
>>> (10+10)*2
40
Parentheses () overriding the precedence of the arithmetic operators
Example 2:
a = 20
b = 10
c = 15
d=5
e=0
e = (a + b) * c / d # (30 * 15) / 5
print("Value of (a + b) * c / d is ", e) e = ((a + b) * c) / d # (30 * 15 ) / 5
print("Value of ((a + b) * c) / d is ", e) e = (a + b) * (c / d); # (30) * (15/5)
print("Value of (a + b) * (c / d) is ", e) e = a + (b * c) / d; # 20 + (150/5)
print("Value of a + (b * c) / d is ", e)
output
Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0
Example:
result = 3 + 4 * 2 # result is 11 (multiplication has higher precedence)
22 | P a g e
Data Types:
Python Data types are the classification or categorization of data items. It represents the kind of value that
tells what operations can be performed on a particular data. The following are the standard or built-in data
types in Python:
a=5
print(type(a))
b = 5.0
print(type(b))
c = 2 + 4j
print(type(c))
Output:
<class 'int'>
<class 'float'>
<class 'complex'>
23 | P a g e
The data stored in memory can be of many types. For example, a student roll number is stored
as a numeric value and his or her address is stored as alphanumeric characters. Python has
various standard data types that are used to define the operations possible on them and the
storage method for each of them.
Int:
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
>>> print(24656354687654+2)
24656354687656
>>> print(20)
20
>>> print(0b10)
2
>>> print(0B10)
2
>>> print(0X20)
32
>>> 20
20
>>> 0b10
2
>>> a=10
24 | P a g e
>>> print(a)
10
# To verify the type of any object in Python, use the type() function:
>>> type(10)
<class 'int'>
>>> a=11
>>> print(type(a))
<class 'int'>
Float:
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals. Float can also be scientific numbers with an "e" to indicate the power of 10.
>>> y=2.8
>>> y 2.8
>>> y=2.8
>>> print(type(y))
<class 'float'>
>>> type(.4)
<class 'float'>
>>> 2.
2.0
Example:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Output:
<class 'float'>
<class 'float'>
<class 'float'>
Boolean:
Objects of Boolean type may have one of two values, True or False:
>>> type(True)
<class 'bool'>
25 | P a g e
>>> type(False)
<class 'bool'>
String:
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks. Python allows for either pairs of single or double quotes.
If you want to include either type of quote character within the string, the simplest way is to
delimit the string with the other type. If a string is to contain a single quote, delimit it with
double quotes and vice versa:
>>> print("svc is an autonomous (') college") svc is an autonomous (') college
>>> print('svc is an autonomous (") college') svc is an autonomous (") college
Specifying a backslash (\) in front of the quote character in a string “escapes” it and causes
Python to suppress its usual special meaning. It is then interpreted simply as a literal single
quote character:
The following is a table of escape sequences which cause Python to suppress the usual special
interpretation of a character in a string:
>>> print('a\ b')
ab
>>> print('a\b\c') abc
>>> print('a \n b') a b
>>> print("svc\n college") svc college
In Python (and almost all other common computer languages), a tab character can be specified
by the escape sequence \t:
26 | P a g e
>>> print("a\tb") a b
Python Lists are the most versatile compound data types. A Python list contains items
separated by commas and enclosed within square brackets ([]). To some extent, Python lists
are similar to arrays in C. One difference between them is that all the items belonging to a
Python list can be of different data type where as C array can store elements related to a
particular data type.
The values stored in a Python list can be accessed using the slice operator ([ ] and [:]) with
indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+)
sign is the list concatenation operator, and the asterisk (*) is the repetition operator. For example
list=['abcd', 786,2.23,'john',70.2]
tinylist =[123, 'john']
print (list) # Prints complete list
print (list[0])# Prints first element of the list
print (list[1:3])# Prints elements starting from 2 nd to 3rd
print (list[2:] print elements starting from 3rd element
print (tinylist * 2)# Prints list two times print (list+ tinylist) # Prints concatenated
lists
Output:
['abcd', 786, 2.23, 'john', 70.2]
abcds [786, 2.23]
[2.23, 'john', 70.2]
[123, 'john', 123, 'john']
['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Python Tuple Data Type
Python tuple is another sequence data type that is similar to a list. A Python tuple
consists of a number of values separated by commas. Unlike lists, however, tuples
are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in
brackets ( [ ] ) and their elements and size can be changed, while tuples are
enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought
of as read-only lists. For example –
27 | P a g e
print (tuple[1:3]) # Prints elements of the tuple starting from 2nd till 3rd
print (tuple[2:]) # Prints elements of the tuple starting from 3rd element
print (tinytuple * 2) # Prints the contents of the tuple twice
Output:
abcd
(786, 2.23)
Python Dictionary
Python dictionaries are kind of hash table type. They work like associative arrays
or hashes found in Perl and consist of key-value pairs. A dictionary key can be
almost any Python type, but are usually numbers or strings. Values, on the other
hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using
square braces ([]). For example
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'
print (dict['one']) # Prints value for 'one' key
28 | P a g e
{'dept': 'sales', 'code': 6734, 'name': 'john'} ['dept', 'code', 'name']
['sales', 6734, 'john']
Python dictionaries have no concept of order among elements. It is incorrect to
say that the elements are "out of order"; they are simply unordered
Indentation:
Definition: Whitespace at the beginning of a line that indicates a block of code.
Importance: Indentation is crucial in Python; it defines the scope of loops,
functions, and conditional statements.
Example
if x > 0:
print("Positive")
Comments:
Single-line Comments: Use # to comment a single line.
Example: # This is a comment
Multi-line Comments: Use triple quotes (''' or """).
Example:
29 | P a g e
Built-in Functions:
Console Input: Use input() to take user input.
Example:
name = input("Enter your name: ")
Console Output: Use print() to display output.
Example:
print("Hello, " + name)
Example:
x = "10"
y = int(x) + 5 # y is now 15
Example:
x = 20
print("x type:",type(x) y = 0.6
print("y type:",type(y)) a = x + y
print(a)
print("z type:",type(z))
Output:
x type: <class 'int'>
y type: <class 'float' >20.6
a type: <class 'float'>
30 | P a g e
Explicit Type Conversion
Example:
num_string = '12'
num_integer = 23
print("Data type of num_string before Type
Casting:",type(num_string)) # explicit type
conversion
num_string = int(num_string)
print("Data type of num_string after Type
Casting:",type(num_string)) num_sum =
num_integer + num_string
print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
Output:
Data type of num_string before
Type Casting:
<class 'str'>
Data type of num_string after Type
Casting:
<class 'int'> Sum: 35
Data type of num_sum: <class 'int'>
Python Libraries:
A Python library is a reusable chunk of code that you may want to include in our
programs/ projects.
Examples:
Pandas - This library is used for structured data operations, like
import CSV files, create dataframes, and data preparation
31 | P a g e
Numpy - This is a mathematical library. Has a powerful
N-dimensional array object, linear algebra, Fourier
transform, etc.
Matplotlib - This library is used for visualization of data.
SciPy - This library has linear algebra modules
Importing Libraries:
We can import and use modules across different programs using keyword import.
Modules in the Python standard library need no installing and therefore importing them at the
top of our programs is enough to get started. A common example of such libraries is the math
library. The math library provides access to common mathematical functions. Using these
functions, we can perform various mathematical expressions such as finding the square root
of a number.
Using the keywords from…import we can import specific items from a library or module.
These may include functions or classes within that specific library. This is important
especially when you do not intend to use only a specific function in a module and therefore it
is needless to import the entire module.
Example:
1) # import standard math module import math
# use [Link] to get value of pi print("The value of pi is", [Link])
Output:
The value of pi is 3.141592653589793
Output:
3.141592653589793
32 | P a g e
1. if-else Statements
if statement: Executes a block of code if a condition is true.
else statement: Executes a block of code if the if condition is false.
elif statement: Allows for multiple conditions to be checked.
Example:
x = 10
if x > 0:
print("Positive") elif x < 0:
print("Negative") else:
print("Zero")
1. while Loop
Executes a block of code as long as a condition is true.
Can be used to implement various types of loops, such as counting
loops, infinite loops, and nested loops.
Loops are either infinite or conditional. Python while loop keeps
reiterating a block of code defined inside it until the desired condition
is met.
The while loop contains a boolean expression and the code inside
the loop is repeatedly executed as long as the boolean expression is
true.
The statements that are executed inside while can be a single line of code or
a block of multiple statements
33 | P a g e
Syntax:
while(expression):
Statement(s)
Flowchart
Example:
count = 0
while count < 5:
print(count)
count += 1
1. break Statement
Terminates the current loop and transfers execution to the statement immediately
following the loop.
Example:
while True:
user_input = input("Enter a number (or 'q' to quit): ") if user_input == 'q':
break
print("You entered:", user_input)
2. continue Statement
Skips the current iteration of the loop and moves to the next iteration.
Example:
for i in range(1, 11): if i % 2 == 0:
continue print(i)
34 | P a g e
[Link] Loop
Iterates over the elements of a sequence (such as a list, tuple, or string).
Can be used to implement various types of loops, such as counting
loops, iterating over collections, and nested loops.
Example:
fruits = ["apple",
"banana", "cherry"]
for fruit in fruits:
print(fruit)
Flowchart:
range() Function
35 | P a g e
for i in range(1,5):
#
range(start,upto)
print(i) #
Output: 1, 2,
3,4
Terminates the Python program and returns control to the operating system.
Example:
if user_input == 'q': # if user input is q then
terminate the execution. exit()
Arrays in Python
Definition of Array
An array is a data structure that stores multiple values of the same data type in a single
variable. Each value is stored at a specific index position.
Syntax
array_name = [element1, element2, element3, ...]
Example
numbers = [10, 20, 30, 40, 50]
36 | P a g e
• Index starts from 0
• Negative indexing starts from -1
print(numbers[0]) #output: 10
print(numbers[2]) #output:30
print(numbers[-1]) #output: 50
Slicing
numbers[1] = 25
append()
Adds an element at the end.
[Link](60)
insert()
Adds an element at a specified index. [Link](2, 15)
remove()
Removes a specific element. [Link](40)
pop()
Removes and returns element at given index.
[Link]() # Removes last element
[Link](1) # Removes element at index 1
index()
Returns index of an element. [Link](30)
count()
Counts occurrences of an element.
[Link](20)
37 | P a g e
sort()
Sorts the array in ascending order.
[Link]()
reverse()
Reverses the array.
[Link]()
clear()
Removes all elements.
[Link]()
Syntax
import array
i Integer
f Float
d Double
Accessing Elements
print(arr[1])
# Output: 20
Advantages of Arrays
Disadvantages of Arrays
38 | P a g e
Fixed size (in array module)
Stores only same data type
Insertion and deletion can be slow
39 | P a g e