0% found this document useful (0 votes)
10 views60 pages

Python Unit II

Uploaded by

shubashunmugam
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)
10 views60 pages

Python Unit II

Uploaded by

shubashunmugam
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/ 60

UNIT II

Python
UNIT II DATA TYPES, CONTROL FLOW & ITERATION

Built-in data types: int, float, bool, str. Type conversion and
casting. Input/output functions. Conditional Statements: if,
if-else, if-elif-else.Loops: for, while, nested loops. Loop
control: break, continue, pass, else with loop
PYTHON DATA TYPES
Variables can store data of different types, and different types can do different
things.

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.
NUMERIC DATA TYPES IN PYTHON

The numeric data type in Python represents the data that has a numeric value.
A numeric value can be an integer, a floating number, or even a complex
number.

Integers - This value is represented by int class. It contains positive or


negative whole numbers (without fractions or decimals). In Python, there
is no limit to how long an integer value can be.

age = 5
Float - This value is represented by the float class. It is a real number with
a floating-point representation. It is specified by a decimal point.
Optionally, the character e or E followed by a positive or negative integer
may be appended to specify scientific notation.

height = 5.0

Complex Numbers - A complex number is represented by a complex class.


It is specified as (real part) + (imaginary part)j . For example - 2+3j

c = 2 + 4j
SEQUENCE DATA TYPES IN PYTHON

The sequence Data Type in Python is the ordered collection of similar or


different Python data types. Sequences allow storing of multiple values in an
organized and efficient fashion.

String Data Type- Python Strings are arrays of bytes representing Unicode
characters. In Python, there is no character data type Python, a character
is a string of length one. It is represented by str class.
Strings in Python can be created using single quotes, double quotes or
even triple quotes. We can access individual characters of a String using
index

s = 'Welcome to the CS With AI'


SEQUENCE DATA TYPES IN PYTHON
Indexing in Python Strings
Indexing starts from 0 (for the first character).
Negative indexing is also allowed (last character = -1)

print(s[0]) # Empty list


a = []
Lists are just like arrays, declared in # list with int values
other languages which is an ordered a = [1, 2, 3]
collection of data. It is very flexible as print(a)
the items in a list do not need to be of
the same type. # list with mixed int and string
b = ["Geeks", "For", "Geeks", 4, 5]
print(b)
SEQUENCE DATA TYPES IN PYTHON
Indexing in Python Strings
Indexing starts from 0 (for the first character).
Negative indexing is also allowed (last character = -1)

print(s[0]) # Empty list


a = []
Lists are just like arrays, declared in # list with int values
other languages which is an ordered a = [1, 2, 3]
collection of data. It is very flexible as print(a)
the items in a list do not need to be of
the same type. # list with mixed int and string
b = ["Geeks", "For", "Geeks", 4, 5]
print(b)
SEQUENCE DATA TYPES IN PYTHON
Access List Items
In order to access the list items refer to the index number. In Python,
negative sequence indexes represent positions from the end of the
array.
a = ["Geeks", "For", "Geeks"]
print("Accessing element from the list")
print(a[0])
print(a[2])

print("Accessing element using negative


indexing")
print(a[-1])
print(a[-3])
SEQUENCE DATA TYPES IN PYTHON
Access List Items
In order to access the list items refer to the index number. In Python,
negative sequence indexes represent positions from the end of the
array.
a = ["Geeks", "For", "Geeks"]
Index starts from 0 for the
print("Accessing element from the list")
first element. print(a[0])
print(a[2])

print("Accessing element using negative


indexing")
print(a[-1])
print(a[-3])
SEQUENCE DATA TYPES IN PYTHON
Tuple Data Type
Just like a list, a tuple is also an ordered collection of Python objects.
The only difference between a tuple and a list is that tuples are
immutable. Tuples cannot be modified after it is created.
In Python Data Types, tuples are created by placing a sequence of values
separated by a ‘comma’ with or without the use of parentheses for
grouping the data sequence. Tuples can contain any number of elements
and of any datatype (like strings, integers, lists, etc.).

tup1 = ()

tup2 = ('Geeks', 'For')


SEQUENCE DATA TYPES IN PYTHON
Access Tuple Items
In order to access the tuple items refer to the index number. Use the
index operator [ ] to access an item in a tuple.

Index starts from 0 for the


first element.

tup1 = tuple([1, 2, 3, 4, 5])

# access tuple items


print(tup1[0])
BOOLEAN DATA TYPE IN PYTHON

Python Data type with one of the two built-in values, True or False.
Boolean objects that are equal to True are truthy (true), and those
equal to False are falsy (false).

It is mainly used for decision-making and logical operations.

print(5 == 5)

True
SET DATA TYPE IN PYTHON

In Python Data Types, Set is an unordered collection of data types


that is iterable, mutable, and has no duplicate elements. The order of
elements in a set is undefined though it may consist of various
elements.
Create a Set in Python

s1 = set()

s1 = set("GeeksForGeeks")
print("Set with the use of String: ", s1)
DICTIONARY DATA TYPE
A dictionary in Python is a collection of data values, used to store data
values like a map, unlike other Python Data Types that hold only a
single value as an element, a Dictionary holds a key: value pair. Key-
value is provided in the dictionary to make it more optimized. Each
key-value pair in a Dictionary is separated by a colon : , whereas each
key is separated by a ‘comma’.

Create a Set in Python


# Accessing an element using key
s1 = dict() print(d['name'])

d = {1: 'Geeks', 2: 'For', 3: 'Geeks'} # Accessing a element using get


print(d) print(d.get(3))
GETTING THE DATA TYPE

You can get the data type of any object by using the type() function:

print(type(age))

<class 'int'>

SETTING THE DATA TYPE

In Python, the data type is set when you assign a value to a variable:

Age=22
x = str("Hello World")
str
x = int(20)
int
x = float(20.5)
float
x = complex(1j)
complex
x = list(("apple", "banana", "cherry"))
list
x = tuple(("apple", "banana", "cherry"))
tuple
x = dict(name="John", age=36)
dict
x = set(("apple", "banana", "cherry"))
set
x = bool(5)
bool
TYPE CONVERSION AND CASTING IN PYTHON

Type conversion is the process of converting one data type into another.
In Python, there are two types of type conversion:
1.Implicit Type Conversion (Type Casting by Python itself)
2.Explicit Type Conversion (Manual Casting by the Programmer)
IMPLICIT TYPE CONVERSION (TYPE CASTING BY PYTHON)

Definition:
Also called Type Promotion. Python automatically converts one data type to another
without loss of data, to avoid errors.
👉 Happens internally when we mix different data types in an expression.
x=5 # int
y = 2.5 # float

z = x + y # int + float → result becomes float


print(z) # 7.5
print(type(z)) # <class 'float'>

Python automatically converted int → float.


EXPLICIT TYPE CONVERSION (TYPE CASTING BY PROGRAMMER)

📌 Definition:
When we manually convert one data type into another using built-in
functions, it is called type casting or explicit conversion.
📌 Common Casting Functions:
int() → Converts to integer
float() → Converts to float
str() → Converts to string
list() → Converts to list
tuple() → Converts to tuple
set() → Converts to set
EXPLICIT TYPE CONVERSION (TYPE CASTING BY PROGRAMMER)

Example 1: int()
a = "100"
b = int(a) # string → integerprint(b + 50) # 150
Example 2: float()
x = "3.14"
y = float(x) # string → floatprint(y * 2) # 6.28
Example 3: str()
n = 25
s = str(n) # integer → stringprint("Age is " + s)
INPUT AND OUTPUT IN PYTHON
Taking input in Python
Python's input() function is used to take user input. By default, it
returns the user input in form of a string.
name = input("Enter your name: ")
print("Hello,", name, "! Welcome!")

Printing Output using print()


This function allows us to display text, variables and expressions on
the console.
print("Hello, World!")
INDENTATION IN PYTHON

👉 Indentation means spaces at the beginning of a line of code.


Python does not use {} or keywords like begin/end to mark
code blocks.
Instead, it uses indentation (spaces or tabs) to group
statements.
If indentation is not correct, Python will throw an
IndentationError.

it defines the structure of the code.


CONDITIONAL STATEMENTS: IF, IF-
ELSE, IF-ELIF-ELSE.
CONDITIONAL STATEMENTS

Conditional statements are used to make decisions in a program


based on conditions (True/False).
python supports the usual logical conditions

Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
CONDITIONAL STATEMENTS
if
if else
Nested if
if elif statement
An "if statement" is written by using the if keyword

if Statement in Python

If the simple code of block is to be performed if the condition holds


true then the if statement is used.

Syntax

if condition:
# Statements to execute if condition is true
CONDITIONAL STATEMENTS
Flow Chart

num = int(input("Enter a number: "))

if num % 2 == 0:
print("Even")
if num % 2 != 0:
print("Odd")

Each condition is checked independently.


CONDITIONAL STATEMENTS

if else Statement in Python

In conditional if Statement the additional block of code is merged as


else statement which is performed when if condition is false.

Syntax

if (condition):
# Executes this block if condition is true
else:
# Executes this block if condition is false
CONDITIONAL STATEMENTS
Flow Chart

if (year % 400 == 0) or (year % 100 != 0 and year % 4 == 0):


print("Leap Year")
else:
print("Not a Leap Year")

Leap Year Rules (from calendar system)


A year is a leap year if:

Divisible by 400 Leap year.

Else if divisible by 4 but not 100 Leap year.

Otherwise Not a leap year.
.
CONDITIONAL STATEMENTS

Step 1: Divisible by 4 Add Leap Year
Every 4 years, 0.242 × 4 ≈ 1 day.
So we add Feb 29 every 4 years.


Step 2: Divisible by 100 Remove Leap Year
But 0.242 is not exactly 0.25, so adding a day every 4 years is a bit too much.
After 100 years, the extra adds up to about 24 days too many.

To fix this, we say: If year % 100 == 0 Not a leap year.

Step 3: Divisible by 400 Add Leap Year Back
But if we always remove at 100, we end up removing too many leap days.
After 400 years, the calendar drifts too far the other way.

To fix this: If year % 400 == 0 It is a leap year.
CONDITIONAL STATEMENTS

Nested if Statement

if statement can also be checked inside other if statement. This


conditional statement is called a nested if statement.

Syntax

if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
CONDITIONAL STATEMENTS
Flow Chart
CONDITIONAL STATEMENTS
Flow Chart

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
if a > b:
if a > c:
print("a is largest")
else:
print("c is largest")
else:
if b > c:
print("b is largest")
else:
print("c is largest")
CONDITIONAL STATEMENTS

if-elif Statement in Python

The if-elif statement is shortcut of if..else chain. While using if-elif


statement at the end else block is added which is performed if none of
the above if-elif statement is true.
Syntax

if (condition):
statement
elif (condition):
statement
else:
statement
CONDITIONAL STATEMENTS
Flow Chart
CONDITIONAL STATEMENTS
Flow Chart

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

if a >= b and a >= c:


print("Largest is:", a)
elif b >= a and b >= c:
print("Largest is:", b)
else:
print("Largest is:", c)
LOOPS
LOOPS
A loop is a control structure in Python that allows us to repeat a block
of code multiple times without writing it again and again.
Instead of writing the same statement many times, we use loops to
make the program shorter, cleaner, and more efficient.

Types of Loops in Python


For Loop

A for loop is used for iterating over a sequence (that is either a list,
a tuple, a dictionary, a set, or a string).
With the for loop we can execute a set of statements, once for each
item in a list, tuple, set etc.
The for loop is used when we know exactly how many times we
want to repeat an action.

Syntax

for iterator_var in sequence:


statements(s)
FOR LOOP
Flow Chart
FOR LOOP
Example
for x in "banana":
print(x)

Iterable

students = ["Arun", "Priya", "Sam", "Neha"]

Iteration
for name in students:
print("Welcome,", name)

Iterator
RANGE ()

The range() function generates a sequence of numbers, starting from 0 by


default, and increments by 1 (by default), and stops before a specified
number.

Optional. An integer number


Syntax
start specifying at which position to
start. Default is 0
range(start, stop, step)
Required. An integer number
stop specifying at which position to
stop (not included).

Optional. An integer number


step specifying the incrementation.
Default is 1
RANGE ()
Example

x = range(3, 6)
for n in x:
print(n)

Why do we use it?

To repeat tasks a fixed number of times


for i in range(5):
To generate sequences of numbers print("Hello")

To control increments (steps) for i in range(2, 11, 2):


print(i)
To loop backwards for i in range(5, 0, -1):
print(i)
WHILE LOOP
The while loop is used when we don’t know the number of
iterations in advance.
It continues to run as long as the condition is True.

Definition:
👉 A while loop in Python repeatedly executes a block of code as long
as the given condition evaluates to True.

Syntax

while condition: condition → An expression that results in either


# body of while loop True or False.

If True run the code block.

If False stop the loop.
WHILE LOOP
The while loop is used when we don’t know the number of
iterations in advance.
It continues to run as long as the condition is True.

Definition:
👉 A while loop in Python repeatedly executes a block of code as long
as the given condition evaluates to True.

Syntax

while condition: condition → An expression that results in either


# body of while loop True or False.

If True run the code block.

If False stop the loop.
WHILE LOOP
Flow Chart
WHILE LOOP
Example
Initialization
i=1
Condition while i <= 5:
print(i)
i += 1 Statement

Keep asking until correct password

password = ""
while password != "python123":
password = input("Enter password: ")

print("Access granted ✅")


WHILE LOOP
Example

Infinite While Loop

while True:
print("This will run forever! ❌")
If the condition never becomes False, the loop runs forever.
WHILE LOOP
Example

Infinite While Loop

while True:
print("This will run forever! ❌")
If the condition never becomes False, the loop runs forever.
NESTED LOOP
A nested loop means having one loop inside another loop.
The outer loop runs first.
For each iteration of the outer loop, the inner loop runs completely.
👉 In short: Inner loop runs fully for every single step of outer
loop.

Syntax

for outer_variable in outer_sequence:


for inner_variable in inner_sequence:
NESTED LOOP
Flow Chart
NESTED LOOP
NESTED LOOP
for i in range(1, 6): →
# Outer loop rows for i in range(2, 4): # Outer loop

for j in range(i): # Inner loop columns for j in range(1, 6): # Inner loop
print("*", end=" ") print(i, "x", j, "=", i * j)
print() 2x1=2 print("-----")
2x2=4
* 2x3=6
** 2x4=8
*** 2 x 5 = 10
**** -----
***** 3x1=3
3x2=6
3x3=9
3 x 4 = 12
3 x 5 = 15
-----
LOOPS CONTROLS
LOOP CONTROL
When we use loops (for or while), sometimes we don’t want the
loop to run normally from start to end.
We may want to:
Exit early (stop loop immediately),
Skip one particular iteration, or
Do nothing temporarily.

👉 In such cases, loop control statements are used to change the normal flow
of the loop.
LOOP CONTROL
Break Statement
Definition:
The break statement is used to exit the loop immediately, regardless of the
loop condition or sequence. Once break is executed, the loop terminates and
control moves to the first statement after the loop.

How it works:

Encounter break stop the loop completely.
Useful when we have found what we were searching for.

for i in range(1, 10): 1


if i == 5: 2
break 3
print(i) 4
LOOP CONTROL
Continue Statement
The continue statement is used to skip the current iteration of a loop and jump
directly to the next iteration. The loop itself does not end.

How it works:
When continue is encountered, Python skips the remaining statements of
that iteration and goes back to check the loop condition for the next cycle.

for i in range(1, 6): 1


if i == 3: 2
continue 4
print(i) 5
LOOP CONTROL
Pass Statement
The pass statement in Python does nothing. It is simply a null operation. It is
used as a placeholder where syntactically some code is required but logically
we don’t want to execute anything yet.

How it works:
When Python encounters pass, it just ignores it and moves on.
Helps in writing the structure of code first and filling logic later.

for i in range(5):
0
if i == 3:
1
pass #
2
placeholder, does
3
nothing
4
print(i)
LOOP CONTROL

Control Statement Meaning Use Case

Exits the loop Stop searching once


break
immediately found

Skip absentees, skip


continue Skips current iteration
errors

Does nothing When writing code


pass
(placeholder) structure

You might also like