Dept & Sem: Subject Name: Course Code: Unit: Prepared by
Dept & Sem: Subject Name: Course Code: Unit: Prepared by
PREPARED BY :
• Reassignment
• Updating variables
• Break
• Square roots
• Algorithms.
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.
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.
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.
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:
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);
>>> x = x + 1
Before you can update a variable, you have to initialize it, usually with a simple
assignment:
>>> x = 0
>>> x = x + 1
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.
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.
n = int(input("Enter n: "))
n = 10
sum = 0 i = 1
while i <= n:
sum = sum + I
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.
Example
str = "python"
for i in str:
if i == ‘o':
break
print(i)
Output:p y t h
Loops are often used in programs that compute numerical results by starting with an
approximate answer and iteratively improving it.
y = x + a/x/2
>>> x = 3
>>> y = (x + a/x) / 2
>>> y
2.16666666667
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.
• A string is a sequence
• Len
• String slices
• Searching
• String methods
• The in operator
• String comparison
A string is a sequence of characters. You can access the characters one at a time
with the bracket operator:
The second statement selects character number 1 from fruit and assigns it to letter.
A string is a sequence of characters. You can access the characters one at a time
with the bracket operator:
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).
>>> letter
'a‘
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‘
But the value of the index has to be an integer. Otherwise you get:
>>> letter = fruit[1.5]
TypeError: string indices must be integers
>>> 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
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.
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.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
for x in "banana":
print(x)
Specify the start index and the end index, separated by a colon, to return a part of
the string.
b = "Hello, World!"
print(b[2:5])
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.
tuple1[0] = 4
print(tuple1)
Error :
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.
element x in arr[].
Examples :
Input : arr[] = {10, 20, 80, 30, 60, 50, 110, 100, 130, 170}
x = 110;
Input : arr[] = {10, 20, 80, 30, 60, 50, 110, 100, 130, 170}
x = 175;
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[]
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)
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'
String find() Method:-
x = txt.find("welcome")
print(x)
Output:-7
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
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
• Search,
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.
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.
Start from the leftmost element of arr[] and one by one compare x with each
element of arr[]
while expression:
statement(s)
• List is a sequence
• Traversing a list
• List operations
• List slices
• List methods
• Deleting elements
• Aliasing
• List arguments.
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 ]):
The following list contains a string, a float, an integer, and (lo!) another list:
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] []
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]
Example:
input_list = [10, “SVEC", 15, “TPT", 1]
for x in input_list:
print(x)
Output:
10
SVEC
15
TPT
1
length_list = len(input_list)
x=0
print(input_list[x])
x += 1
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> c
[1, 2, 3, 4, 5, 6]
>>> [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.
>>> t[1:3]
['b', 'c']
>>> t[:4]
>>> t[3:]
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']
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']
>>> t.sort()
>>> t
Output:-
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.
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.
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.
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']
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']
>>> s = ‘SVEC'
>>> t = list(s)
>>> t
The list function breaks a string into individual letters. If you want to break a string
into words, you can use the split method:
>>> t = s.split()
>>> t
To check whether two variables refer to the same object, you can use the is
operator:
>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
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
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]
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.
def delete_head(t):
del t[0]
def delete_head(t):
del t[0]
>>> delete_head(letters)
>>> letters
['b', 'c']
The parameter t and the variable letters are aliases for the same object.
A. hello123
B. hello
C. Error
D. hello6
str1="Information"
print(str1[2:8])
print(len(str1))
A. 13
B. 14
C. 15
D. 16
A.range
B.iteration
A. hello123
B. hello
C. Error
D. hello6
>>>"a"+"bc"
a) a
b) bc
c) bca
d) abc
>>>"abcd"[2:]
a) a
b) ab
c) cd
d) dc
a) +
b) *
c) –
d) All of the mentioned
>>>str1="helloworld"
>>>str1[::-1]
a) dlrowolleh
b) hello
c) world
d) helloworld
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.