0% found this document useful (0 votes)
99 views

Dept & Sem: Subject Name: Course Code: Unit: Prepared by

This document provides an overview of Python programming concepts related to strings and iteration. It discusses reassignment, updating variables, while loops, break statements, string slicing, and string traversal using for loops. The key points covered are: 1) Strings in Python are sequences that can be accessed using indexes and sliced to extract substrings. Strings are immutable, so their values cannot be altered. 2) Loops like while and for are used for iteration, allowing code blocks to be repeated. The break statement can be used to exit a loop early. 3) Variables can be reassigned new values, but updating a variable relies on the variable first being initialized. Increment and decrement are common ways to update numeric variables
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
99 views

Dept & Sem: Subject Name: Course Code: Unit: Prepared by

This document provides an overview of Python programming concepts related to strings and iteration. It discusses reassignment, updating variables, while loops, break statements, string slicing, and string traversal using for loops. The key points covered are: 1) Strings in Python are sequences that can be accessed using indexes and sliced to extract substrings. Strings are immutable, so their values cannot be altered. 2) Loops like while and for are used for iteration, allowing code blocks to be repeated. The break statement can be used to exit a loop early. 3) Variables can be reassigned new values, but updating a variable relies on the variable first being initialized. Increment and decrement are common ways to update numeric variables
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 75

DEPT & SEM : CSE & I SEM

SUBJECT NAME PYTHON PROGRAMMING


:
PP
COURSE CODE
: III

UNIT : S SRINIVASULU & R SWATHI

PREPARED BY :

COURSE: Python UNIT: 3 Pg. 1


Part A:Iteration

• Reassignment

• Updating variables

• The while statement

• Break

• Square roots

• Algorithms.

COURSE: Python UNIT: 3 Pg. 2


Reassignment

 Iteration, which is the ability to run a block of statements repeatedly. We saw a kind
of iteration, using recursion.

Reassignment:-

 A new assignment makes an existing variable refer to a new value (and stop
referring to the old value).
>>> x = 5
>>> x
5
>>> x = 7
>>> x
7

The first time we display x, its value is 5; the second time, its value is 7.

COURSE: Python UNIT: 3 Pg. 3


Reassignment

 In Python, an assignment statement can make two variables equal, but they don’t
have to stay that way:
>>> a = 5
>>> b = a # a and b are now equal
>>> a = 3 # a and b are no longer equal
>>> b
5

 The third line changes the value of a but does not change the value of b, so they
are no longer equal.

COURSE: Python UNIT: 3 Pg. 4


Reassignment

 Reassigning variables is often useful, but you should use it with caution. If the values
of variables change frequently, it can make the code difficult to read and debug.

Figure :State diagram.

COURSE: Python UNIT: 3 Pg. 5


Updating Variables

 A common kind of reassignment is an update, where the new value of the variable
depends on the old.

>>> x = x + 1

 This means “get the current value of x, add one, and then update x with the new
value.

 If you try to update a variable that doesn’t exist, you get an error, because Python
evaluates the right side before it assigns a value to x:

COURSE: Python UNIT: 3 Pg. 6


Python break Keyword

 The break keyword is used to break out a for loop, or a while loop.

Ex:for i in range(9):
   if i > 3:
     break
  print(i)

Ex: str = "python"  
for i in str:  
  if i == 'o':  
   break  
print(i); 

COURSE: Python UNIT: 3 Pg. 7


Python break Keyword

>>> x = x + 1

NameError: name 'x' is not defined

 Before you can update a variable, you have to initialize it, usually with a simple
assignment:

>>> x = 0

>>> x = x + 1

 Updating a variable by adding 1 is called an increment; subtracting 1 is called a


decrement.

COURSE: Python UNIT: 3 Pg. 8


While Loop

 The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.

 We generally use this loop when we don't know the number of times to iterate
beforehand.

Syntax of while Loop in Python


 

while test_expression:

Body of while

 In the while loop, test expression is checked first. The body of the loop is entered
only if the test_expression evaluates to True. After one iteration, the test expression is
checked again.

 This process continues until the test_expression evaluates to False.

COURSE: Python UNIT: 3 Pg. 9


While Loop

Program for sum of n natural numbers

n = int(input("Enter n: "))

n = 10

sum = 0 i = 1

while i <= n:

sum = sum + I

i = i+1 # update counter

print("The sum is", sum)

COURSE: Python UNIT: 3 Pg. 10


Python break statement

 The break is a keyword in python which is used to bring the program control out of
the loop.

 In other words, we can say that break is used to abort the current execution of the
program and the control goes to the next line after the loop.

COURSE: Python UNIT: 3 Pg. 11


Python break statement

Example

str = "python"  

for i in str:  

    if i == ‘o':  

        break  

    print(i)

Output:p y t h

COURSE: Python UNIT: 3 Pg. 12


Square Roots

Loops are often used in programs that compute numerical results by starting with an
approximate answer and iteratively improving it.

For example, one way of computing square roots is Newton’s method.


 Suppose that you want to know the square root of a. If you start with almost any
estimate, x, you can compute a better estimate with the following formula

y = x + a/x/2

For example, if a is 4 and x is 3:


 

>>> x = 3
>>> y = (x + a/x) / 2
>>> y
2.16666666667

COURSE: Python UNIT: 3 Pg. 13


Algorithms

Newton’s method is an example of an algorithm: it is a mechanical process for solving


a category of problems (in this case, computing square roots).

To understand what an algorithm is, it might help to start with something that is not
an algorithm. When you learned to multiply single-digit numbers, you probably
memorized the multiplication table. In effect, you memorized 100 specific
solutions.That kind of knowledge is not algorithmic.

COURSE: Python UNIT: 3 Pg. 14


Part B:Strings

• A string is a sequence

• Len

• Traversal with a for loop

• String slices

• Strings are immutable

• Searching

• Looping and Counting

COURSE: Python UNIT: 3 Pg. 15


Part B:Strings

• String methods

• The in operator

• String comparison

COURSE: Python UNIT: 3 Pg. 16


Strings

 A string is a sequence of characters. You can access the characters one at a time
with the bracket operator:

>>> fruit = 'banana'

>>> letter = fruit[1]

 The second statement selects character number 1 from fruit and assigns it to letter.

COURSE: Python UNIT: 3 Pg. 17


Strings

 A string is a sequence of characters. You can access the characters one at a time
with the bracket operator:

>>> fruit = 'banana'

>>> letter = fruit[1]

 The second statement selects character number 1 from fruit and assigns it to letter.

 The expression in brackets is called an index. The index indicates which character in
the sequence you want (hence the name).

 But you might not get what you expect:

>>> letter

'a‘

COURSE: Python UNIT: 3 Pg. 18


Strings

 For most people, the first letter of 'banana' is b, not a. But for computer
scientists,the index is an offset from the beginning of the string, and the offset of the
first letter is zero.
>>> letter = fruit[0]
>>> letter
'b’

 As an index, you can use an expression that contains variables and operators:
>>> i = 1
>>> fruit[i]
'a'
>>> fruit[i+1]
'n‘

COURSE: Python UNIT: 3 Pg. 19


Strings

 But the value of the index has to be an integer. Otherwise you get:
>>> letter = fruit[1.5]
TypeError: string indices must be integers

COURSE: Python UNIT: 3 Pg. 20


Len

 len is a built-in function that returns the number of characters in a string:

>>> fruit = 'banana'

>>> len(fruit)

 To get the last letter of a string, you might be tempted to try something like this:
>>> length = len(fruit)
>>> last = fruit[length]
IndexError: string index out of range

COURSE: Python UNIT: 3 Pg. 21


Len

 To get the last character, you have to subtract 1 from length:


>>> last = fruit[length-1]
>>> last
'a‘

Or you can use negative indices, which count backward from the end of the string.

The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last,and so
on.

COURSE: Python UNIT: 3 Pg. 22


Traversal with a 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.

Example:-Print each fruit in a fruit list:


 

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

for x in fruits:
  print(x)

COURSE: Python UNIT: 3 Pg. 23


Looping Through a String

 Even strings are iterable objects, they contain a sequence of characters:

Example:-Loop through the letters in the word "banana":


 

for x in "banana":
 

  print(x)

COURSE: Python UNIT: 3 Pg. 24


String Slices

 A segment of a string is called a slice.

 You can return a range of characters by using the slice syntax.

 Specify the start index and the end index, separated by a colon, to return a part of
the string.

Example:-Get the characters from position 2 to position 5 (not included):


 

b = "Hello, World!"
 

print(b[2:5])

COURSE: Python UNIT: 3 Pg. 25


Strings Are Immutable

 Immutable Object

That means once created its state cannot be changed. It will represent the same
value once created. For Example — String is immutable in python.

A string object will always represent the same value, it can't be modified.

tuple1 = (0, 1, 2, 3) 

tuple1[0] = 4

print(tuple1)

Error :

TypeError: 'tuple' object does not support item assignment


 

COURSE: Python UNIT: 3 Pg. 26


Searching

 Searching is a very basic necessity when you store data in different data structures.
The simplest appraoch is to go across every element in the data structure and match it
with the value you are searching for. This is known as Linear search.

Problem: Given an array arr[] of n elements, write a function to search a given


 

element x in arr[].
Examples :

Input : arr[] = {10, 20, 80, 30, 60, 50, 110, 100, 130, 170}
 

x = 110;
 

Output : 6 Element x is present at index 6


 

COURSE: Python UNIT: 3 Pg. 27


Searching

Input : arr[] = {10, 20, 80, 30, 60, 50, 110, 100, 130, 170}
 

 
x = 175;

Output : -1 Element x is not present in arr[].


 

 A simple approach is to do linear search, i.e Start from the leftmost element of arr[]
and one by one compare x with each element of arr[]

If x matches with an element, return the index.

If x doesn’t match with any of elements, return -1.

COURSE: Python UNIT: 3 Pg. 28


Looping and Counting

The following program counts the number of times the letter a appears in a string:
word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print(count)

COURSE: Python UNIT: 3 Pg. 29


String methods

Strings provide methods that perform a variety of useful operations.

For example, the method upper takes a string and returns a new string with all
uppercase letters.

Instead of the function syntax upper(word), it uses the method syntax word.upper():
>>> word = 'banana'
>>> new_word = word.upper()
>>> new_word
'BANANA'

COURSE: Python UNIT: 3 Pg. 30


String methods

String find() Method:-
 

The find() method finds the first occurrence of the specified value.

The find() method returns -1 if the value is not found.

EX:- txt = "Hello, welcome to my world.”

x = txt.find("welcome")

print(x)

Output:-7

COURSE: Python UNIT: 3 Pg. 31


in operator

 in and not in are the membership operators in Python. They are used to test


whether a value or variable is found in a sequence (string, list, tuple, set and
dictionary). 

 in operator:-Returns True if a sequence with the specified value is present in the


object.

Example:
 
x in y

In Operator Example
 

x = ["apple", "banana"]
print("banana" in x)
# returns True because a sequence with the value "banana" is in the list

COURSE: Python UNIT: 3 Pg. 32


String comparison.

 You can use ( > , < , <= , <= , == , != ) to compare two strings. 

 Python compares string lexicographically i.e using ASCII value of the characters. 

 The characters in both strings are compared one by one. When different characters


are found then their Unicode value is compared. The character with lower Unicode
value is considered to be smaller.

COURSE: Python UNIT: 3 Pg. 33


String comparison.

fruit1 = 'Apple'
print(fruit1 == 'Apple')
print(fruit1 != 'Apple')
print(fruit1 < 'Apple')
print(fruit1 > 'Apple')
print(fruit1 <= 'Apple')
print(fruit1 >= 'Apple')
Output:- True
False
False
False
True
True

COURSE: Python UNIT: 3 Pg. 34


PART C : Case Study

• Reading word lists

• Search,

• Looping with indices

COURSE: Python UNIT: 3 Pg. 35


Reading word lists

 You In Python the built-in function open takes the name of the file as a parameter
and returns a file object you can use to read the file.

>>> fin = open('words.txt')

 fin is a common name for a file object used for input

 The file object provides several methods for reading, including readline, which reads
characters from the file until it gets to a newline and returns the result as a string:
>>> fin.readline()
'aa\r\n'

 The first word in this particular list is “aa”, which is a kind of lava. The sequence \r\n
represents two whitespace characters, a carriage return and a newline, that separate
this word from the next.

COURSE: Python UNIT: 3 Pg. 36


Python Program for Linear Search

def search(arr, x):


  for i in range(len(arr)):   
        if arr[i] == x:
             return i
     return -1

 A simple approach is to do linear search, i.e

 Start from the leftmost element of arr[] and one by one compare x with each
element of arr[]

 If x matches with an element, return the index.

 If x doesn’t match with any of elements, return -1.

COURSE: Python UNIT: 3 Pg. 37


Looping with indices

 The syntax of a while loop in Python programming language is  

while expression: 

statement(s)

 Here, statement(s) may be a single statement or a block of statements. The


condition may be any expression, and true is any non-zero value.

 The loop iterates while the condition is true.


num = 1
while num < 10:
print(num)
num = num + 3

COURSE: Python UNIT: 3 Pg. 38


PART D : Lists

• List is a sequence

• Lists are mutable

• Traversing a list

• List operations

• List slices

• List methods

• Map filter and reduce

COURSE: Python UNIT: 3 Pg. 39


PART D : Lists

• Deleting elements

• Lists and Strings

• Objects and values

• Aliasing

• List arguments.

COURSE: Python UNIT: 3 Pg. 40


List Is a Sequence

 Like a string, a list is a sequence of values. In a string, the values are characters; in
a list, they can be any type. The values in a list are called elements or sometimes
items.

 There are several ways to create a new list; the simplest is to enclose the elements
in square brackets ([ and ]):

[10, 20, 30, 40]

['crunchy frog', 'ram bladder', 'lark vomit']

 The following list contains a string, a float, an integer, and (lo!) another list:

['spam', 2.0, 5, [10, 20]]

 A list within another list is nested.

COURSE: Python UNIT: 3 Pg. 41


List Is a Sequence

A list that contains no elements is called an empty list; you can create one with empty
brackets, [].

As you might expect, you can assign list values to variables:
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> numbers = [42, 123]
>>> empty = []
>>> print(cheeses, numbers, empty)
['Cheddar', 'Edam', 'Gouda'] [42, 123] []

COURSE: Python UNIT: 3 Pg. 42


Lists Are Mutable

 Lists are mutable objects which means you can modify a list object after it has been
created. 

Ex:-
>>> a = [1, 3, 5, 7]
>>> b = a
>>> b[0] = -10
>>> a
[-10, 3, 5, 7]

COURSE: Python UNIT: 3 Pg. 43


Lists Are Mutable

 The in operator also works on lists:


>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False

COURSE: Python UNIT: 3 Pg. 44


Traversing a List

 Python for loop can be used to iterate through the List.

Example:
input_list = [10, “SVEC", 15, “TPT", 1]
for x in input_list:
    print(x)

Output:
10
 

 
SVEC
 
15
TPT
 

 
1

COURSE: Python UNIT: 3 Pg. 45


Traversing a List

 Python while loop can be used to iterate through the list.

input_list = [10, "Safa", 15, "Aman", 1]

length_list = len(input_list)

x=0

while x < length_list:

    print(input_list[x])

    x += 1

COURSE: Python UNIT: 3 Pg. 46


List operations
The + operator concatenates lists:

>>> a = [1, 2, 3]

>>> b = [4, 5, 6]

>>> c = a + b

>>> c

[1, 2, 3, 4, 5, 6]

The * operator repeats a list a given number of times:

>>> [1, 2, 3] * 3

[1, 2, 3, 1, 2, 3, 1, 2, 3]

In the above example repeats the list [1, 2,3] three times.
 

COURSE: Python UNIT: 3 Pg. 47


List slices

 The slice operator also works on lists:

>>> t = ['a', 'b', 'c', 'd', 'e', 'f']

>>> t[1:3]

['b', 'c']

>>> t[:4]

['a', 'b', 'c', 'd']

>>> t[3:]

['d', 'e', 'f']

COURSE: Python UNIT: 3 Pg. 48


List slices

 If you omit the first index, the slice starts at the beginning. If you omit the second,
the slice goes to the end. So if you omit both, the slice is a copy of the whole list:
>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']

 Since lists are mutable, it is often useful to make a copy before performing
operations that modify lists.

 A slice operator on the left side of an assignment can update multiple elements:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> t
['a', 'x', 'y', 'd', 'e', 'f']

COURSE: Python UNIT: 3 Pg. 49


List Methods

 Python provides methods that operate on lists. For example, append adds a new
element to the end of a list:
>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> t
['a', 'b', 'c', 'd']

 extend takes a list as an argument and appends all of the elements:


>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> t1
['a', 'b', 'c', 'd', 'e']

COURSE: Python UNIT: 3 Pg. 50


List Methods

 Sort arranges the elements of the list from low to high:

>>> t = ['d', 'c', 'e', 'b', 'a']

>>> t.sort()

>>> t

Output:-

['a', 'b', 'c', 'd', 'e']

COURSE: Python UNIT: 3 Pg. 51


Map, Filter and Reduce

 To add up all the numbers in a list, you can use a loop like this:
def add_all(t):
total = 0
for x in t:
total += x
return total

Total is initialized to 0. Each time through the loop, x gets one element from the list.

The += operator provides a short way to update a variable. This augmented


assignmentstatement,

COURSE: Python UNIT: 3 Pg. 52


Map, Filter and Reduce

total += x

 As the loop runs, total accumulates the sum of the elements; a variable used this
way is sometimes called an accumulator.

 Adding up the elements of a list is such a common operation that Python provides it
as a built-in function, sum:

>>> t = [1, 2, 3]

>>> sum(t)

 An operation like this that combines a sequence of elements into a single value is
sometimes called reduce.

COURSE: Python UNIT: 3 Pg. 53


Deleting Elements

 There are several ways to delete elements from a list. If you know the index of the
element you want, you can use pop:
>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> t
['a', 'c']
>>> x
'b‘

 pop modifies the list and returns the element that was removed. If you don’t
provide an index, it deletes and returns the last element.

COURSE: Python UNIT: 3 Pg. 54


Deleting Elements

 If you know the element you want to remove (but not the index), you can use
remove:
>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> t
['a', 'c']

The return value from remove is None.

To remove more than one element, you can use del with a slice index:
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> t
['a', 'f']

COURSE: Python UNIT: 3 Pg. 55


Lists and Strings

 A string is a sequence of characters and a list is a sequence of values, but a list of


characters is not the same as a string. To convert from a string to a list of characters,
you can use list:

>>> s = ‘SVEC'

>>> t = list(s)

>>> t

[‘S', ‘V', ‘E', ‘C']

COURSE: Python UNIT: 3 Pg. 56


Lists and Strings

The list function breaks a string into individual letters. If you want to break a string
into words, you can use the split method:

>>> s = 'pining for the fjords'

>>> t = s.split()

>>> t

['pining', 'for', 'the', 'fjords']

COURSE: Python UNIT: 3 Pg. 57


Objects and values

 In Python, variables are references to objects and any variable can reference


any object. A variable is created by simply using it.

 To check whether two variables refer to the same object, you can use the is
operator:

>>> a = 'banana'

>>> b = 'banana'

>>> a is b

True

COURSE: Python UNIT: 3 Pg. 58


aliasing

 If a refers to an object and you assign b = a, then both variables refer to the same
object:

>>> a = [1, 2, 3]

>>> b = a

>>> b is a

Tru

 The association of a variable with an object is called a reference. In this


example,there are two references to the same object.

COURSE: Python UNIT: 3 Pg. 59


aliasing

 An object with more than one reference has more than one name, so we say that
the object is aliased.

 If the aliased object is mutable, changes made with one alias affect the other:

>>> b[0] = 42

>>> a

[42, 2, 3]

COURSE: Python UNIT: 3 Pg. 60


List Arguments

 When you pass a list to a function, the function gets a reference to the list. If the
function modifies the list, the caller sees the change.

 For example, delete_head removes the first element from a list:

def delete_head(t):

del t[0]

COURSE: Python UNIT: 3 Pg. 61


List Arguments
 When you pass a list to a function, the function gets a reference to the list. If the
function modifies the list, the caller sees the change. For example, delete_head
removes the first element from a list:

def delete_head(t):

del t[0]

 Here’s how it is used:

>>> letters = ['a', 'b', 'c']

>>> delete_head(letters)

>>> letters

['b', 'c']

 The parameter t and the variable letters are aliases for the same object.

COURSE: Python UNIT: 3 Pg. 62


MCQ’s

1. What is the output of “hello”+1+2+3?

A. hello123

B. hello

C. Error

D. hello6

COURSE: Python UNIT: 3 Pg. 63


MCQ’s

2. What will be the output of below Python code?

str1="Information"
print(str1[2:8])

COURSE: Python UNIT: 3 Pg. 64


MCQ’s

3. What will following Python code return?


str1="Stack of books"

print(len(str1))

A. 13
B. 14
C. 15
D. 16

COURSE: Python UNIT: 3 Pg. 65


MCQ’s

4.For loop in python in Work on___________

A.range

B.iteration

C.Both of the above

D.None of the above

COURSE: Python UNIT: 3 Pg. 66


MCQ’s

1. What is the output of “hello”+1+2+3?

A. hello123

B. hello

C. Error

D. hello6

COURSE: Python UNIT: 3 Pg. 67


QUIZ

1. Which of the following commands will create a list?


a) list1 = list()
b) list1 = []
c) list1 = list([1, 2, 3])
d) all of the mentioned

COURSE: Python UNIT: 3 Pg. 68


QUIZ

2.Suppose list1 is [1, 5, 9], what is sum(list1)?


a) 1
b) 9
c) 15
d) Error

COURSE: Python UNIT: 3 Pg. 69


QUIZ

3. Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1]?


a) Error
b) None
c) 25
d) 2

COURSE: Python UNIT: 3 Pg. 70


QUIZ

4. What will be the output of the following Python statement?

>>>"a"+"bc"

a) a
b) bc
c) bca
d) abc

COURSE: Python UNIT: 3 Pg. 71


QUIZ

5. What will be the output of the following Python statement?

>>>"abcd"[2:]

a) a
b) ab
c) cd
d) dc

COURSE: Python UNIT: 3 Pg. 72


QUIZ

6. What arithmetic operators cannot be used with strings?


 

a) +
b) *
c) –
d) All of the mentioned

COURSE: Python UNIT: 3 Pg. 73


QUIZ

7. What will be the output of the following Python code?

>>>str1="helloworld"

>>>str1[::-1]

a) dlrowolleh
b) hello
c) world
d) helloworld

COURSE: Python UNIT: 3 Pg. 74


Assignment programs

1)Write a C Program to access each character of string in forward & backward


direction.

2) Write a C Program to accept some string print all characters with index.

3) Write a C Program to read employee data from the keyboard print the data.

4) How to slice lists in Python write a Program on it?

COURSE: Python UNIT: 3 Pg. 75

You might also like