[Go to site: main page, start]

0% found this document useful (0 votes)
1 views94 pages

Code Examples Python

The document provides a comprehensive overview of flow control statements in both C/C++ and Python, detailing various types of conditional statements, loops, and operators. It includes syntax examples and explanations for 'if', 'switch', 'goto', and loop statements in C/C++, as well as 'if', 'else', 'elif', 'while', and 'for' loops in Python. Additionally, it presents several Python programming assignments demonstrating practical applications of these concepts.

Uploaded by

Anmol munnolli
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views94 pages

Code Examples Python

The document provides a comprehensive overview of flow control statements in both C/C++ and Python, detailing various types of conditional statements, loops, and operators. It includes syntax examples and explanations for 'if', 'switch', 'goto', and loop statements in C/C++, as well as 'if', 'else', 'elif', 'while', and 'for' loops in Python. Additionally, it presents several Python programming assignments demonstrating practical applications of these concepts.

Uploaded by

Anmol munnolli
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Assignment-1

Flow Control statements in c/c++:

1. If Statements

Enables the programmer to choose a set of instructions, based on a condition. When


the condition is evaluated to true, a set of instructions will be executed and a different
set of instructions will be executed when the condition is evaluated to false. We have 4
types of if Statement which are:
1. If..else
2. Nested if
3. Else if ladder
4. Simple if or null else
5. Null else or Simple else
● If…else Statement
In this statement, there are two types of statements execute. First, if the condition is true first
statement will execute if the condition is false second condition will be executed.
Syntax:
If(condition)
{
Statement(s);
}
else
{
Statement(s)
}
Statement
● Nested if
If the condition is evaluated to true in the first if statement, then the condition in the second if
statement is evaluated and so on.
Syntax:
If(condition)
{
If(condition)
{
Statement(s);
}
Else
{
Statement(s)
}
}
● else if Ladder
The corresponding array of instructions is executed when the first condition is correct. If the
condition is incorrect, the next condition will be verified. If all the specifications fail, the default
block statements will be executed. The remainder of the ladder can be shown as shown below.
Syntax:
If(condition)
{
Statement(s);
}
Else if(condition)
{
Statement(s);
}
else if(condition)
{
Statement(s)
}

Else
{
Statement(s)
}
Statement(s);
● Null else or Simple else
If the programmer can execute or skip a set of instructions based on the condition value. The
simple one-way statement is selected. A set of statements is carried out if the condition is true.
If the condition is false, the control will proceed with the following declaration after the if
declaration. Simple else statement:
Syntax:
If(condition)
{
Statement(s);
}
Statement(s);
2. Switch Statement
C offers a selection statement in several ways as if the program becomes less readable when
the number of conditions increases. C has a multi-way selection statement called the switch
statement that is easy to understand to resolve this problem. The switch declaration is easy to
understand if more than 3 alternatives exist. The command switches between the blocks based
on the expression value. Each block will have a corresponding value.
Syntax:
Switch(expression)
{
Case label1:
Statement(S);
Break;
Case label2:
Statement(S);
Break;
Case label3;
Statement(s);
Break;
….
Case labelN:
Statement(s);
Break;
Default:
Statement(s);
Break;
}

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.

else statement always consists of the following:


The else keyword
A colon Starting on the next line,
an indented block of code (called the else clause)

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.')

Output: You are not Alice, kiddo.


while Loop Statements:

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.

a while statement always consists of the following:


The while 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 while clause)

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

for Loops and the range() Function

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:

Assignment-3 python programs:

[Link] Python program that accepts principle, rate of interest, time and compute
the simple interest.

p = float(input("Enter principal: "))


r = float(input("Enter rate: "))
t = float(input("Enter time: "))
si = p * r * t / 100
print("Simple Interest =", si)

Output:
Enter principal: 10
Enter rate: 10
Enter time: 2
Simple Interest = 2.0

2.· Write Python program to display palindrome numbers in a given range.

maximum = int(input(" Please Enter the Maximum Value : "))


print("Palindrome Numbers between 1 and %d are : " %(maximum))
for num in range(1, maximum + 1):
temp = num
reverse = 0

while(temp > 0):


Reminder = temp % 10
reverse = (reverse * 10) + Reminder
temp = temp //10
if(num == reverse):
print("%d " %num, end = ' ')

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

[Link] python program to check if number is odd or even.


num = int(input("Enter a number: "))
if (num % 2) == 0:
print("{0} is Even".format(num))
else:
print("{0} is Odd".format(num))
Output:
Enter a number: 12
12 is Even

[Link] a Python program to convert Decimal number to Binary number.

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 Check_Vow(string, vowels):


final = [each for each in string if each in vowels]
print(len(final))
print(final)
string = input()
vowels = "AaEeIiOoUu"
Check_Vow(string, vowels)
Output:
person
2
['a', 'o']
6. Write Python program that accepts a distance in centimeters and prints the
corresponding value in feet and inches

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.

sentence = input("Enter sentence: ")


longest = max([Link](), key=len)
print("Longest word is: ", longest)
print("And its length is: ", len(longest))
Output:
Enter sentence: banana is a fruit
Longest word is: banana
And its length is: 6

[Link] a function to print out a blank tic-tac-toe board.

board = [' ' for x in range(10)]


def printBoard(board):
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
printBoard(board)
Output:

| |
| |
| |
-----------
| |
| |
| |
-----------
| |
| |
| |

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] = []

def add(self, dataval):


if dataval not in [Link]:
[Link](dataval)
return True
else:
return False
def remove(self):
if len([Link]) <= 0:
return ("No element in the Stack")
else:
return [Link]()
AStack = Stack()
[Link]("Mon")
[Link]("Tue")
[Link]("Wed")
[Link]("Thu")
print([Link]())
print([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

[Link] Python program to find sum of first n natural numbers.


num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
sum = 0
while(num > 0):
sum += num
num -= 1
print("The sum is",sum)
Output:
Enter a number: 3
The sum is 6
14.· Write a Python program to find factorial of a given number.
num = int(input())
factorial = 1
if num < 0:
print("factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Output:
5
The factorial of 5 is 120
[Link] Python program to check if given number is Armstrong or not (Ex: 153 =
1^3 + 5^3 + 3^3, therefore 153 is Armstrong number).
num = int(input("Enter a number: "))
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
Output:
Enter a number: 153
153 is an Armstrong number
16.· Define a Python function with suitable parameters to generate first N
Fibonacci numbers. The first two Fibonacci numbers are 0 and 1 and the
Fibonacci sequence is defined as a function F as . Write a Python program which
accepts a value for N (where N>0) as input and pass this value to the function.
Display suitable error message if the condition for input value is not followed.
def Fibonacci(n):
if n < 0:
print("Incorrect input")
elif n == 0:
return 0
elif n == 1 or n == 2:
return 1
else:
return Fibonacci(n-1) + Fibonacci(n-2)
print(Fibonacci(int(input())))
Output:
6
8
17.· Write a Python program to accept n names and display the sorted name
alphabetical order.
my_str = input()
words = [[Link]() for word in my_str.split()]
[Link]()
print("The sorted words are:")
for word in words:
print(word)
Output:
hi im person
The sorted words are:
person
hi
Im
[Link] are creating a fantasy video game. The data structure to model the player’s inventory
will be a dictionary where the keys are string values describing the item in the inventory and
the value is an integer value detailing how many of that item the player has. For example, the
dictionary value {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} means the player
has 1 rope, 6 torches, 42 gold coins, and so on. Write a function named displayInventory()
that would take any possible “inventory” and display it like the following inventory: 12 arrow,
42 gold coin, 1 rope, 6 torch, 1 dagger Total number of items: 63.
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def display_inventory(inventory):
total_items = 0
print ("Inventory:")
for item in inventory:
print(str(inventory[item]) + ' ' + item)
total_items += inventory[item]
print("Total number of items: " + str(total_items))
if __name__ == '__main__':
display_inventory(stuff)
Output:
Inventory:
1 rope
6 torch
42 gold coin
1 dagger
12 arrow
Total number of items: 62
person nameolli
numberIS013
Python Notes

Module 1

Python is a programming language which has a wide range of syntactic constructions, standard
library functions and interactive development and env features.

Entering expressions into the interactive shell

● Run the interactive shell by launching the IDLE

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.

Math operators from highest to lowest precedence:


Operator Operation Example Evaluates to

** exponent 2**3 8

% modulus 22%8 6

// Integer 22//8 2
division/floored
quotient

/ Division 22/8 2.75

* Multiplication 3*5 15

- Subtraction 5-2 3

+ Addition 2+2 4

The integer, floating point and string data types

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’

String Concatenation and replication:


String concatenation: When the plus operator is used on two string values , it joins the strings as
the string concatenation operator.

When the operator is used on one string value and one integer value it comes the string
replication operator

eg)print('alice'*5)

->alicealicealicealicealice

String value and variables:

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”

Rules for variable names:

● It can be only one word


● It can use only letters, numbers and underscore characters

eg) _spam=valid
total_$spam=invalid (reason-dollar sign is used)

Comments:

It is represented as #.

The # marker is called hash.

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.

When python executes print(“Hello”)

It calls the print function and string value is being passed to the print function.

A value that is passed to the function is called an argument.

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.

printing the user name:

The call to print function contains the expression

print(‘it is good to meet you'+myName’)


Length function (len()): the length is passed to a string value [len(MyName)] or a variable
containing a string
The function evaluates to the Integer value of the number of characters in that string.

The str(), int(), float()

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:

It is written by using if keyword

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.

Nested if can have if statement inside if statement


Pass if statements cannot be empty but if you for some reason have an if statement with no
content
put in the pass statement to avoid error

a=33
b=200
if(a>b)
Pass

While loop:

It can execute the statements till the condition is true


eg)i=1
while(i<6):
print(i)
i+=1

->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

for loop: is used for iterating over a sequence


numbers=[2,6,5,11]
for x in numbers:
print(x)
->2
6
5
11

Do while loop:

Do{
1(statement)
}while(condition)

Boolean values: The boolean values True/False in python code.


Lacks the equaltos as we place around the strings and they will always start with T and Fand
then the rest of the word in lowercase

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

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

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.

Truth table: Show every possible result of a boolean operator

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

Mixing boolean and comparison operators:


(4<5) and (5<6)
True and True
True

(1==2)or(2==3)
False and False
False

2+2=4 and not 2+2==5 and 2*2==2+2


True and not False and True
True and True and True
True
Elements of flow control:

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.

There are 3 rules for blocks:

1 Blocks begin when the indentation increases


2 Blocks can contain other blocks
3 Blocks end when indentation decreases to zero or to a containing blocks indentation

if (name=='mary'):
print('hello mary')
password=='sword fish'
print('access denied')
else:
print('wrong password')

Python Built in Module


● The python interactive shell has a number of built in functions they are loaded
automatically as a hell starts and are available such as print system function, input
function
● Number conversion functions such as int(), float(),complex(), etc
● In built in functions a large number of pre defined functions are also available on apart
libraries bundled with python apart libraries in distributions. These functions are defined
in module and are called built in modules.
● To display list of available modules help(modules)
● Pipes,typing,random,size of

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)

->[1, 2, 15, 12, 25, 35]

Python sys module:

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]

Importing a module: an import statement consists of the following


1. Import keyword
2. Name of module
3. It can be some more module names, as long as they are separated by ’ , ’ commas.
eg)import random,os,math

[Link]:

It causes the program to terminate or xit by calling the [Link] function.


This function is present in sys module
We will have to import sys

Functions:

A function is a mini program within a program

eg) def hello:


print(‘___’)
print(‘___’)
hello()

Def with parameters:


Def Hello(name):
print(‘___’+name)
Hello(person)

When you call the len function you pass values called arguments in this context by typing them
within parenthesis.

A parameter is available where an argument is stored when a function is called


1. The first the hello function is called is with argument passed.
2. The program execution enters the function and the variable name is automatically set to
the parameter.

Return values and Return Statements:

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.

Magic 8 ball program:

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

None is the only value of the none typ, datatype

None must be typed with a capital ‘N’


The value without a value can be helpful when you need to store something that wont be
confused for a real value in a variable.
eg) spam=print(“Hello”)
None=spam

Keyword print() and arguments:

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.

List data type

A list is a value that contains multiple values in an ordered sequence.

The term list value refers to the list itself, not the values inside the list values.

A list value looks like


[ ‘cat’, ‘dog’,’elephant’]

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.

Values inside the lists are called items.

Items are separated with commas.(comma delimited)

Getting individual values in a list with indices

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

Getting sublists with slices

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]

Getting lists length with len function

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.

Changing values in a list with indices:

spam=['cat','elephant','banana'],['cow','apple']
spam[0][2]='person'
print(spam)

->(['cat', 'elephant', 'person'], ['cow', 'apple'])

spam=['cat','elephant','banana'],['cow','apple']
spam[0][2]=spam[0][1]
print(spam)

->(['cat', 'elephant', 'elephant'], ['cow', 'apple'])


List concatenation and list replication

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]

Removing values from list with delete statement:

spam=['cat','dog','rabbit']
del spam[0]
print(spam)

->['dog', 'rabbit']

Working with lists:

[1,2,3,4]
spam=[1,2,3,4]
spam=’apple’

Print(‘Enter some names’)


names=input()

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

The 5A student name


person
Roger

**************************************************************

Using for loop with lists:

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])

->index 0spam is cat


index 1spam is dog
index 2spam is horse
In and not in operator:
spam=['cat','dog','horse']
print('cat' in spam)

-> 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')

->enter pet name

tom
i dont have a pet named tom

enter pet name

timmy
Timmy is my pet

The Multiple assignment trick


Is a shortcut which lets you assign multiple variables with the values in a list in one line of code.

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

● When we use the augmented assignment operator (+=) to do the same

Augmented Assignment statements Euivalent assignment statement

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

Finding a value in a list with index method:

spam=['hey','hi']
print([Link]('hi'))

-> 1

Adding values to a list with append() and insert() methods:


To add values to a list use the append() and insert() methods.

eg)spam=['cat','cow','dog']
[Link]('mouse')
print(spam)

-> ['cat', 'cow', 'dog', 'mouse']

● 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)

->['cat', 'cow', 'mouse', 'dog']

Removing values from list with remove :

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)

->['cat', 'cow', 'dog']

eg2)spam=['cat','cow','mouse','cow','dog']
[Link]('cow')
print(spam)

->['cat', 'mouse', 'cow', 'dog']

Sorting the values in a list with the sort method:

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)

->['ant', 'bear', 'cow', 'dog', 'mouse']

eg2)spam=[-2,10,2,-4,3]
[Link]()
print(spam)

->[-4, -2, 2, 3, 10]

eg3)spam=['ant','Ant','mouse','cow','dog']
[Link](reverse=True)
print(spam)

->['mouse', 'dog', 'cow', 'ant', 'Ant']

● 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)

->['ant', 'Ant', 'cow', 'dog', 'mouse']

Magic 8 ball with list

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)])

->reply hazy try again

List like types: strings and tuples

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 and immutable data types:

Mutable Immutable

A list value is a mutable data type A string is 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)name=['person','the ','great'] eg) name='person a great'


name=['person','is ','great'] newname=name[0:6]+'the'+name[7:14]
print(name) print(newname)
->['person', 'is ', 'great'] -> person the great

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

● Tuples cannot have their values modified, appended or removed.

eg)eggs=('hello',2,45)
eggs[1]=99

->TypeError: 'tuple' object does not support item assignment

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'>

Benefits of using tuple:


● Tuples are used to convey to anyone who is reading your code that you dont intend to
change the sequence of values.
● Tuples are immutable which means contents dont change.
● Python can implement some optimizations which makes the code using tuples faster
than code using lists.

Converting types with list() and tuple():

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

eg)spam=42 #assign value


cheese=spam #copy value in spam and assign it to cheese variable
spam=100 #changing value in spam
print(cheese)
print(spam)

It doesn’t affect as spam and cheese are different variables

->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]

eg) def eggs(a):


[Link]('hi')
spam=[1,2,3]
eggs(spam)
print(spam)

-> [1, 2, 3, 'hi']

eg2)def eggs(a):
a=20
a=50
eggs(a)
print(a)

->50

Copy and Deepcopy:

import copy
a=[1,2,[4,5],3]
b=[Link](a)
b[2][1]=45
print(a)
print(b)

->[1, 2, [4, 45], 3]


[1, 2, [4, 45], 3]

import copy
a=[1,2,[4,5],3]
b=[Link](a)
b[2][1]=45
print(a)
print(b)

->[1, 2, [4, 5], 3]


[1, 2, [4, 45], 3]

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

Keys values and methods:

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.

The values returned by these methods are not true lists.

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))

->features are key: color values: red


features are key: age values: 42
Checking whether a key or value exists in a dictionary(in and not):
spam={'color':'red','age':42}
print('color' in [Link]())

->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')

->i am bringing 5 cups

eg2)items={'apple':10,'cups':5}
print('i am bringing '+str([Link]('eggs',0))+' cups')

->i am bringing 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.

message='It is a rainy day'


count={}
for character in message:
[Link](character,0)
count[character]+=1
print(count)

->{'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)

->{ ' ': 4,


'I': 1,
'a': 3,
'd': 1,
'i': 2,
'n': 1,
'r': 1,
's': 1,
't': 1,
'y': 2}

Using data structures to model real world things:

Tic tac toe board:

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

A String is a sequence of characters

eg)a=”person”
String literals:

String literals beings and ends with a single quote.


eg)’Hello’

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

Escape character Print as

\’ 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.

eg)print(r"hi\nhow are you\nhello\ni\'m good\t\"i am going home\"\\outside")

->hi\nhow are you\nhello\ni\'m good\t\"i am going home\"\\outside

Multiline strings with triple quotes:

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()

->['a', 'b', 'c']

Indexing and slicing:

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:

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.

eg)print("person" in "person is great")

->False

Using string methods:

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

Join and split methods:

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())

->['cats', 'rats', 'bats']

eg)print('fruit name is mango'.split('m'))


->['fruit na', 'e is ', 'ango']

Justifying text with rjust, ljust

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***

Removing white spaces with strip,lstrip and rstrip:

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

eg) spam=" balaji the great "


print([Link]())
print([Link]())
print([Link]())

->

balaji the great


balaji the great
balaji the great
eg)
spam="SpamSpamBaconSpamEggsSpamSpam"
print([Link]('ampS'))

->BaconSpamEggs

Copying and pasting strings using pyperclip module:

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.

Pyperclip does not come with python

To install pyper clip in the command prompt type pip install pyperclip

Password locker:

1. Password design and data structures

2. Handle cmd line arguments

3. Copy the right passwords

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

1. Program design and data structures:


● To run this program we require command prompt where a cmd line argument has
the accounts name- for instance
password={‘Email’:’awdku@[Link]’, ‘blog’:’awdh’,’luggage’:2342}

2. Handle command line arguments:


● The cmd line arguments will be stored in the variable [Link]
● [Link] - should always be a string containing the programs file name
- It should be the first cmd line argument
3. Copying and pasting

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')

Adding bullets to wikimarker

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.

Finding patterns of text without regular expression:


def isphonenumber(text):
if(len(text)!=12):
return False
for i in range(0,3):
if not text[i].isdecimal():
return False
if text[3]!='-':
return False
for i in range(4,7):
if not text[i].isdecimal():
return False
if text[7]!='-':
return False
for i in range(8,12):
if not text[i].isdecimal():
return False
return True
print('415-555-6555')
print(isphonenumber('415-555-6555'))
print('person is a phonenumber')
print(isphonenumber('person'))

->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’

Finding pattern of texts with RE


RE called regexes, are descriptions for a pattern of text \d in a regex stands for a digit character
any single numeral 0-9

Creating regex objects:

All the regex functions in python are in the RE module

Import re

Passing a string value representing RE to [Link]() returns a regex pattern object

[Link](r’\d\d\d-\d\d\d-\d\d\d\d’)

Matching regex objects:

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]())

->phone number found: 123-456-3333

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]())

->phone number found: 223-456-3353

More pattern matching with RE:

Grouping with parenthesis


Matching multiple groups with the pipe
Optional matching with ?
Matching 0 or more with the *
Matching 1 or more with +
Matching specific repititions with {}
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](1))

->
1: phone number found: 123
2: phone number found: 456
0: phone number found: 123-456-3333

Group: Individual values will be printed.


Groups: multiple values will be printed.

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]())

->('123', '456', '3333')

Matching multiple groups with the pipe:

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

Optional matching with the ?:

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

Matching zero or more with *:

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

Matchng 1 or more with +:


+ Means match one or more. The group preceding a plus must appear at least once
It is not optional
eg)

import re
h=[Link](r'Bat(wo)+man')
m=[Link]('The adventures of Batwowoman')
print([Link]())

->
Batwowoman

Matching specific repetition with {}

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 method:

[Link] will return string of every match in the search string

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:

Short hand character class Meaning

\d Any numeric digit 0=9

\D Any character that is not numeric digit

\w Any letter, numeric digit or underscore

\W Any character that is not a letter, numeric digit


or underscore.
\s Any space, tab or newline

\S Any character that is not space, tab or


newline

\d+ Will match text that has one or more numeric


digits

\w+ Will match one or more letter, digit or


underscore characters

import re
h=[Link](r'\d\s\w')
m=[Link]('10 apples15 dolls 25 toys')
print(m)

-> ['0 a', '5 d', '5 t']

import re
h=[Link](r'\d+\s\w+')
m=[Link]('10 apples15 dolls 25 toys')
print(m)

->['10 apples15', '25 toys']

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)

->[' apples ', ' dolls ']


Making character class:

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)

->['I', 'i', 'e', 'I', 'e', 'e', 'a']

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 and dollar sign characters:

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)

-><[Link] object; span=(0, 5), match='Hello'>

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

Wild card character:

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'))

->['cat', 'hat', 'sat', 'lat', 'mat']

Matching everything with (.*):

You can use the .* to stand in for ‘anything’

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

The .* using greedy mode


eg)
import re
s=[Link](r'<.*?>')
m=[Link]('<to serve man> for dinner>')
print([Link]())

-><to serve man>

Otherwise

-><to serve man> for dinner>

Matching new lines with . character :

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]())

->serve the public


protest innocent
uphold law

Case insensitive matching:

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

Substituting strings with the sub method:

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:

String to replace any matches


String for regular expressions

The sub method returns a string with the substitution applied

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)

->people the nation people

Managing complex regexes

The VERBOSE mode can be enabled by passing the variable [Link]


As 2 argument to [Link]()

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

A file has 2 key properties: file name and path


Filename- written as one word
eg)[Link]
Path- specifies the location of a file on the computer
C:\Users\person

Folders: contain files and other folders.

Directories:consists of folders in turn all the files.

C:\

User
person

\ on windows and / on os x and linux

On windows paths are written using \ as the separator between folder name

Os x and linux use / as separator

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.

Current working directory:

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

Handling absolute and relative paths:

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],abspath(path) : will return a string of the absolute path of the argument


It is an easy way to convert relative path into an absolute one

[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]']

Finding file sizes and folder content:

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']

Checking path validity:

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.

FIle reading and writing:

The shelve module makes it easier to work with binary files.


There are three steps to read or write files:
1. Open- if the function is called it will return a file object
2. Read/write- if the method is called the read/write is performed on the file object.
3. Close- closes the file by calling the close method on the object.

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.

>>> h=open("/mnt/c/Users/person/Desktop/check/txt files/[Link]")


>>> content=[Link]()
>>> print(content)

Hello

>>> h=open("/mnt/c/Users/person/Desktop/check/txt files/[Link]")


>>> content=[Link]()
>>> print(content)

Writing files:

>>> print([Link]('ellooo\n'))
7

Saving variables with shelve module:

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]()

>>> import shelve


>>> s=[Link]('mydata')
>>> cats=['zophie','person','simon']
>>> s['cats']=cats
>>> [Link]()
>>>
>>> s=[Link]('mydata')
>>> print(type(s))
<class '[Link]'>
>>> print(s['cats'])
['zophie', 'person', 'simon']

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

Moving and renaming files and folders:

import shutil,os
[Link]('d:\\')
print([Link]('d:\\[Link]','d"\\delicious'))

print([Link]('d:\\hello','d"\\delicious')) - it will create a new folder with same content as


the original folder

[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'))

Permanently delete files and folder:

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.

[Link](path): will delete file at the path


[Link](path): will delete folder at path. The folder must be empty from any files or folders
[Link](path): remove the folder at path and all files and folders it contains will be deleted.

Import os
For filename in [Link]():
If [Link](‘.rxt’):
[Link](filename)
print(filename)

Safe delete with the send2trash module:

[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]’)

Walking a directory tree:

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(‘ ‘)

Compressing files with zipfile module:

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)

SET(Minor)(12) person_(1)/[Link]', 'DP SET(Minor)(12) person_(1)/[Link]']


320425
263250

Extracting from zip files: The extractall method for ZipFile objects , extracts all the files and
folders from a zipfile into the current working directory

Creating and adding to zipfiles:

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

5. Explain functions of shutil module with examples


6. Explain caret and dollar sign with examples
7. How to handle absolute and relative paths
8. Write a python program to extract phone numbers and email ids
9. Write a python program to implement multiclip board using shell,pyperclip and sys
modules

10. Explain the string methods start end join split


11. Whitespace character rjust,ljust and center with examples
12. Write python program to find number of words, digits, uppercase and lowercase
13. Write the difference between os and [Link] module
14. Chdir,rmdir,list,get,walk
15. Assertions with examples
16. Greedy and non greedy
17. Findall()
18. Explain the modes of opening the files in python with example
19. Write a python program to generate multiple choice question paper for the set of 50
students(assume domain of question paper are on states and capitals)
20. Evaluate the expression ‘Hello world!’[1]
b)’Hello world!’[0:5]
c)’Hello world!’[:5]
d)’Hello world!’[3:]
e)’Hello’.upper().isupper()
f)’Hello’.upper().lower()
g)’\n’.join([‘A’,’B’,’C’])
h)‘Hello,how are you?.split()

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:

1 The raise keyword


2 A call to the exception function
3 A string with a helpful error message passed to the exception function

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

Getting traceback as a 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:

Used instead of print

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.

Using the logging module:

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

INFO: [Link]() used to record information on general events in your


program or confirm that things are working at their point in the program

WARNING [Link]() used to indicate a potential problem that doesn't prevent


the program from working but might do so in the future.

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.

DISABLE [Link]() will disable all messages after it

IDLE debugger:
The debugger is a feature of IDLE which allows you to execute your program one line at a time

To enable IDLE debugger debug->debugger in the interactive shell window

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

Step- Executes the next line of code and then pauses

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.

Quit- it will immediately terminate the program

print('enter the first number to add:')


first=input()
print('enter the second number to add:')
second=input()
print('enter the third number to add:')
third=input()
print('the sum is '+first +second+third)

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

Project [Link] with Browser module


The webbrowser module open function helps in launching a new web browser to the specified
url

The module used here is webbrowser

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]

Downloading files from the web with request module

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

To run the request module install pip install requests


Import requests

If no error message occurs, the request module has successfully installed

Downloading a web page with [Link]()

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

Checking for errors

import requests
res=[Link]('[Link]
res.raise_for_status()

raise HTTPError(http_error_msg, response=self)

HTTPError: 404 Client Error: Not Found for url: [Link]

Saving Downloaded files to hard drive

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]

A html file is plain text file with .html file extension.


The text in these files are surrounded by tags which are enclosed in <>. A starting and closing
tag can enclose some text to form an element. The text or inner html is the content between
starting and closing tags.
<strong>Hello</strong>world;

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> tag encloses text that should be a link.

<a href=”[Link]

Viewing the source html of a web page:

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>

Opening a browser’s developers tools:

In chrome, internet explorer the developer tools are already installed and it can be viewed by
pressing f12

If you press f12 developer window will disappear.

In chrome dev tool can be viewed by selecting view->developer-developer tools

Excel spreadsheets: excel Document is called workbook.


A single workbook is saved in a file with the .xlsx extension
Each workbook can contain multiple sheets or worksheets
The sheet the user is currently viewing is called the active sheet
Each sheet has columns and rows. Columns are addressed by letters starting at A
Rows are addressed by letters starting at 1
A box at a particular column and row is called a cell
Each cell can contain a number or text value

Installing the openpyxl module:

The name of the module is openpyxl , to install pip install openpyxl

Reading excel sheets:

Opening doc with OpenPyXL

import openpyxl
path=r'C:/Users/person/Desktop/[Link]'
wb=openpyxl.load_workbook(path)
print(type(wb))
-><class '[Link]'>

Getting sheets from workbook:

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

Getting sheets from Sheets:

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

You might also like