Code Examples Python
Code Examples Python
1. If Statements
Using the case keyword every block is shown and the block label follows the case keyword. The
default block and the break statement are optional in a switch statement.
3. Conditional Operator Statement
C language provides an unusual operator, which is represented as a conditional operator.
Syntax:
(condition)? expr1: expr2
Expr1 is executed when the condition is valid. Then Expr2 will be executed if the statement is
incorrect.
4. goto Statement
goto statement is known for jumping control statements. It is used to transfer the control of the
program from one block to another block. goto keyword is used to declare the goto statement.
Syntax:
goto labelname;
labelname;
In the above syntax, goto is a keyword that is used to transfer the control to the labelname.
labelname is a variable name. In this case, the goto will transfer the control of the program to
the labelname and statements followed by the labelname will be executed.
5. Loop Statements
The programmer may want to repeat several instructions when writing C programs until some
requirements are met. To that end, C makes looping declarations for decision-making. We have
three types of loops,
1. For Loop
2. While Loop
3. Do While Loop
For Loop
In the For loop, the initialization statement is executed only one time. After that, the condition is
checked and if the result of condition is true it will execute the loop. If it is false, then for loop is
terminated. However, the result of condition evaluation is true, statements inside the body of for
loop gets executed, and the expression is updated. After that, the condition is checked again.
This process goes on until the result of the condition becomes false. When the condition is
false, the loop terminates.
Syntax:
for( initialization statement; condition)
{
//statements inside the loop
}
While Loop
In C, the while loop is a guided entry loop. The body of the while loops is only performed if the
condition is valid. The loop structure is not executed if the condition scores to incorrect.
The while loops are usually used when several instructions have to be repeated for an indefinite
time.
Syntax:
While(condition)
{
//statements inside the loop
}
Do While Loop
Unlike while loop, the body of the do is the difference between while and … while loop is
guaranteed to be done once at a time.
Syntax:
Do
{
//statements inside the loop
}
While(condition);
person nameolli
numberIS013
Assignment-2
Flow control Statements in python:
if Statements
The most common type of flow control statement is the if statement. An if clause (that is, the
block following the if statement) will execute if the condition is True. The clause is skipped if the
condition is False.
if statement consists of the following:
The if keyword A condition (that is, an expression that evaluates to True or False)
A colon Starting on the next line,
an indented block of code (called the if clause)
eg)
name=”person”
if name == 'Alice':
print('Hi, Alice.')
Output: False
else Statements
An if clause can optionally be followed by an else statement. The else clause is executed only
when the if statement condition is False.
eg)
name=’person’
if name == 'Alice':
print('Hi, Alice.')
else:
print('Hello, stranger.')
Output:
Hello, stranger
elif Statements
While only one of the if or else clauses will execute, you may have a case where you want one
of many possible clauses to execute.
In code, an elif statement always consists of the following:
The elif keyword A condition (that is, an expression that evaluates to True or False)
A colon Starting on the next line,
an indented block of code (called the elif clause)
eg)
name=’roger’
age=5
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
You can make a block of code execute over and over again using a while statement. The code
in a while clause will be executed as long as the while statement condition is True.
eg)
spam = 0
while spam < 5:
print('Hello, world.')
spam = spam + 1
Output:
Hello, world.
Hello, world.
Hello, world.
Hello, world.
Hello, world.
break Statements
If the execution reaches a break statement, it immediately exits the while clause. In code, a
break statement simply contains the break keyword.
eg)
while True:
print('Please type your name.')
name=input()
if name == 'avm':
break
print('Thank you!')
Output:
Please type your name.
avm
Thank you!
continue Statements
Like break statements, continue statements are used inside loops. When the program execution
reaches a continue statement, the program execution immediately jumps back to the start of the
loop and reevaluates the loop condition.
eg)
i=0
while(i<5):
i+=1
if(i==3):
continue
print(i)
Output:
1
2
4
5
The while loop keeps looping while its condition is True (which is the reason for its name), but
what if you want to execute a block of code only a certain number of times? You can do this with
a for loop statement and the range() function
In code, a for statement looks something like for i in range(5): and includes the following: The
for keyword
A variable name
The in keyword
A call to the range() method with up to three integers passed to it
A colon
Starting on the next line, an indented block of code (called the for clause)
eg)
print('My name is')
for i in range(5):
print('Jimmy Five Times (' + str(i) + ')')
Output:
My name is
Jimmy Five Times (0)
Jimmy Five Times (1)
Jimmy Five Times (2)
Jimmy Five Times (3)
Jimmy Five Times (4)
person nameolli
numberIS013
Assignment-3
Programs:
[Link] Python program that accepts principle, rate of interest, time and compute
the simple interest.
Output:
Enter principal: 10
Enter rate: 10
Enter time: 2
Simple Interest = 2.0
Output:
Please Enter the Maximum Value : 50
Palindrome Numbers between 1 and 50 are :
1 2 3 4 5 6 7 8 9 11 22 33 44
def DecimalToBinary(num):
if num >= 1:
DecimalToBinary(num // 2)
print(num % 2, end = '')
dec_val = int(input())
DecimalToBinary(dec_val)
Or
dec=244
print(bin(dec),”in binary”)
Output:
5
0101
5. Write a Python program to accept a string and display vowels and consonants
characters of the string.
def Conversion(centi):
inch = 0.3937 * centi
feet = 0.0328 * centi
print ("Inches is:", round(inch, 2))
print ("Feet is:", round(feet, 2))
centi = int(input())
Conversion(centi)
Output:
10
Inches is: 3.94
Feet is: 0.33
7.· Develop a Python program that accepts a sentence from the user and display
the longest word of that sentence with its length.
| |
| |
| |
-----------
| |
| |
| |
-----------
| |
| |
| |
9.· Write a Python program to demonstrate the working of stack (push, pop)
operations by creating corresponding function for push and pop operations.
Display the appropriate message in case of overflow and underflow situations.
class Stack:
def __init__(self):
[Link] = []
def add(self, dataval):
if dataval not in [Link]:
[Link](dataval)
return True
else:
return False
def peek(self):
return [Link][-1]
AStack = Stack()
[Link]("Mon")
[Link]("Tue")
[Link]()
print([Link]())
[Link]("Wed")
[Link]("Thu")
print([Link]())
class Stack:
def __init__(self):
[Link] = []
Output:
Tue
Thu
Thu
Wed
[Link] Python, build phone book which contains name of the person with their
phone numbers. Then, accept a name of the person and display the
corresponding phone number of the person if found, else error message.
names = []
phone_numbers = []
num = 3
for i in range(num):
name = input("Name: ")
phone_number = input("Phone Number: ")
[Link](name)
phone_numbers.append(phone_number)
print("\nName\t\t\tPhone Number\n")
for i in range(num):
print("{}\t\t\t{}".format(names[i], phone_numbers[i]))
search_term = input("\nEnter search term: ")
print("Search result:")
if search_term in names:
index = [Link](search_term)
phone_number = phone_numbers[index]
print("Name: {}, Phone Number: {}".format(search_term, phone_number))
else:
print("Name Not Found")
Output:
Name: avm
Phone Number: 99
Name:
Phone Number:
Name: ad
Phone Number: 97
Name Phone Number
avm 99
ad 97
Enter search term: avm
Search result:
Name: avm, Phone Number: 99
[Link] a Python program to check whether a given number is prime or not.
num = int(input())
flag = False
if num > 1:
for i in range(2, num):
if (num % i) == 0:
flag = True
break
if flag:
print(num, "is not a prime number")
else:
print(num, "is a prime number")
Output:
11
11 is a prime number
12.· Write a Python program to find largest of three numbers using nested-if.
a=int(input("Enter A: "))
b=int(input("Enter B: "))
c=int(input("Enter C: "))
if a>b:
if a>c:
g=a
else:
g=c
else:
if b>c:
g=b
else:
g=c
print("Greater = ",g)
Output:
Enter A: 1
Enter B: 2
Enter C: 3
Greater = 3
Module 1
Python is a programming language which has a wide range of syntactic constructions, standard
library functions and interactive development and env features.
On Windows
● Open the start button
● Select all programs
● Python 3.3
● Select IDLE (GUI)
On OSx
● Select application
● Mac Python 3.3
● Select IDLE
On Ubuntu
● Open terminal window
● IDLE 3
● A window with prompt should appear, this is interactive shell
eg) >>>2+2
4
In python, 2+2 is called an expression which is the basic programming instruction in the python
language.
● Expression consists of values such as 2 and operators such as + and they can always
evaluate down to a single value.
** exponent 2**3 8
% modulus 22%8 6
// Integer 22//8 2
division/floored
quotient
* Multiplication 3*5 15
- Subtraction 5-2 3
+ Addition 2+2 4
A data type is a category for values and every value belongs to exactly one data type.
Integer: The integer or int data type indicates values that are whole numbers.
Floating point: Numbers with decimal point are called floating point numbers or floats.
Strings: The text values are called strings or strs.
● The Strings are surrounded in single quote characters, so that python knows where the
string begins and ends.
● A string with no characters ‘’ is called a blank string.
Integer -2,-1,0,1,2
Floats -2.0,1.0.--0.5
String ‘a’,’bb!’,’// abc’
When the operator is used on one string value and one integer value it comes the string
replication operator
eg)print('alice'*5)
->alicealicealicealicealice
A variable is like a box in the computer memory where you can store a single value.
Assignment operators:
The value stored in variables in an assignment statement
An assignment statement consists of a variable name and an = (equal to) sign and the value to
be stored.
eg)spam=”hello”
eg) _spam=valid
total_$spam=invalid (reason-dollar sign is used)
Comments:
It is represented as #.
The hash is put in front of the loc to temporarily remove at while testing the program.
This is called commenting out of code and it can be useful when your program doesnt work.
You can even remove the # if you are ready to put back the line
Print function:
The print function displays the string value inside the parenthesis on the screen.
It calls the print function and string value is being passed to the print function.
Input function:
The input function waits for the user to type some text on the keyboard and press enter.
The function call evaluates to the string equal to the user’s text and the previous lines of code
assigns the MyName variable to the string value.
The function call evaluates to the string equal to the users text and the previous lines of code
assigns the myAge variable to the string value.
str(29)
print(‘i am’+str(29)+’yrs old’)
Chapter 2: Flow control
Flow control statement can decide which python instruction to execute on match
condition
If statement syntax:
eg)
a=15
b=30
if a>b:
print("a is greater")
elif(a==b):
print('a is equal to b')
else:
print('a is less than b')
Else keyword catches anything which isnt caught by the preceding conditions.
a=33
b=200
if(a>b)
Pass
While loop:
->1
2
3
4
5
Break:
Statement we can stop the loop even if the while condition is true
eg)i=1
while(i<6):
print(i)
if(i==3):
break;
i+=1
->1
2
3
Continue statement: we can stop the current iteration and continue with next
eg)i=0
while(i<6):
i+=1
if(i==3):
continue
print(i)
->1
2
4
5
6
Do while loop:
Do{
1(statement)
}while(condition)
spam=True
Spam
True
spam=TRUE||spam=true
->name error
Comparison operators: Compare two values and evaluates down to single boolean vale
Operator Meaning
== Equal to
!= Not equal
Boolean operators:
AND
OR
NOT
Are used to compare boolean values.
Binary boolean operators: the AND,OR operators always take two boolean values {expression}
so they are called binary operators.
AND :
0 0 False
0 1 False
1 0 False
1 1 True
OR:
0 0 False
0 1 True
1 0 True
1 1 True
NOT:
01
10
(1==2)or(2==3)
False and False
False
Flow control statements often start with a part called condition and all are followed by a block if
code called clause
Conditions:
condition s is a specific name with the context of flow control statements. Conditions always
evaluate to a boolean value.
A flow control statement decides what to do based on whether that condition is true or false and
almost every flow control statement uses a condition
Blocks of Code:
Lines of python code can be grouped into together in blocks,
When the block begins and ends from the indentation of the loc.
if (name=='mary'):
print('hello mary')
password=='sword fish'
print('access denied')
else:
print('wrong password')
Python OS module:
It provides for creating and removing a directory, gathering its contents, changing and
identifying the current directory etc.
import random
[Link]()
[Link](1,100)
[Link](1,100,2)
[Link]('computer')
number=[12,15,25,35,1,2]
[Link](number)
print(number)
The sys module provides function and variables used to manipulate different parts of the python
runtime environment.
Some of the important features of this module are
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]:
Functions:
When you call the len function you pass values called arguments in this context by typing them
within parenthesis.
When creating a function using the def statement you can specify what is the return value.
Should be within the return statement.
A return statement consists of the following:
1. The return keyword
2. The value or expression, that the function should return
Such as an expression is used within a return statement.
The return value is what this expression evaluates to.
import random
def getanswer(answernumber):
if(answernumber==1):
return 'it is certain'
if(answernumber==2):
return 'probably'
if(answernumber==3):
return 'most likely'
if(answernumber==4):
return 'uncertain'
if(answernumber==5):
return 'rarely'
if(answernumber==6):
return 'often'
if(answernumber==7):
return 'frequently'
if(answernumber==8):
return 'doubtful'
if(answernumber==9):
return 'try again'
v=[Link](1, 9)
fortune=getanswer(v)
print(fortune)
->rarely
None value(none,nil,undefined):
In python there is a value called none which represents the absence of value
print(“hello”)
print(“world”)
->hello
World
print(‘Hello’,end=’ ‘)
print(‘world’)
->Hello world
print(‘cats’,’dogs’,’mice’,sep=’,’)
->cats,dogs,mice
If two strings appear on separate lines because the print function automatically adds a new line
character to the end of string it is passed.
So you can set the keyword ‘end’ argument to change this to a different string.
When you pass multiple string values to print() it will automatically separate with a single space
You can replace the default separating string by passing the ‘sep’ keyword.
Local and global scope:
Parameters and variables that are assigned in a call function, are said to exist without local
scope
Module 2
Lists
Lists and tuples can contain multiple values which makes it easier to write programs that handle
large amount of data.
The term list value refers to the list itself, not the values inside the list values.
In the above example the string values are typed with quote characters to mark where the string
begins and ends, a list begins with an opening square bracket and ends with a closing square
bracket.
pam=['cat',1,'elephant']
print(spam[0])
->cat
print(['cat',1,'elephant'][2])
-> elephant
spam=['cat',1,'elephant']
print('Hello'+spam[0])
->Hellocat
spam=['cat','elephant'],['cow','apple']
print(spam[1][1])
->apple
spam=['cat','elephant','banana'],['cow','apple']
print(spam[0][-3])
->cat
As we get the index value from the list, a slice can get several values from a list in the form of a
new list.
A slice is typed between square brackets, like an index but it has two integers separated by a
colon.
The difference between index and slices
Index: spam[2]
Slice: spam[0:4]
print(len(spam))
->6
The len function will return the number of values that are in the list value passed to it. It can
count the number of characters in a string value.
spam=['cat','elephant','banana'],['cow','apple']
spam[0][2]='person'
print(spam)
spam=['cat','elephant','banana'],['cow','apple']
spam[0][2]=spam[0][1]
print(spam)
spam=['cat','elephant','banana'],['cow','apple']+[1,2,3],[4,5,6],[7,8,9],[10,11,12]
print(spam)
->(['cat', 'elephant', 'banana'], ['cow', 'apple', 1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12])
[1,2,3]*3
->[1, 2, 3, 1, 2, 3, 1, 2, 3]
spam=['cat','dog','rabbit']
del spam[0]
print(spam)
->['dog', 'rabbit']
[1,2,3,4]
spam=[1,2,3,4]
spam=’apple’
usn=[]
while True:
print('Enter the student name '+str(len(usn)+1)+ ' or please press enter key')
name=input()
if name=='':
break
usn+=[name]
print('The 5A student name')
for name in usn:
print(' '+name)
***********output************************
->Enter the student name 1 or please press enter key
person
Enter the student name 2 or please press enter key
Roger
Enter the student name 3 or please press enter key
**************************************************************
A for loop repeats the code block, once for each value in a list or list like value.
eg)
for i in range(5):
print(i)
-> 0
1
2
3
4
eg2) usn=[4,5,6,7]
for i in usn:
print(i)
->4
5
6
7
spam=['cat','dog','horse']
for i in range(len(spam)):
print('index '+ str(i)+'spam is '+spam[i])
-> True
spam=['cat','dog','horse']
print('owl' not in spam)
->True
mypets=['timmy','tommy','jimmy']
print("enter pet name")
name=input()
if name not in mypets:
print("i dont have a pet named "+ name)
else:
print(name+ 'is my pet')
tom
i dont have a pet named tom
timmy
Timmy is my pet
cat=['fat','black','loud']
size=cat[0]
color=cat[1]
disposition=cat[2]
size,color,disposition =cat
toy=['blue','wooden',5]
color=toy[0]
material=toy[1]
year=toy[2]
Augmented Assignment operator
When assigning a value to a variable we would use the variable itself.
eg)
spam=42
spam=spam+1
spam+=1
->43
spam=spam+1 spam+=1
spam=spam-1 spam-=1
spam=spam%1 spam%=1
spam=spam/1 spam/=1
spam=spam*1 spam*=1
The += operator can also do string and list concatenation, the *= can do string and list
replication
eg)spam='Hello'
spam+='world'
print(spam)
->Helloworld
spam='Hello'
spam+='world'
spam*=5
print(spam)
->HelloworldHelloworldHelloworldHelloworldHelloworld
Methods: A method is the same thing as a function except it is “called on” on a value.
● Each data type has its own set of methods.
● The method part comes after the value separated by a period.
● The list data type has several useful methods for:
● Finding
● Adding
● Removing
● Manipulating values in a list
spam=['hey','hi']
print([Link]('hi'))
-> 1
eg)spam=['cat','cow','dog']
[Link]('mouse')
print(spam)
● The append method call adds the argument to the end of the list.
● The insert method can insert a value at any index in the list.
eg)spam=['cat','cow','dog']
[Link](2,'mouse')
print(spam)
The remove method is passed the value to be removed from the list it is called on.
Attempting to delete a value that does not exist in the list will result in a value error.
If the value appears multiple times in a list, only the first instance of the value will be removed.
eg) spam=['cat','cow','mouse','dog']
[Link]('mouse')
print(spam)
eg2)spam=['cat','cow','mouse','cow','dog']
[Link]('cow')
print(spam)
List of number values or list of strings can be sorted with the sort method.
eg)spam=['ant','bear','mouse','cow','dog']
[Link]()
print(spam)
eg2)spam=[-2,10,2,-4,3]
[Link]()
print(spam)
eg3)spam=['ant','Ant','mouse','cow','dog']
[Link](reverse=True)
print(spam)
● If you pass true for the reverse keyword argument to have sort() sorts the values in
reverse order.
● If sort() uses ASCII order rather than actual alphabetical order for sorting strings it
means, Uppercase letters comes before lowercase letters.
● If you need to sort values in regular alphabetical order pass [Link] for the key keyword
argument in the sort method call.
eg)spam=['ant','Ant','mouse','cow','dog']
[Link](key=[Link])
print(spam)
eg)
import random
message=['it is certain',
'it is decidedly so',
'reply hazy try again',
'ask again later',
'concentrate and ask again',
'my reply is no',
'outlook not so good',
'very doubtful'
]
print(message[[Link](0,len(message)-1)])
eg) name='person'
print(name[0])
print(name[-1])
print(name[0:3]
->a
l
anm
eg2)name='person'
print('nm' in name)
-> True
eg3)name='person'
for i in range(len(name)):
print("**"+name[i]+"**")
->**a**
**n**
**m**
**o**
**l**
(or)
name='person'
for i in name:
print("**"+i+"**")
->**a**
**n**
**m**
**o**
**l**
Mutable Immutable
The list can have values added, removed or String cannot be [Link] proper way to
changed. A list value is mutable but it does mutate a string is to use slicing and
not change the values in the list when an concatenation to build a new string by
entirely new and different list value is copying from parts of the old string.
overwritten to the old list value.
eg)del name[:]
i=-1
while(i<2):
[Link](input())
i+=1
print(name)
->person
is
great
['person', 'is', 'great']
Tuple:
The tuple data type is identical to the list data type except in 2 ways:
tuples are typed with () instead of []
eg)
eggs=('hello',2,45)
print(len((eggs)))
->3
eg)eggs=('hello',2,45)
eggs[1]=99
Type ():
eg)eggs=('hello',2,45)
print(type(eggs))
-><class 'tuple'>
● If you have only one value in your tuple, it can be indicated by placing a trailing comma
after the value inside the (). Otherwise, python would think you have just typed the value
inside regular (). The comma in python indicates it as a tuple value.
eg)eggs=(2,)
print(type(eggs))
-><class 'tuple'>
eggs=(2)
print(type(eggs))
-><class 'int'>
The functions list and tuple will return list and tuple versions of the values passed to them.
eg)eggs=[2,3]
print(type(tuple(eggs)))
-><class 'tuple'>
eggs=(2,3)
print(type(list(eggs)))
-><class 'list'>
References:
i) pass by value
ii) pass by value
->42
100
spam=[0,1,2,3,4]
#When you create the list you are assigning a reference to it in the spam variable
cheese=spam
# it copies only the list reference in spam to cheese, not the list value itself. The values stored in
spam and cheese refer to the same list which means the list itself is actually copied.
cheese[1]='hello'
#when you modify the first element of cheese you are modifying the same list that refers to the
spam.
print(spam)
print(cheese)
->[0, 'hello', 2, 3, 4]
[0, 'hello', 2, 3, 4]
eg2)def eggs(a):
a=20
a=50
eggs(a)
print(a)
->50
import copy
a=[1,2,[4,5],3]
b=[Link](a)
b[2][1]=45
print(a)
print(b)
import copy
a=[1,2,[4,5],3]
b=[Link](a)
b[2][1]=45
print(a)
print(b)
Dictionaries:
A dictionary is a collection of many values.
A dictionary is typed with {} braces.
Indices for dictionaries can use many different data types. Indices for dictionaries are called
keys. And Key with its associated values is called key value pair
eg) cat={'size':'fat','color':'white','disposition':'loud'}
print(cat['size'])
->fat
cat={'size':'fat','color':'white','disposition':'loud'}
print("my cat is "+cat[1])
-> keyerror:1
Dictionaries vs lists:
eg)spam=['cat','dog','cow']
temp=['dog','cow','cat']
print(spam==temp)
spam={'name':'person','species':'human','age':21}
temp={'species':'human','age':21,'name':'person'}
print(spam==temp)
->False
True
eg2)spam=['cat','dog','cow']
temp=['cat','dog','cow']
print(spam==temp)
spam={'name':'person','species':'human','age':21}
temp={'species':'animal','age':21,'name':'person'}
print(spam==temp)
->True
False
There are three dictionary methods- keys, values and items that will return list like values of the
dictionary keys, values or both keys and values.
They cannot be modified and do not have an append method. These data types
(dict_key,dict_values,dict_items) can be used in for loops.
eg)
spam={'color':'red','age':42}
for k in [Link]():
print(k)
->color
age
eg2)spam={'color':'red','age':42}
for k in [Link]():
print(k)
->red
42
eg3)spam={'color':'red','age':42}
for k in [Link]():
print(k)
->('color', 'red')
('age', 42)
eg)spam={'color':'red','age':42}
print([Link]())
print([Link]())
print([Link]())
->dict_keys(['color', 'age'])
dict_items([('color', 'red'), ('age', 42)])
dict_values(['red', 42])
eg)spam={'color':'red','age':42}
print(list([Link]()))
print(list([Link]()))
print(list([Link]()))
->['color', 'age']
[('color', 'red'), ('age', 42)]
['red', 42]
Multiple assignment trick in a for loop to assign a key and value to separate variables
spam={'color':'red','age':42}
for k,v in [Link]():
print('features are key: '+k+' values: '+str(v))
->True
eg)spam={'color':'red','age':42}
print('texture' not in [Link]())
->True
eg)spam={'color':'red','age':42}
print('red' not in [Link]())
->False
get() method
Dictionaries have a get() method that takes 2 arguments: the key of the value to retrieve and a
fall back value to return if the key does not exist.
eg)items={'apple':10,'cups':5}
print('i am bringing '+str([Link]('cups',0))+' cups')
eg2)items={'apple':10,'cups':5}
print('i am bringing '+str([Link]('eggs',0))+' cups')
setdefault() method
The set default method offers a way to write the below line of code in a line.
eg)items={'apple':10,'cups':5}
if 'color' not in items:
items['color']='black'
print([Link]('color'))
->black
items={'apple':10,'cups':5}
[Link]('color','black')
print([Link]('color'))
->black
eg2)items={'apple':10,'cups':5}
[Link]('apple',15)
print([Link]('apple'))
->10
Program for counting the number of occurrences of each letter in a string using
setdefault() method.
->{'I': 1, 't': 1, ' ': 4, 'i': 2, 's': 1, 'a': 3, 'r': 1, 'n': 1, 'y': 2, 'd': 1}
Pretty printing
pprint()
pformat()
In your program import the module pprint, so that will have access to the pprint() and pformat()
functions. That will pretty print a dictionary’s values.
This is helpful when you want the clear display of items in a dictionary than what print provides.
eg)import pprint
message='It is a rainy day'
count={}
for character in message:
[Link](character,0)
count[character]+=1
[Link](count)
(or)
import pprint
message='It is a rainy day'
count={}
for character in message:
[Link](character,0)
count[character]+=1
print([Link](count))
->{' ': 4, 'I': 1, 'a': 3, 'd': 1, 'i': 2, 'n': 1, 'r': 1, 's': 1, 't': 1, 'y': 2}
import pprint
message='It is a rainy day'
count={}
for character in message:
[Link](character,0)
count[character]+=1
[Link](count,indent=3,width=20)
import pprint
board={'top-l':'','top-m':'','top-r':'','mid-l':'','mid-m':'','mid-r':'',
'low-l':'','low-m':'','low-r':''}
def print_board(board):
print(board['top-l']+' | '+board['top-m']+' | '+board['top-r'])
print('-+ -+ -')
print(board['mid-l']+' | '+board['mid-m']+' | '+board['mid-r'])
print('-+ -+ -')
print(board['low-l']+' | '+board['low-m']+' | '+board['low-r'])
print_board(board)
->
| |
-+ -+ -
| |
-+ -+ -
| |
board={'top-l':'','top-m':'','top-r':'','mid-l':'','mid-m':'','mid-r':'',
'low-l':'','low-m':'','low-r':''}
def print_board(board):
print(board['top-l']+' | '+board['top-m']+' | '+board['top-r'])
print('-+ -+ -')
print(board['mid-l']+' | '+board['mid-m']+' | '+board['mid-r'])
print('-+ -+ -')
print(board['low-l']+' | '+board['low-m']+' | '+board['low-r'])
turn='x'
for i in range(9):
print_board(board)
print('turn for '+ turn+ ' move on which space?')
move=input()
valid[i]=1
board[move]=turn
if (turn=='x' and valid[i]==0):
turn='o'
elif turn=='o' and valid[i]==0:
turn='x'
else:
print("invalid input")
print_board(board)
Practice
1. Explain if, else, else if , while, for, continue, break statements with example.(12)
2. Explain the data types with example. (int,float,string)
3. Explain math operators, boolean operators and comparison operators with
[Link] comparison and boolean operators.(only table)
4. Explain local and global scope in python programs with suitable examples(8)
5. Explain exception handling with example.(divide by zero)
6. Write the difference between list and dictionaries with example.
7. Explain references briefly
8. Explain the concept of slices
9. Briefly give explanation of the list methods
10. Explain tuple data type along with list() and tuple() function
11. Explain copy and deepcopy functions
12. Briefly explain hello world program and reset the program>explain all terms and user
defined functions
13. Briefly explain the methods of dictionary with examples
Manipulating Strings
eg)a=”person”
String literals:
a='a's'
print(a)
->syntax error
Double quotes:
Strings can begin and end with double quotes.
Benefits:
Using double quotes in a string can have a single quote character.
eg) a="a's"
print(a)
->a’s
Escape characters:
An Escape character allows to use characters that are impossible to use into a string.
It consists of a backslash ‘\’ followed by a character you want to add to the string.
For eg)
a='a\'s'
print(a)
->a’s
\’ Print ‘
\” Print “
\t Tab space
\n Line break
\\ Print \
eg)print("hi\nhow are you\nhello\ni\'m good\t\"i am going home\"\\outside")
->
hi
how are you
hello
i'm good "i am going home"\outside
Raw Strings:
A raw string completely ignores all escape characters and prints any backslash that appears in
the string.
You can place an ‘r’ before the beginning quotation mark of a string to make it a raw string.
Begins and and ends with either three single quotes or three double quotes. Any quotes, tab or
new lines in between the triple quotes are considered part of the string.
eg)print('''person is
here''')
print("""This
is weird""")
->
person is
here
This
is weird
Commenting:
The Hash character marks the beginning of comment for rest of line.
A multi line string is used for comments that span multiple lines.
spams=['a','b','c']
def spam():
'''alphabets
has been
written to print'''
print(spams)
spam()
Strings use indices and slices same as [Link] the string, each character in the string is an item
with the corresponding index.
eg)spam="person is great"
print(spam[4])
->l
Slicing
eg)spam="person is great"
print(spam[0:4])
->perso
The in and not in operator can be used with strings just like with list values. An Expression with
two strings join using in or not in will evaluate to a boolean true or false.
->False
upper()
lower()
isupper()
islower()
startswith()
endswith()
isx()
join()
split()
rjust()
ljust()
center()
strip()
rstrip()
lstrip()
Upper and lower string method returns a new string where all the letters in the original string
have been converted to uppercase or lowercase
eg)spam="hello"
print([Link]())
print([Link]())
o/p:
HELLO
hello
eg)
print("how r u")
feeling=input()
if [Link]()=='great':
print('i feel great too')
else:
print('i hope the rest of the day is good')
->how r u
GreaT
i feel great too
eg2)
print("how r u")
feeling=input()
if [Link]()=='GREAT':
print('i feel great too')
else:
print('i hope the rest of the day is good')
->how r u
great
i feel great too
Isupper and islower methods will return a boolean true or false values.
Boolean true value will be returned if the string has at least one letter and all the letters are
uppercase or lowercase respectively otherwise the method returns false.
eg)
spam="hello world"
print([Link]())
print([Link]())
print('HELLO'.isupper())
print('abc'.islower())
print('12345'.isupper())
print('abc132'.islower())
->
False
True
True
True
False
True
eg2)
name='person'
print([Link]().lower().upper())
->person
The isx
Returns a boolean value which describes the nature of the string. Some common isx string
methods are isalpha()- returns true if the string consists only of letters and have blank spaces.
isalnum:
Returns true if string consists of only letters and numbers and is not blank.
is decimal:
Returns true if string consists only of numeric characters and not blank.
isspace(): returns true if the string consists only of spaces, tabs, newlines and is not blank.
Istitle():
Returns true if the string consists only of words that begin with an uppercase letter followed by
only lowercase letters.
eg)
print('hello'.isalpha())
print('hel123'.isalpha())
print('hel123'.isalnum())
print('hello'.isalnum())
print(''.isalnum())
print('hello'.isdecimal())
print('123'.isdecimal())
print('hello '.isspace())
print(' '.isspace())
print('This Is Title'.istitle())
print('This is Title'.istitle())
->
True
False
True
True
False
False
True
False
True
True
False
eg)
while True:
print('enter your age')
age=input()
if [Link]():
break
print('please enter a number for your age')
while True:
print('select a new password')
password=input()
if [Link]():
break
print('password can only have letters and numbers')
->
enter your age
bla
please enter a number for your age
enter your age
30
select a new password
avm
Startswith():
If the string value starts with and ends with returns true if the string value they are called on
begins or ends with the string passed to the method, otherwise they return false.
eg)
print('hi hello world'.startswith('hello'))
->False
The join method is useful when you have a list of strings that need to be joined together into a
single string value.
The join method is called on a string, gets passed a list of strings, and returns a string. The
returned string is the concatenation of each string in the passed in list.
eg)print('abc'.join(['cats','rats','bats']))
->catsabcratsabcbats
The split method is called on a string value and returns a list of strings.
print('cats rats bats'.split())
The rjust and ljust methods return the padded version of the string they are called on with
spaces inserted to justify the string. The first augment to both methods is an integer length for
the justified string, the second method is optional which will specify a fill character other than a
space character.
eg)print('hello'.rjust(40))
print('hello'.ljust(10,'*'))
->
hello
hello*****
eg)print('hello'.rjust(40))
print('hello'.center(10,'*'))
->
hello
**hello***
The strip string method return a new string without any whitespace characters at the beginning
or end.
The lstrip and rstrip methods will remove whitespace characters from the left and right ends
->
->BaconSpamEggs
The pyperclip module has copy and paste functions that can send text to and receive text from
your computers clipboard.
Sending the output of the clipboard will make it easy to email, to a word processor or other
software.
To install pyper clip in the command prompt type pip install pyperclip
Password locker:
The password locker is a system where you have an account and a password for the account.
Generally, we have to remember the password for the account or we would the the same
password for different accounts because we need to forget it or any of the sites has a security
breach or the hackers will learn the passwords of all other accounts.
The password manager program is an insecure program which is basically used for the
demonstration how such program works
import sys,pyperclip
if len([Link])<2:
print('usage:py [Link] [account] - copy account password')
[Link]()
account=[Link][1]
password={'Email':'awdku@[Link]', 'blog':'awdh','luggage':2342}
if account in password:
[Link](password[account])
print('password for '+account+'copies to clipboard')
import pyperclip
text=[Link]()
lines=[Link]('\n')
for i in range(len(lines)):
lines[i]='@'+lines[i]
text='\n'.join(lines)
[Link](text)
->
@av
@d
@d
@d
@v
Regular expressions will allow you to specify a pattern of text to search for.
->415-555-6555
True
person is a phonenumber
False
A regular expression is a special sequence of characters that helps you match to find other
strings using a specialized syntax held in a pattern.
The python module RE provides full support for pearl like regular expressions in python.
The RE module raises the exception [Link]. If an error occurs while compiling or using a
regular expression
There are various characters which would have special meaning when they are used in RE.
To avoid any confusion while dealing with RE, we would use raw strings as r’expression’
Import re
[Link](r’\d\d\d-\d\d\d-\d\d\d\d’)
A regex objects search() method searches the string it is passed for any matches to the regex.
The search method will return none if the regex pattern is not found in the string. If the pattern is
found, returns a match object.
Match objects have a group method that will return the actual matched text from the searched
string
eg)import re
phonenumber=[Link](r'\d\d\d-\d\d\d-\d\d\d\d')
m=[Link]('my number is 123-456-3333')
print('phone number found: '+[Link]())
import re
phonenumber=[Link](r'\d\d\d-\d\d\d-\d\d\d\d')
m=[Link]('my number is 1223-456-33533')
print('phone number found: '+[Link]())
->
1: phone number found: 123
2: phone number found: 456
0: phone number found: 123-456-3333
If you would like to retrieve all groups at once use the groups() method.
eg)
import re
phonenumber=[Link](r'(\d\d\d)-(\d\d\d)-(\d\d\d\d)')
m=[Link]('my number is 123-456-3333')
print([Link]())
| is called pipe. It can be used anywhere you want to match one or many expressions.
The first occurrence of matching text will be returned as the match object.
Sometimes there is a pattern you want to match only optionally that is the regex would find the
match whether or not the bit of text is there, the question mark character flags the group that
receives optional part of the program.
eg)
import re
h=[Link](r'Bat(wo)?man')
m=[Link]('The adventures of Batwoman')
print([Link]())
->
Batman
->
Batwoman
import re
h=[Link](r'Bat(wo)+man')
m=[Link]('The adventures of Batwowoman')
print([Link]())
->
Batwowoman
The * means match zero or more the group that precedes the * can occur any number of times
in a text. It can be completely absent or repeated over and over again
import re
h=[Link](r'Bat(wo)+man')
m=[Link]('The adventures of Batwowoman')
print([Link]())
->
Batwowoman
If you have a group that you want to repeat a specific number of times follow the group in your
regex with a number in {}
Greedy and non greedy matching:
Python regular expressions are greedy by default which meas that in ambiguous situations they
will match the longest string possible.
The non greedy version of the curly braces which matches the shortest string possible has the
closing curly braces followed by a question mark.
eg)
import re
h=[Link](r'(Ha){3,5}?')
m=[Link]('HaHaHaHaHa')
print([Link]())
->
HaHaHa
Find all will not return a match object but a list of strings- as long as there are no groups in the
RE
eg)
import re
h=[Link](r'\d\d\d-\d\d\d-\d\d\d\d')
m=[Link]('My number is 123-455-5555 call me ar 155-666-7777')
print(m)
->['123-455-5555', '155-666-7777']
Character classes:
import re
h=[Link](r'\d\s\w')
m=[Link]('10 apples15 dolls 25 toys')
print(m)
import re
h=[Link](r'\d+\s\w+')
m=[Link]('10 apples15 dolls 25 toys')
print(m)
import re
h=[Link](r'\w+\s\d+')
m=[Link]('10 apples15 dolls 25 toys')
print(m)
->['dolls 25']
import re
h=[Link](r'\D\S\W ')
m=[Link]('10 apples15 dolls 25 toys')
print(m)
->[]
import re
h=[Link](r'\D+\S\W')
m=[Link]('10 apples 15 dolls 25 toys')
print(m)
Sometimes you want to match a set of characters but the short hand character classes are too
broad. We can define our own character class using [].
import re
h=[Link](r'[aeiouAEIOU]')
m=[Link]('I like Ice creams')
print(m)
import re
h=[Link](r'[^aeiouAEIOU]')
m=[Link]('I like Ice creams')
print(m)
->[' ', 'l', 'k', ' ', 'c', ' ', 'c', 'r', 'm', 's']
By placing a caret character just after the character class opening braces, you can make a
negative character class.
A negative character class will match all the characters that are not in the character class.
The caret symbol is used at the start of the regex to indicate that a match must occur at the
beginning of the search text
The dollar sign is used at the end of the regex to indicate that the string must end with this regex
pattern.
The caret and dollar together indicate that the entire string must match the regex- that is its not
enough for a match to be made on some subset of the string.
import re
h=[Link](r'^Hello')
m=[Link]('Hello world')
print(m)
import re
h=[Link](r'^Hello')
m=[Link]('world Hello')
print(m)
->None
import re
h=[Link](r'^Hello')
m=[Link]('Hello world')==None
print(m)
->False
The dot character in the regular expression is called a wild card and will match any character
except for a new line.
eg)
import re
s=[Link](r'.at')
print([Link]('the cat in the hat sat on the flat mat'))
The (.) character means any single character except the new line
The (*) character means zero or more of the preceding character.
eg)
import re
s=[Link](r'first name:(.*)last name:(.*)')
m=[Link]('first name:AI last name:Swiggy')
print([Link](1))
->AI
Otherwise
The .* will match everything except a new line. By passing [Link] as the 2nd argument to
[Link], you can make the . character to match all characters including new line character
eg) import re
s=[Link](r'.*',[Link])
m=[Link]('serve the public \n protest innocent \n uphold law')
print([Link]())
To make your regex Case insensitive you can pass [Link] or re.I as a second
argument to [Link]()
eg)
import re
s=[Link](r'Serve',re.I)
m=[Link]('serve the public \n protest innocent \n uphold law')
print([Link]())
->serve
Re cannot only find text patterns but can also substitute new text in place of those patterns.
The sub method for regex objects is passed two arguments:
eg)
import re
s=[Link](r'serve')
m=[Link]('people','serve to the nation')
print(m)
->
people to the nation
eg)
import re
s=[Link](r'serve \w+')
m=[Link]('people','serve to the nation serve others')
print(m)
eg)
import re
s=[Link](r'''
(\d){3}|\(\d{3}\)?
(\s|-|\.)?
\d{3}
(\s|-|\.}
\d{4}
(\s*(ext|x|ext)\s*\d{2,5})?
)''',[Link])
n=[Link]('134-555-3333')
print([Link]())
->134
Reading and writing files
C:\
User
person
On windows paths are written using \ as the separator between folder name
If you want your programs to work on all os u have to write python scripts to handle both cases.
This can be done using [Link] function
If you pass the string values of individual file and folder names in your path [Link], it will
return a string with a file path using the correct path separators.
Any filename or paths that do not begin with a root folder are assumed to be under the current
working directory.
You can get the current working directory as a string value with the [Link]
[Link]()
'/mnt/c/Users/person'
[Link] module:
Contains many functions related to filenames and file paths
[Link] is a module inside the os module which can be imported from import os
The os,path module provides functions for returning the absolute path of a relative path and for
checking whether a given path is an absolute path
[Link](path): it will return True if the argument is absolute path and false otherwise
[Link](path,start): It will return a string of a relative path from the start path to path. If
start is not provided the current working directory is used as path
>>> import os
>>> print([Link]('.'))
/mnt/c/Users/person
>>> print([Link]('Users/person'))
False
>>> print([Link]('/mnt/c/Users/person'))
True
>>> [Link]('c://qpython','/mnt/d://')
'../c:/qpython'
Directory name: will return a string of everything that comes before the last slash in the path
argument.
Base name: it will return a string of everything that comes after the last slash in path argument
eg)
>>> path="/mnt/c/Users/person/[Link]"
>>> [Link](path)
'[Link]'
[Link]():
iF you need directory and path name together you can call [Link] to get a tuple value with
these two strings.
eg)
>>> [Link](path)
('/mnt/c/Users/person', '[Link]')
eg)
>>> [Link](path),[Link](path)
('/mnt/c/Users/person', '[Link]')
sep():
[Link] variable is sep to the correct folder separating slash for the computer running program
>>> [Link]([Link])
['', 'mnt', 'c', 'Users', 'person', '[Link]']
The [Link] module provides functions for finding the size of a file in bytes. And files and folders
inside a given folder.
[Link](path)- Returns the size in bytes of the file in the path argument
>>> [Link]('/mnt/c/Users/person/[Link]')
8785
[Link](path)
It will return a list of file name, strings for each file in the path argument.
>>> [Link]('/mnt/c/Users/person/')
['$', '.acquia', '.android', '.AndroidStudio4.0', '.atom', '.bashrc', '.bash_history', '.bash_profile',
'.conda', '.condarc', '.config', '.drush', '.fontconfig', '.git', '.gitconfig', '.gitignore', '.gradle',
'.ipynb_checkpoints', '.ipython', '.jupyter']
The [Link] provides function to check whether a given path exists and whether it is a
file or folder
>>> [Link](path)
True
Will return true if the file or folder referred to in the argument exists and will return false if it
doesn't exists.
>>> [Link](path)
True
Returns true if the path argument exists and is a file and false otherwise
>>> [Link](path)
False
Will return true if the path argument exists and is a folder and false otherwise.
Opening files with the open(): to open a file with open(, you have to pass a string path indicating
the file you want to open, it can be either absolute path or relative path. The open function
returns a file object.
Hello
Writing files:
>>> print([Link]('ellooo\n'))
7
You can save the variable to binary shelve files using the shelve module. So that your program
can restore data to variables from the hard drive.
The shelve module will allow to add, save and open features to your program.
eg)
>>> import shelve
>>> s=[Link]('mydata')
>>> cats=['zophie','person','simon']
>>> s['cats']=cats
>>> [Link]()
>>> cats=['zophie','person','simon']
>>> s['cats']=cats
>>> list([Link]())
['cats']
>>> list([Link]())
[['zophie', 'person', 'simon']]
Pprint:
The [Link] function will pretty print the contents of a list or dictionary on the screen while
the [Link] function will return the same text as a string instead of printing it.
import pprint
import shelve
cats=[{'name':'xophie','desc':'fluffy'},{'name':'piku','desc':'donkey'}]
print([Link](cats))
f=open(('[Link]'),'w')
print([Link]('cats= ' + [Link](cats)+'\n'))
[Link]()
->
[{'desc': 'fluffy', 'name': 'xophie'}, {'desc': 'donkey', 'name': 'piku'}]
81
Organizing files:
Shutil module
Or shell utilities has functions which allows you to copy, move,rename and delete files in your
python program
To use the shutil module you need to use import shutil
Copying files and folders: the shutil module provides functions for copying files as well as entire
folders
[Link](source,destination): will copy the file at the path source to the folder at the path
destination
If destination is a filename it will be used as the new name of the copied file.
import shutil,os
[Link]('d:\\')
print([Link]('d:\\[Link]','d"\\delicious'))
[Link](source,destination): will move the file or folder at the path source to the path
destination and will return a string of the absolute path of the new location
import shutil
print([Link]('d:\\hi,txt','d:\\bacon'))
We can delete a single file or a single empty folder with functions in os [Link] to
delete a folder and all of its contents use the sutil module.
Import os
For filename in [Link]():
If [Link](‘.rxt’):
[Link](filename)
print(filename)
[Link] function irreversibly deletes files and folders which are dangerous to use. To
delete files and folders which are with third path we can use send2trash module.
Import send2trash
b=open(’[Link],’a’)
[Link](‘Bacon is not a vegetable’)
[Link]()
send2trash.send2trash(‘[Link]’)
The [Link]() is passed as a single string value, which returns list of strings for the subfolder
and filename variables.
Import os
For [Link] in [Link](‘c:\\delicious’):
print(‘the current folder is ‘ +folder)
For subfolder in subfolders:
print(‘subfolder of ‘ + folder + ‘: ‘ +subfolder)
For file in files:
print(‘file inside’ + folder+ ‘:’ +files)
print(‘ ‘)
Zipfiles can hold the compressed contents of many other files. The zipfiles are saved using .xip
file ex.
Zip file can also contain multiple files and subfolders where it can be made as a package into
one. This single file is called an archive which can be attached to an email. The python program
can create and open zip files using functions in the zip file module.
Reading zip files: to read the contents of a zip file you must create a ZipFile object which is
similar to the open function.
To create a zip file object [Link]() - .zip, files, filename must be passed as a string
import zipfile,os
[Link]("c:/Users/person/Desktop/mavenai")
newzip=[Link]("DP SET(Minor)(12) person_(1).zip")
print([Link]())
info=[Link]('DP SET(Minor)(12) person_(1)/[Link]')
print(info.file_size)
print(info.compress_size)
Extracting from zip files: The extractall method for ZipFile objects , extracts all the files and
folders from a zipfile into the current working directory
To create your own zipfile, you must open the ZipFile object in write mode, by passing w as the
second argument
When you pass the path to the write method of a ZipFile object, python will compress the file at
that particular path and adds into the zipfile
The write methods 1st argument is a string of the file name to add
The 2nd argument is the compression type parameter, which tells the computer what algorithm
should be used to compress the files.
import zipfile
n=[Link]('[Link]','w')
[Link]('[Link]',compress_type =zipfile.ZIP_DEFLATED)
[Link]()
Assertions: an assertion is a sanity check to make sure your code isnt doing something wrong.
The sanity checks are performed by assert statements
If the sanity check fails then an assertion error exception is raised.
The assert statement consists of the following:
1. Assert keyword
2. Condition
3. Comma
4. String to display when the condition is false
Using an assertion in a traffic light simulation:
market_2nd={'ns':'green','ew':'red'}
mission_16th={'ns':'red','ew':'green'}
def switchLisghts(stoplight):
for key in [Link]():
if stoplight[key]=='green':
stoplight[key]='yellow'
elif stoplight[key]=='yellow':
stoplight[key]='red'
elif stoplight[key]=='red':
stoplight[key]='green'
switchLights(market_2nd)
assert 'red' in [Link](),'neither light is red'+str(stoplight)
Disabling assertions:
Assertions can be disabled by passing the -O option when running python code
Q:
1. String manipulation functions
2. String literal
3. Trim whitespace characters
4. Write a program name print table that takes a list of lists of strings and displays it in well
organised table with each column right [Link] that all inner lists contain the
same number of strings
tabledata=[['aples','oranges','cherries','banana'],
['alice','mary','david'],
['dog','cat','cow']]
output:
apples alice dog
oranges mary cat
cherries david cow
banana
Raising exceptions
Python raises an exception whenever it tries to execute invalid code.
Exceptions are raised with a raise statement
A raise statement consists of the following:
def boxprint(symbol,width,height):
if len(symbol)!=1:
raise Exception('symbol must be a single character string')
if width<=2:
raise Exception('width must be greater than 2')
if height<=2:
raise Exception('Height must be greater than 2')
print(symbol*width)
for i in range(height-2):
print(symbol+(' '*(width-2))+symbol)
print(symbol*width)
for s,w,h in (('*',4,4),('o',20,5),('x',1,3),('22',3,3)):
try:
boxprint(s,w,h)
except Exception as err:
print('An exception found' + str(err))
->
****
* *
****
* *
****
oooooooooooooooooooo
o o
oooooooooooooooooooo
o o
oooooooooooooooooooo
o o
oooooooooooooooooooo
An exception foundwidth must be greater than 2
An exception foundsymbol must be a single character string
When python encounters an error it produces a list of error information called the
traceback
The traceback includes the error message, the line number of error and the sequence of
function calls that led to the [Link] sequence of calls is called the call stack.
Logging:
Logging is a way to understand what is happening in the program and in what order it is
happening.
Python uses logging module to create a record of custom messages that you write.
import logging
[Link](level=[Link],format='%(asctime)s- %(message)s')
[Link]('start of program')
def factorial(n):
[Link]('start of factorial(%s)' %(n))
total=1
for i in range(1,n+1):
total*=i
[Link]('i is '+ str(i)+',total is '+str(total))
[Link]('end of factorial(%s)'%(n))
return total
print(factorial(5))
[Link]('end of program')
->
2022-01-05 13:58:24,373- start of program
2022-01-05 13:58:24,375- start of factorial(5)
2022-01-05 13:58:24,376- i is 1,total is 1
2022-01-05 13:58:24,377- i is 2,total is 2
2022-01-05 13:58:24,377- i is 3,total is 6
2022-01-05 13:58:24,379- i is 4,total is 24
2022-01-05 13:58:24,380- i is 5,total is 120
2022-01-05 13:58:24,380- end of factorial(5)
2022-01-05 13:58:24,381- end of program
120
Logging levels:
DEBUG: [Link]() the lowest [Link] for small [Link] you care
about these messages only when diagnosing problems
ERROR [Link]() used to record an error that caused the program to fail to
do something.
CRITICAL [Link]() the highest level. Used to indicate a fatal error that has
caused or is about to cause the program to stop running entirely.
IDLE debugger:
The debugger is a feature of IDLE which allows you to execute your program one line at a time
In the debug control window, select all four of the stack locus source globals checkboxes so that
the window shows the set of debug information
The program will stay paused until you press one of the five buttons in the debug control
window.
Go- The program will execute normally until it terminates or reaches a breakpoint
Over- executes the next line of code if the code is a function call, the over button will sep over
the code in the function.
Out- it will execute the loc at full speed until it returns from the current function.
Breakpoints:
A breakpoint can be set on a specific line of code and forces the debugger to cause whenever
the program execution reaches the line
Mod 5
Web Scraping
Web scraping is the rem for using the program to download and process content from the web
The open function will open the web pageof the specified url
import webbrowser,sys,pyperclip
if len([Link])>1:
address=''.join([Link][1:])
else:
address=[Link]()
[Link]('[Link]
The request module allows you to download files from the web without worrying about
complicated issues such as network errors,data compression and connection problems
The [Link]() takes a string of string as arg by calling type on [Link]() returns values
as response object which contains response of web server which you had requested.
import requests
res=[Link]('[Link]
print(type(res))
print(res.status_code==[Link])
print(len([Link]))
print([Link][:200])
<class '[Link]'>
True
179380
The Project Gutenberg EBook of Romeo and Juliet, by William Shakespeare
*******************************************************************
THIS EBOOK WAS ONE OF PROJECT GUTENBERG'S EARLY FILES
import requests
res=[Link]('[Link]
res.raise_for_status()
We can save webpage on the hard drive using the standard open function and write method.
Open the file in write binary mode by passing the string wb as 2nd argument to open function
import requests
res=[Link]('[Link]
res.raise_for_status()
playFile=open('[Link]','wb')
for i in res.iter_content(100000):
print([Link](i))
->100000
79382
HTML:
Hypertext markup language is the format that web pages are written.
view-source:[Link]
Hello will be in bold by telling the browser where the end of the bold text is.
A href is a hypertext reference to the given url that the text links to using the href attribute
<a href=”[Link]
The source of web page can be seen by selecting view source or view page source by right
click on web page in your web browser to see the html text of a page.
eg)
<!doctype html>
<html dir="ltr" lang="en">
<head>
<meta charset="utf-8">
<title>New Tab</title>
<style>
body {
background: #353535;
margin: 0;
}
#backgroundImage {
border: none;
height: 100%;
pointer-events: none;
position: fixed;
top: 0;
visibility: hidden;
width: 100%;
}
[show-background-image] #backgroundImage {
visibility: visible;
}
</style>
</head>
<body>
<iframe id="backgroundImage" src=""></iframe>
<ntp-app></ntp-app>
<script type="module" src="new_tab_page.js"></script>
<link rel="stylesheet" href="chrome://resources/css/text_defaults_md.css">
<link rel="stylesheet" href="shared_vars.css">
</body>
</html>
In chrome, internet explorer the developer tools are already installed and it can be viewed by
pressing f12
import openpyxl
path=r'C:/Users/person/Desktop/[Link]'
wb=openpyxl.load_workbook(path)
print(type(wb))
-><class '[Link]'>
You can get list of all sheets from workbook by calling the get_sheet_names() function
import openpyxl
path=r'C:/Users/person/Desktop/[Link]'
wb=openpyxl.load_workbook(path)
print(wb.get_sheet_names())
->['Sheet1']
import openpyxl
path=r'C:/Users/person/Desktop/[Link]'
wb=openpyxl.load_workbook(path)
sheet=wb.get_sheet_by_name('Sheet1')
print([Link])
-> Sheet1
THe cell object has a value attribute that contains the value stored in a cell
cell object has row, column,coordinate attributes that provides location , information of cell
import openpyxl
path=r'C:/Users/person/Desktop/[Link]'
wb=openpyxl.load_workbook(path)
sheet=wb.get_sheet_by_name('Sheet1')
print(sheet['A1'].value)
->ftythf
import openpyxl
path=r'C:/Users/person/Desktop/[Link]'
wb=openpyxl.load_workbook(path)
sheet=wb.get_sheet_by_name('Sheet1')
a=sheet['A1']
print('row '+str([Link])+ ' col '+ str([Link])+ ' is '+ [Link])
-><class 'int'>
row 1 col 1 is ftythf