0% found this document useful (0 votes)
2 views17 pages

Python Unit II

The document outlines the fundamentals of Python programming, focusing on control structures including sequential, selection, and iterative controls. It details Boolean expressions, operators, and various control statements such as if, if-else, and loops, along with their syntax and examples. Additionally, it covers data types like strings and lists, their operations, and the importance of indentation in Python code.

Uploaded by

suganya.d
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)
2 views17 pages

Python Unit II

The document outlines the fundamentals of Python programming, focusing on control structures including sequential, selection, and iterative controls. It details Boolean expressions, operators, and various control statements such as if, if-else, and loops, along with their syntax and examples. Additionally, it covers data types like strings and lists, their operations, and the importance of indentation in Python code.

Uploaded by

suganya.d
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

Department of Computer Science

ELECTIVE - I: PYTHON PROGRAMMING AND LAB


Unit – I
Control Structures: Boolean Expressions - Selection Control - If Statement-
Indentation in Python- Multi-Way Selection -- Iterative Control- While Statement-
Infinite loops- Definite vs. Indefinite Loops- Boolean Flag. String, List and Dictionary,
Manipulations Building blocks of python programs, Understanding and using ranges.
xc dcss

Control Structures
 A control statement is a statement that determines the control flow of a set of
instructions.
 There are three fundamentals forms of control. They are.
1. Sequential control
2. Selection control
3. Iterative control
 Collectively a set of instruction and the control statement controlling their
execution is called control structure.

1. Sequential control
 Sequential control refers to the default mode of execution where the program’s
statement are executed one after the other in order they appear in the code.
 Each instruction is processed line by line and it is also referred to as ‘straight-line
program’
2. Selection control
 Selection control allows a program to choose between different paths of
execution based on certain condition.
 The program evaluates one or more condition and selects a block of code to
execute based on whether the condition is true or false
3. Iterative control
 Iterative control statement is a control statement providing the repeated
execution of a set of instruction.
 An iterative control structure is a set of instruction and the iterative control
statement controlling their execution.
 Iterative control structures are commonly referred as ‘loops’.
Department of Computer Science

Boolean Expressions (Conditions)


 A Boolean expression is an expression that produces either ‘True’ or ‘False’
value after evaluate the expression.
 The Boolean expression may have any combination of valid arithmetic, relational
and logical expression.
 The value ‘True and ‘false is called Boolean value.
 The Boolean expression is used in selection and iterative control as condition.
1. Boolean Operators
 The Boolean operator are used to combine relational expression and
negate the result of the expression.
 The Boolean oprator ‘and’ and ‘or’ are used to combine the result of
expression and ‘not’ operator is used to negate the result.

2. Relational Operators
 The relational operators in Python perform the usual comparison
operations.
 The comparison operator , ‘==’ for determining if two values are equal.
Ex)
>>> 5 == 5
True
>>> 5 == 6
False
Department of Computer Science

Selection control
Selection control structures in programming allow you to make decisions based
on conditions. In Python, these control structures help you execute different blocks of
code depending on whether certain conditions are met. The primary types of selection
control structures in Python are:
1. If statement
The if statement executes a block of code if a specified is true. An if statement
is a selection control statement based on the value of a given Boolean expression.

Syntax)
if condition :
statement
Ex)
x = 10

if x > 5:
print("x is greater than 5"

2. If-else statement
The if-else statement allows you to execute one block of code if the condition is true
and another block of code if the condition is false. Statements that contain other
statements are referred to as a compound statement.

Syntax)
if condition :
statement
else:
statement
Ex)
x = 10

if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")

3. Multi-Way Selection Statement


The two means of constructing multi-way selection in Python—one involving
multiple nested if statements, and the other involving a single if statement and the use
of elif headers.
Department of Computer Science

I. Nested if Statements
There are often times when selection among more than two sets of
statements (suites) is needed. You can nest if statements inside other if statements
to check multiple

Syntax)
if condition :
statement
else:
if condition:
statement
else:
if condition:
statement
Ex)
if score >= 90:
print("Grade: A")
else:
if score >=80:
print("Grade: B")
else:
if score >=70:
print("Grade: C")
else:
print (“Grade: D”)

II. If-elif-else statement


The if-elif-else statement extends the if-else structure to allow multiple conditions
to be checked sequentially. If statements may contain only one else header. Thus,
if-else statements must be nested to achieve multi-way selection. Python,
however, has another header called elif (“else-if”) that provides multi-way selection
in a single if statement.

Syntax)
if condition :
statement
elif:
statement
elif:
statement
else:
statement
Department of Computer Science

Ex)
if score >= 90:
print("Grade: A")
elif score >=80:
print("Grade: B")
elif score >=70:
print("Grade: C")
else:
print (“Grade: D”)
Indentation in Python
Indentation in Python is crucial because it defines the structure and flow of the code.
Python relies on consistent indentation to indicate blocks. A header in Python starts
with a keyword and ends with a colon. The group of statements following a header is
called a suite. A header and its associated suite are together referred to as a clause.

Key points about indentation in Python:


1. Indentation Level: Indentation is typically done with four spaces per level. However, you
can use a different number of spaces or tabs, but you should be consistent throughout your
code. Mixing tabs and spaces can lead to errors.
2. Defining Blocks: Indentation defines the scope of loops, conditionals, functions, and
classes.
3. Indentation Errors: Python will raise an Indentation Error if there is an inconsistency in
indentation.
4. Choosing Between Spaces and Tabs: PEP 8, the Python style guide, recommends using 4
spaces per indentation level. If you use tabs, be consistent, but mixing spaces and tabs is
generally discouraged.
5. Automatic Indentation: Most modern IDEs and text editors automatically handle
indentation for you. They can also convert tabs to spaces and vice versa.

Iterative Control
An iterative control statement typically refers to structures in programming that allow a
block of code to be executed repeatedly based on certain conditions. In Python,
common iterative control statements include for and while loops. Here’s a brief
overview of each:

1. for loop
The for loop is generally used when the number of iteration is known as when iterating
over a sequence.

Syntax)
for variable in sequence:
statement
Department of Computer Science

Ex)
Number = [1,2,3,4,5]
for num in number:
Print(num)

2. While loop
A while statement is an iterative control statement that repeatedly executes a set of
statements based on a provided Boolean expression (condition). All iterative control
needed in a program can be achieved by use of the while statement.

Syntax)
while condition:
statement
Ex)
count = 0
while count<5:
print(count)
count+=1

3. Nested loop
A nested loop is a loop which exists as a part of the suite of outer loop. The
nested loop is structured as the nested if statement.

Syntax)
for variable in sequence
for variable in sequence
suite inner loop
suite outer loop
Example)
n=5
for i in range (n):
for j in range(i+1):
print(‘*’, end=’ ‘)
print()
4.a) BREAK
Break statements can alter the flow of a loop.
It terminates the current
loop and executes the remaining statement outside the loop.
If the loop has else statement, that will also gets terminated and come out of the loop
completely.

Syntax)
For variable in sequence
If condition:
Break:
Statement
Department of Computer Science

Ex)
for i in "welcome":
if(i=="c"):
break
print(i)

b) CONTINUE
It terminates the current iteration and transfer the control to the next iteration in the
loop.

Syntax)
For variable in sequence
If condition:
continue
Statement
Ex)
for i in "welcome":
if(i=="c"):
continue
print(i)

Definite vs. Indefinite Loops


Definite and indefinite loops are two fundamental concepts in programming that control how
many times a block of code executes.

Definite Loops
A defi nite loop is a program loop in which the number of times the loop will iterate can be
determined before the loop is executed.
Ex)
numbers = [1, 2, 3, 4, 5]
sum_total = 0

for number in numbers


sum_total += number

print('The sum is:', sum_total)

Indefinite Loops

An indefinite loop is a program loop in which the number of times that the loop will iterate
cannot be determined before the loop is executed.
Ex)
which = input("Enter selection: ")
while which != 'F' and which != 'C':
which = input("Please enter 'F' or 'C': ")
print("You selected:", which)
Department of Computer Science

Sequence:
 A sequence is an ordered collection of items, indexed by positive integers.
 It is a combination of mutable (value can be changed) and immutable (values
cannot be changed) datatypes.
 There are three types of sequence data type available in Python, they are
Strings
Lists
Tuples
Mutable Immutable
Data type whose values can Data types whose values can’t
be changed after creation. be changed or altered.
Retains the same memory Any modification results in a new
location even after the content object and new memory location
is modified.
List, Dictionaries, Set are Strings, Types, Integer are
mutable immutable
It is memory-efficient, as no It might be faster in some
new objects are created for scenarios as there’s no need to
frequent changes. track changes.
Not inherently thread-safe. They are inherently thread-safe
Concurrent modification can due to their unchangeable
lead to unpredictable results. nature.
When you need to modify, When you want to ensure data
add, or remove existing data remains consistent and
frequently. unaltered.

Strings:
 A String in Python consists of a series or sequence of characters - letters,
numbers, and special characters.
 Strings are marked by quotes:
Single quotes(' ')
E.g., 'This a string in single quotes'
double quotes(" ")
E.g., "'This a string in double quotes'"
triple quotes(""" """)
E.g., """This is a paragraph. It is made up of multiple lines and
sentences."""
 Individual character in a string is accessed using a subscript(index).
 Characters can be accessed using indexing and slicing operations .Strings are
 Immutable i.e the contents of the string cannot be changed after it is created.
Department of Computer Science

Method Description Examples


Capitalize() It is used to capitalize the s=”university”
first letter of the string and cap_str = [Link]()
returns the capitalize
string. The remaining output
characters are unchanged. University
It does not take any
parameter.
Lower() It converts all character of s=”university”
the string into lower case conv_str = [Link]()
letter and return the
converted string. output
university
Upper() It converts all characters of s=”university”
the string into upper case conv_str = [Link]()
letters and returns the
converted string. output
UNIVERSITY
Title() It is used to converts first s=”good morning”
character of all words into conv_str = [Link]()
uppercase and returns the
converted strings. output
Good Morning
Swapcase() It is used to flip the s=”good morning”
character case from conv_str = [Link] ()
lowercase to uppercase
and vice versa output
gOOD mORNING

Operations on string:
 Indexing - Indexing allows you to access individual characters in a string directly
by using a numeric value.
 Slicing - String slicing in Python allows you to extract a portion of a string by
specifying a start and end index.
 Concatenation - Concatenation is the process of appending one string to the
end of another string.
 Repetitions - The multiplication operator (*) is used to repeat a string a specified
number of times.
 Membership - The membership operator determines whether a value is present
or absent in a data sequence.
Department of Computer Science

Creating a string >>> s="good morning" Creating the string with


elements of different
data types.
Indexing >>>print(s[2])  Accessing the item
o in the Position 2
>>>print(s[6])  Accessing the item
O in the Position 6
Slicing( ending position -1) >>>print(s[2:]) - Displaying items from
od morning 2ndtill
last.
Slice operator is used >>>print(s[:4]) - Displaying items from 1
to extract part of a Good st
data position till 3rd.
type
Concatenation >>>print(s+"friends") -Adding and printing the
good morning friends characters of two strings
Repetition >>>print(s*2) Creates new strings,
good morning concatenating multiple
good morning copies of
the same string
in, not in (membership >>> s="good morning" Using membership
operator) >>>"m" in s True operators to check a
>>> "a" not in s False particular character is in
string or not.
Returns true if present.
Department of Computer Science

Lists
 List is an ordered sequence of items. Values in the list are called elements
/items.
 It can be written as a list of comma-separated items (values) between square
brackets [].
 Items in the lists can be of different datatypes.

Operations on list:
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Updation, Insertion, Deletion

Creating a list >>>list1=[“python”,7.79,101,”hello”] Creating the list


>>>list2=[“god”,6.789] with elements of
different
data types.
Indexing >>>print(list1[0]) python  Accessing the
>>>list1[2] item in the
101 position0
 Accessing the
item in the
position2
Slicing( ending >>>print(list1[1:3]) - Displaying items
position -1) [7.79, 101] from 1st till 2nd.
Slice operator is >>>print(list1[1:]) [7.79, 101, - Displaying item from
used to extract part 'hello'] 1st position till last.
of a string, or some
part of a list Python
Concatenation >>>print( list1+list2) -Adding and printing
['python', 7.79, 101, 'hello', 'god' , 6.78, the items of two lists.
9]
Repetition >>>list2*3 Creates new strings,
['god', 6.78, 9, 'god', 6.78, 9, 'god', concatenating
6.78, 9] Multiple copies of the
same string
Updating the list >>>list1[2]=45 Updating the list
>>>print( list1) using index value
[‘python’, 7.79, 45, ‘hello’]
Inserting an element >>>[Link](2,"program") Inserting an element
>>> print(list1) in 2ndposition
['python', 7.79, 'program', 45,
'hello']
Removing an >>>[Link](45) Removing an element
element >>> print(list1) by giving the element
['python', 7.79, 'program', 'hello'] directly
Department of Computer Science

Tuple:

 A tuple is same as list, except that the set of elements is enclosed in


parentheses instead of square brackets.
 A tuple is an immutable list i.e. once a tuple has been created, you can't add
elements to a tuple or remove elements from the tuple.
 Altering the tuple data type leads to error. Following error occurs when user tries
to do.

Benefit of Tuple:

 Tuples are faster than lists.


 If the user wants to protect the data from accidental changes, tuple can be used.
 Tuples can be used as keys in dictionaries, while lists can't.

Creating a tuple >>>t=("python", 7.79, Creating a tuple with


101, "hello”) elements of different
datatype
Indexing >>>print(t[0])  Accessing the item
python in the position0
>>>t[2]  Accessing the item
101 in the position2
Slicing( ending >>>print(t[1:3]) - Displaying items from1st
position -1) (7.79, 101) till2nd.
Concatenation >>>t+("ram", 67) Adding tuple elements at
('python', 7.79, 101, 'hello', the end of another tuple
'ram', elements
67)
Repetition >>>print(t*2) Creates new strings,
('python', 7.79, 101, 'hello', concatenating multiple
'python', 7.79, 101, 'hello') copies of the same string

Mapping

- This data type is unordered and mutable.


- Dictionaries fall under Mappings.
Department of Computer Science

Dictionaries:
 Lists are ordered sets of objects, whereas dictionaries are un ordered sets.
 Dictionary is created by using curly brackets. i,e.{}
 Dictionaries are accessed via keys and not via their position.
 A dictionary is an associative array (also known as hashes). Any key of the
dictionary is associated (or mapped) to a value.
 The values of a dictionary can be any Python data type. So dictionaries are
unordered key-value pairs
 The association of a key and a value is called a key- value pair)
 Dictionaries don't support the sequence operation of the sequence data types
like strings, tuples and lists.

Creating a >>> food = {"ham":"yes", Creating a dictionary with


dictionary "egg" :"yes", "rate":450 } Elements of different
>>>print(food) types
{'rate': 450, 'egg': 'yes', 'ham':
'yes'}
Indexing >>>print(food[“rate”]) Accessing the item with the
450 keys
Department of Computer Science
Department of Computer Science
Department of Computer Science
Department of Computer Science

You might also like