Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
31 views

Python Notes - Unit 2

sfsdfsf

Uploaded by

benim15823
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Python Notes - Unit 2

sfsdfsf

Uploaded by

benim15823
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Python Flow control

(i) The Simple if Statement

if condition :
block

➢ The reserved word if begins a if statement.


➢ The condition is a Boolean expression that determines whether or not the body will be
executed. A colon (:) must follow the condition.
➢ The block is a block of one or more statements to be executed if the condition is true. the
statements within a block must all be indented the same number of spaces from the
left. The block within an if must be indented more spaces than the line that begins the if
statement. The block technically is part of the if statement. This part of the if statement is
sometimes called the body of the if.

Example :

if x < 10:
y=x

could be written

if x < 10: y = x

but may not be written as

if x < 10:
y=x

Example :

a=int(input(" Input a Number : "))


if a>10:
# Starting of if condition Block
print (a)
print("end of condition")
# End of if condition Block
#Below print is not part of if condition
print("end of prog")
How to provide multiple statements on a single line : Normally each statement is
written on separate physical line. However, statements in a block can be written in one
line if they are separated by semicolon. Following is code of three statements written in
separate lines
For examples
a=10
b=20
print(a*b)

can be rewritten as

a=10; b=20; print (a*b)

(ii) The if/else Statement

if condition :
if block
else:
else block
➢ The reserved word if begins the if/else statement.

➢ The condition is a Boolean expression that determines whether or not the if block or the
else block will be executed. A colon (:) must follow the condition.

Example : Write a program to input two numbers and print maximum.

a=eval(input('Input first number : '))


b=eval(input('Input second number : '))
if a>b :
print('a is maximum',a)
else:
print('b is maximum',b)

(iii) The if/elif/else Statement

Q. Write a program to input three numbers and print maximum.

a=eval(input('Input first number : '))


b=eval(input('Input second number : '))
c=eval(input('Input Third number : '))
if a>b and a>c :
print('a is maximum',a)
elif b>c:
print('b is maximum',b)
else:
print('c is maximum',c)

(iv) Nested if Condition

value = eval(input("Please enter an integer value in the range 0...10: "))


if value >= 0 : # First check
if value <= 10 : # Second check
print("In range")
print("Done")
print (“End of Prog”)

(v) Conditional Expressions

expression1(true Value) if condition else expression2(False Value)


where

➢ expression1 is the overall value of the conditional expression if condition is true.


➢ condition is a normal Boolean expression that might appear in an if statement.
➢ expression2 is the overall value of the conditional expression if condition is false.

Example :
>>> a=2
>>> b=4
>>> print (a) if a>b else print (b)
4

Iteration
Iteration repeats the execution of a sequence of code. Iteration is useful for solving many
programming problems.

(i) The while Statement The while statement has the general form:

while condition :
block

(ii)The for Statement


for var in sequence :
block

Sequence can be replaced by range function

range( [begin],end,[step] )
where

• begin is the first value in the range; if omitted, the default value is 0
• end is one past the last value in the range; the end value may not be omitted
• change is the amount to increment or decrement; if the change parameter is omitted, it defaults
to 1 (counts up by ones)

Note : begin, end, and step must all be integer values; floating-point values and other types are
not allowed.

The following examples show how range can be used to produce a variety of sequences:

• range(10) 0,1,2,3,4,5,6,7,8,9 # 10 is end value, begin and step are default


• range(1, 10) 1,2,3,4,5,6,7,8,9 # 1 is begin value, 10 is end value, step is default
• range(1, 10, 2) 1,3,5,7,9
• range(10, 0, -1) 10,9,8,7,6,5,4,3,2,1
• range(10, 0, -2) 10,8,6,4,2
• range(2, 11, 2) 2,4,6,8,10
• range(-5, 5) −5,−4,−3,−2,−1,0,1,2,3,4
• range(1, 2) 1
• range(1, 1) (empty)
• range(0) (empty)

Q. Write a program to print 1 to n numbers using while loop.


n=int(input('Input value of n : '))
i=1
while i<=n:
print(i)
i+=1
print('End of Prog')

Q. Write a program to print 1 to n numbers using for loop.


n=int(input('Input value of n : '))
for i in range(1,n+1):
print(i)
print('End of Prog')

Q. Write a program to input a number and print factorial.


n=int(input('Input value of n : '))
i=1
ans=1
while i<=n:
ans=ans*i
i+=1
print("Factorial is ",ans)

Q. Write a program to print following pattern.


1
12
123
1234
12345

n=int(input('Input value of n : '))


for i in range(1,n+1):
for j in range(1,i+1):
print(j,end=" ")
print()
print("End of Prog")

Q. Write a program to input a number and print sum of digits.


n=int(input('Input value of n : '))
s=0
while n!=0:
r=n%10
s=s+r
n=int(n/10)
print("sum of digits : ",s)
Q. Write a program to input a number and count number of odd and even digits.
n=int(input('Input value of n : '))
odd=0
even=0
while n!=0:
r=n%10
if r%2==0:
even+=1
else:
odd+=1
n=int(n/10)
print("Odd digits : ",odd)
print("Even digits : ",even)

The break statement : Python provides the break statement to implement middle-exiting control logic. The
break statement causes the immediate exit from the body of the loop.

n=5
for i in range(1,n+1):
if i==3:
break
print (i)
print ("end of Prog")

The continue statement : the continue statement stop the current iteration of the
loop, and continue with the next iteration.

n=5
for i in range(1,n+1):
if i==3:
continue
print (i)
print ("end of Prog")

Else in For Loop : The else keyword in a for loop specifies a block of code to
be executed when the loop is finished:
Example1 :
n=5
for i in range(1,n+1):
print (i)
else:
print ("end of for loop")
print("End of Prog")

Output : 1 2 3 4 5 “End of for loop” “End of Prog”

Example 2:
n=5
for i in range(1,n+1):
if i==3:
break
print (i)
else:
print ("end of for ")
print ("end of Prog")

Output : 1 2 End of Prog

(ii) List
Lists are just like the arrays, declared in other languages which is an ordered
collection of data. It is very flexible as the items in a list do not need to be of the
same type. List items can be accessed using a zero-based index in the
square brackets []. Indexes start from zero and increment by one
for each item. Accessing an item using a large index than the list's
total items would result in IndexError.

Example
mylist=[] # empty list
print(mylist)

names=["ajay", "Bill", "mohan", "raman"] # string list


print(names)

item=[1, "Jeff", "Computer", 75.50, True] # heterogeneous data


print(item)

nums=[1, 2, 3, [4, 5, 6, [7, 8, [9]]], 10]

print(nums[0]) # returns 1
print(nums[1]) # returns 2
print(nums[3]) # returns [4, 5, 6, [7, 8, [9]]]
print(nums[4]) # returns 10
print(nums[3][0]) # returns 4
print(nums[3][3]) # returns [7, 8, [9]]
print(nums[3][3][0]) # returns 7
print(nums[3][3][2]) # returns [9]

List Methods
List Method Description

list.append() Adds a new item at the end of the list.

list.clear() Removes all the items from the list and make it empty.

list.copy() Returns a shallow copy of a list.

list.count() Returns the number of times an element occurs in the list.

list.extend() Adds all the items of the specified iterable (list, tuple, set, dictionary, string) to the end of
the list.

list.index() Returns the index position of the first occurance of the specified item. Raises a ValueError if
there is no item found.

list.insert() Inserts an item at a given position. Insert(index,item)

list.pop() Returns an item from the specified index position and also removes it from the list. If no
index is specified, the list.pop() method removes and returns the last item in the list.

list.remove() Removes the first occurance of the specified item from the list. It the specified item not
found then throws a ValueError.

list.reverse() Reverses the index positions of the elements in the list. The first element will be at the last
index, the second element will be at second last index and so on.

list.sort() Sorts the list items in ascending, descending, or in custom order.


List Operators
Like the string, the list is also a sequence. Hence, the operators used
with strings are also available for use with the list (and tuple also).

Operator Example
The + operator returns a list containing all the elements of the first and >>> L1=[1,2,3]
the second list. >>> L2=[4,5,6]
>>> L1+L2
[1, 2, 3, 4, 5, 6]
The * operator concatenates multiple copies of the same list. >>> L1=[1,2,3]
>>> L1*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
The slice operator [] returns the item at the given index. A negative >>> L1=[1, 2, 3]
index counts the position from the right side. >>> L1[0]
1
>>> L1[-3]
1
>>> L1[1]
2
>>> L1[-2]
2
>>> L1[2]
3
>>> L1[-1]
3
The range slice operator [FromIndex : Untill Index - 1] fetches items >>> L1=[1, 2, 3, 4, 5, 6]
in the range specified by the two index operands separated by : symbol. >>> L1[1:]
If the first operand is omitted, the range starts from the index 0. If the [2, 3, 4, 5, 6]
second operand is omitted, the range goes up to the end of the list. >>> L1[:3]
[1, 2, 3]
>>> L1[1:4]
[2, 3, 4]
>>> L1[3:]
[4, 5, 6]
>>> L1[:3]
[1, 2, 3]
>>> L1[-5:-3]
[2, 3]
The in operator returns true if an item exists in the given list. >>> L1=[1, 2, 3, 4, 5, 6]
>>> 4 in L1
True
>>> 10 in L1
False
The not in operator returns true if an item does not exist in the given >>> L1=[1, 2, 3, 4, 5, 6]
list. >>> 5 not in L1
False
>>> 10 not in L1
True
Q. Write a program to input n names in a list and print it.

names=[] # creates empty list


n=int(input('Input value of n : '))
for i in range(1,n+1):
name=input('Input a name : ')
names.append(name)
print(names)

Q. Write a program to input n numbers in a list and print sum.

#Write a program to input n numbers in a list and print sum.


n=int(input("Input value of N : "))
num=[] # create empty list
for i in range(1,n+1):
a=int(input('Input a number : '))
num.append(a)
s=0
for i in range(0,n):
s=s+num[i]
print("Sum = ",s)

Q. Write a program to input n numbers in a list and perform sequencial search


n=int(input("Input value of N : "))
num=[] # create empty list
for i in range(1,n+1):
a=int(input('Input a number : '))
num.append(a)
s=int(input("Input number to search in list : "))
found=False
for i in range(0,n):
if num[i]==s :
found=True
break
if found==True :
print ("Number Found ")
else :
print ("Number Not Found ")

Q Write a program to input n data items in a list and perform sequencial search
n=int(input("Input value of N : "))
data=[] # create empty list
for i in range(1,n+1):
a=input('Input data item : ')
data.append(a)
s=input("Input data to search in list : ")
found=False
for i in range(0,n):
if data[i]==s :
found=True
break
if found==True :
print ("Data Found ")
else :
print ("Data Not Found ")

Q Write a program to input n data items in a list and perform sequencial search
n=int(input("Input value of N : "))
data=[] # create empty list
for i in range(1,n+1):
a=input('Input data item : ')
data.append(a)
s=input("Input data to search in list : ")
if s in data:
print("Data Found")
else:
print("Data Not Found")
(iii) Tuples
Tuple is an immutable (unchangeable) collection of elements of
different data types. It is an ordered collection, so it preserves the
order of elements in which they were defined.

Tuples are defined by enclosing elements in parentheses (),


separated by a comma. The following declares a tuple type variable.

tpl=() # empty tuple


print(tpl)

names = ('Jeff', 'Bill', 'Steve', 'Yash') # string tuple


print(names)

nums = (1, 2, 3, 4, 5) # int tuple


print(nums)

employee=(1, 'Steve', True, 25, 12000) # heterogeneous data tuple


print(employee)

However, it is not necessary to enclose the tuple elements in


parentheses. The tuple object can include elements separated by a
comma without parentheses.

Example: Tuple Variable Declaration


names = 'Jeff', 'Bill', 'Steve', 'Yash' # string tuple
print(names)

nums = 1, 2, 3, 4, 5 # int tuple


print(nums)

Note : Tuples cannot be declared with a single element unless


followed by a comma.

Access Tuple Elements


Each element in the tuple is accessed by the index in the square
brackets []. An index starts with zero and ends with (number of
elements - 1). The tuple supports negative indexing also, the same
as list type.

nums = (1, 2, 3, 4, 5)
print(nums[0]) # prints 1
print(nums[1]) # prints 2
print(nums[4]) # prints 5
print(nums[-1]) # print 5

Tuple elements can be unpacked and assigned to variables

names = ('Jeff', 'Bill', 'Steve', 'Yash')


a, b, c, d = names # unpack tuple
print(a, b, c, d)

Note : Tuple is unchangeable. So, once a tuple is created, any


operation that seeks to change its contents is not allowed. However,
you can delete an entire tuple using the del keyword.
del tuplename

Tuple Operations
Like string, tuple objects are also a sequence. Hence, the operators
used with strings are also available for the tuple.

Operator Example
The + operator returns a tuple containing all the elements of the >>> t1=(1,2,3)
first and the second tuple object. >>> t2=(4,5,6)
>>> t1+t2
(1, 2, 3, 4, 5, 6)
>>> t2+(7,)
(4, 5, 6, 7)
The * operator Concatenates multiple copies of the same tuple. >>> t1=(1,2,3)
>>> t1*4
(1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3)
The [] operator Returns the item at the given index. A negative >>> t1=(1,2,3,4,5,6)
index counts the position from the right side. >>> t1[3]
4
>>> t1[-2]
5
The [:] operator returns the items in the range specified by two >>> t1=(1,2,3,4,5,6)
index operands separated by the : symbol. >>> t1[1:3]
Operator Example
If the first operand is omitted, the range starts from zero. If the (2, 3)
second operand is omitted, the range goes up to the end of the >>> t1[3:]
tuple. (4, 5, 6)
>>> t1[:3]
(1, 2, 3)
The in operator returns true if an item exists in the given tuple. >>> t1=(1,2,3,4,5,6)
>>> 5 in t1
True
>>> 10 in t1
False
The not in operator returns true if an item does not exist in the >>> t1=(1,2,3,4,5,6)
given tuple. >>> 4 not in t1
False
>>> 10 not in t1
True

Tuple Methods
List Method Description

Tuple.count() Returns the number of times a specified value occurs in a tuple

Tuple.index() Searches the tuple for a specified value and returns the position of
first occurrence.

Python - Dictionary
The dictionary is an unordered collection that
contains key:value pairs separated by commas inside curly brackets.
Dictionaries are optimized to retrieve values when the key is known.
The key should be unique and an immutable object. A number,
string or tuple can be used as key.

Example: Dictionary

capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New


Delhi"}

d = {} # empty dictionary
numNames={1:"One", 2: "Two", 3:"Three"} # int key, string value

The same key cannot appear more than once in a collection. If the
key appears more than once, only the last will be retained. The
value can be of any data type.

>>> numNames = {1:"One", 2:"Two", 3:"Three", 2:"Two", 1:"One"}


>>> numNames
{1:"One", 2:"Two", 3:"Three"}

>>> type(numNames)
<class 'dict'>

Access Dictionary : Dictionary is an unordered collection, so a


value cannot be accessed using an index; instead, a key must be
specified in the square brackets. Keys are case-sensitive

>>> capitals = {"USA":"Washington DC", "France":"Paris", "India":"New


Delhi"}
>>>capitals["USA"]
'Washington DC'
>>> capitals["France"]
'Paris'

Access Dictionary using For Loop


capitals = {"USA":"Washington D.C.", "France":"Paris", "India":"New
Delhi"}

for key in capitals:


print("Key = " + key + ", Value = " + capitals[key])

Built-in Dictionary Methods


Method Description

dict.clear() Removes all the key-value pairs from the dictionary.

dict.copy() Returns a shallow copy of the dictionary.

dict.fromkeys() Creates a new dictionary from the given iterable (string, list, set, tuple) as keys and
Method Description

with the specified value.

dict.get() Returns the value of the specified key.

dict.items() Returns a dictionary view object that provides a dynamic view of dictionary
elements as a list of key-value pairs. This view object changes when the dictionary
changes.

dict.keys() Returns a dictionary view object that contains the list of keys of the dictionary.

dict.pop() Removes the key and return its value. If a key does not exist in the dictionary, then
returns the default value if specified, else throws a KeyError.

dict.popitem() Removes and return a tuple of (key, value) pair from the dictionary. Pairs are
returned in Last In First Out (LIFO) order.

dict.setdefault() Returns the value of the specified key in the dictionary. If the key not found, then it
adds the key with the specified defaultvalue. If the defaultvalue is not specified
then it set None value.

dict.update() Updates the dictionary with the key-value pairs from another dictionary or another
iterable such as tuple having key-value pairs.

dict.values() Returns the dictionary view object that provides a dynamic view of all the values in
the dictionary. This view object changes when the dictionary changes.

#Write a program to input coursename and course fee in a dictionary.

dict={}
while True:
print ("\n\n")
print ("1. Add Course and Fee")
print ("2. Course Fee")
print ("3. All Courses")
print ("4. Exit")
print ("============")
n=int(input("Input choice between 1-4 : "))
if n==4:
break

if n==2:
s=input("Input course name : ")
print ("Course Fee : ",dict[s])

if n==1:
cc=input("Input course name : ")
cn=input("Course Fee : ")
dict.setdefault(cc,cn)
if n==3:
for i in dict.keys():
print(i)

print("end of prog")

You might also like