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

School of Computer Science: NAME-Shahid Afridi SAP ID - 500068189 ROLL NO - R134218148 CSF B3

Here is a program to generate three random numbers and check if all the numbers are same: import random num1 = random.randint(0,9) num2 = random.randint(0,9) num3 = random.randint(0,9) if num1 == num2 == num3: print("All numbers are same") else: print("Numbers are not same") Output: Numbers are not same Or it may print: All numbers are same Based on the random numbers generated. C. Nested if statements Nested if statements are used to check multiple conditions where the outer if statement contains inner if

Uploaded by

Misbah Arshad
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)
92 views

School of Computer Science: NAME-Shahid Afridi SAP ID - 500068189 ROLL NO - R134218148 CSF B3

Here is a program to generate three random numbers and check if all the numbers are same: import random num1 = random.randint(0,9) num2 = random.randint(0,9) num3 = random.randint(0,9) if num1 == num2 == num3: print("All numbers are same") else: print("Numbers are not same") Output: Numbers are not same Or it may print: All numbers are same Based on the random numbers generated. C. Nested if statements Nested if statements are used to check multiple conditions where the outer if statement contains inner if

Uploaded by

Misbah Arshad
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
You are on page 1/ 75

SCHOOL OF COMPUTER SCIENCE

NAME- Shahid Afridi


SAP ID- 500068189
ROLL NO- R134218148
CSF B3
LAB-1

Python Installation, Basic Python Programs, how program works, print


statements.

A. Python Installation

Step1. Visit the link https://www.python.org/downloads/

Step2 Click on Download Python 3.8.5 to download python latest version for windows
setup. python-3.8.5.exe will be downloaded.

Step3. Click on setup and Python 3.8.5 setup box is displayed.


Step4. Click on install now and setup installing progress starts.

Step5. Python 3.8.5 is installed after initializing process finishes.


You can check Python 3.8 in start menu.
B. Basic Programs

1. Write a program to calculate the square root of a number.

Code-

num=20
num_sqrt=num**0.5
print('the square root of %0.3f is %0.3f'%(num,num_sqrt))

Output-

2. Write a program to Calculate the area of a triangle ,if a,b,c are 3 sides of the triangle are
given.

Code:

a=6
b=7
c=8
s=(a+b+c)/2
area=(s*(s-a)*(s-b)*(s-c))**0.5
print('%0.2f'%area)

Output-

3. Write a program to solve Quadratic Equations.

Code:

import cmath

a=2
b=5
c=8

# calculate the discriminant


d = (b**2) - (4*a*c)

# find two solutions


x1 = (-b-cmath.sqrt(d))/(2*a)
x2 = (-b+cmath.sqrt(d))/(2*a)

print('The solution are {0} and {1}'.format(x1,x2))

Output-

4. Write a program to print Random Number.


Code:

import random

print(random.randint(0,9))

Output-

C. Print Statements

print evaluates each expression in turn and writes the resulting object to standard output.
If an object is not a string, it is first converted to a string using the rules for string
conversions. The string is then written. A space is written before each object is written,
unless the output system believes it is positioned at the beginning of a line. This is the case

(1) when no characters have yet been written to standard output,

(2) when the last character written to standard output is "\n"

(3) when the last write operation on standard output was not a print statement. (In some
cases it may be functional to write an empty string to standard output for this reason.)

A "\n" character is written at the end, unless the print statement ends with a comma. This
is the only action if the statement contains just the keyword print

Print Syntax:

#print_stmt: "print" [ expression ("," expression)* [","] ]

print also has an extended form, defined as


#print_stmt: "print" ">>" expression [ ("," expression)+ [","] ]

In this form, the first expression after the » must evaluate to a ``file-like'' object, specifically
an object that has a write() method as described above. With this extended form, the
subsequent expressions are printed to this file object. If the first expression evaluates to
None, then sys.stdout is used as the file for output.
LAB-2
Use of input statements and operators

A. Input Statements

Definition-

This function first takes the input from the user and then evaluates the expression, which
means Python automatically identifies whether user entered a string or a number or list. If
the input provided is not correct then either syntax error or exception is raised by python.

Syntax- input(prompt)

B. Basic Programs

1. Write a program to accept 2 numbers from a User and Display the sum of the numbers.

Code-

x1=int(input('enter your number 1:'))

x2=int(input('enter your number 2:'))

sum = x1+x2

print(sum)

Output-
2. Write a program to Check whether a number is Amstrong or not?

Code-

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-

C. Operators-

Python Arithmetic Operators- Arithmetic operators are used with numeric


values to perform common mathematical operations.

OPERATOR DESCRIPTION
SYNTAX

+ Addition: adds two operands x+y

- Subtraction: subtracts two operands x-y

* Multiplication: multiplies two operands x*y

/ Division (float): divides the first operand by the second x / y

// Division (floor): divides the first operand by the second x // y

% Modulus: returns the remainder when first operand is x%y

divided by the second

** Power : Returns first raised to power second x ** y


Code-

a = 10

b=4

# Addition of numbers

add = a + b

# Subtraction of numbers

sub = a - b

# Multiplication of number

mul = a * b

# Division(float) of number

div1 = a / b

# Division(floor) of number

div2 = a // b

# Modulo of both number

mod = a % b

# Power

p = a ** b
# print results

print(add)

print(sub)

print(mul)

print(div1)

print(div2)

print(mod)

print(p)

Output-

Python Assignment Operators- Assignment operators are used to assign


values to variables:

Operator Example Same As

= x=5 x=5
+= x += 3 x=x+3

-= x -= 3 x=x-3

*= x *= 3 x=x*3

/= x /= 3 x=x/3

%= x %= 3 x=x%3

//= x //= 3 x = x // 3

**= x **= 3 x = x ** 3

&= x &= 3 x=x&3

|= x |= 3 x=x|3

^= x ^= 3 x=x^3

>>= x >>= 3 x = x >> 3

<<= x <<= 3 x = x << 3

Python Comparison Operators- Comparison operators are used to compare two values.

Operator Name Example

== Equal x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y


<= Less than or equal to x <= y

Python Logical Operators- Logical operators are used to combine conditional statements.

Operator Description Example

and Returns True if both statements are true x < 5 and x < 10

or Returns True if one of the statements is true x < 5 or x < 4

not Reverse the result, returns False if the result not(x < 5 and x < 10)

is true

Python Identity Operators- Identity operators are used to compare the objects, not if they
are equal, but if they are actually the same object, with the same memory location.

Operator Description Example

is Returns True if both variables are the same object x is y

is not Returns True if both variables are not the same object x is not y

Python Membership Operators-

Membership operators are used to test if a sequence is presented in an object.

Operator Description Example

in Returns True if a sequence with the specified value is x in y

present in the object


not in Returns True if a sequence with the specified value is x not in y

not present in the object

Python Bitwise Operators-

Bitwise operators are used to compare (binary) numbers.

Operator Name Description

& AND Sets each bit to 1 if both bits are 1

| OR Sets each bit to 1 if one of two bits is 1

^ XOR Sets each bit to 1 if only one of two bits is 1

~ NOT Inverts all the bits

<< Zero fill left shift Shift left by pushing zeros in from the

right and let the leftmost bits fall off

>> Signed right shift Shift right by pushing copies of the leftmost

bit in from the left, and let the rightmost bits fall off
LAB-3

Conditional Statement: if, elif and nested if statements

A. If, If..else, If-elif

if Statement-

If the simple code of block is to be performed if the condition holds true than if statement is
used. Here the condition mentioned holds true then the code of block runs otherwise not.

Syntax-

if condition:

# Statements to execute if

# condition is true

if..else Statement-

In conditional if Statement the additional block of code is merged as else statement which
is performed when if condition is false.
Syntax-

if (condition):

# Executes this block if

# condition is true

else:

# Executes this block if

# condition is false

if-elif else Statement-

The if-elif statement is shortcut of if..else chain. While using if-elif statement at the end else
block is added which is performed if none of the above if-elif statement is true.

Syntax-

if (condition):

statement

elif (condition):

statement

else:

statement
B. Basic Programs

1. Write a program to accept two numbers from a user and identify the even number out of
them.

Code-

x1 = int(input("Enter first number : "))

x2 = int(input("Enter second number : "))

if (x1%2 == 0) and (x2%2 == 0):

print("Both are even.")

elif (x1%2 == 0):

print(x1,"is even.")

elif (x2%2 == 0):

print(x2,"is even.")

else:

print("None of them is even")

Output-
2. Write a program to generate three random numbers and check if all the numbers are
same then print 1st prize and if two are same then print 2nd prize and if all three are
different then print try again.

Code-

import random

num1 = random.randrange(1,10)

num2 = random.randrange(1,10)

num3 = random.randrange(1,10)

if num1 == num2 and num1 == num3:

print("1st Prize")

elif num1==num2 or num2==num3 or num1==num3:

print("2nd Prize")

else:

print("Try Again!")

Output-
3. Write a program to check if the number entered by the user is positive , negative or zero.

Code-

num = eval(input("Enter a number: "))

if num == 0:

print(num,"is Zero")

elif num > 0:

print(num,"is Poisitive")

else:

print(num,"is Negative")

Output-

4. Write a program to check whether the entered character is vowel or consonant.

Code-

ch = input("Enter a character: ")[0]

if ch=='A' or ch=='a' or ch=='E' or ch =='e' or ch=='I' or ch=='i' or ch=='O' or


ch=='o' or ch=='U' or ch=='u':
print(ch, "is a Vowel")

else:

print(ch, "is a Consonant")

Output-

LAB-4

LOOPS IN PYTHON

A. Theory of loops-

A loop statement allows us to execute a statement or group of statements multiple times.


The following diagram illustrates a loop statement.

1. for loop- For loops are used for sequential traversal. For example: traversing a list or
string or array etc. In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for
in” loop which is similar to for each loop in other languages. Let us learn how to use for in
loop for sequential traversals.
Syntax:

For iterator_var in sequence:

statements(s)

2. While Loop- In python, while loop is used to execute a block of statements repeatedly
until a given a condition is satisfied. And when the condition becomes false, the line
immediately after the loop in program is executed.

Syntax :

while expression:

statement(s)

B. Basic Programs-

1. Write a program to accept 2 numbers from a user and display the sum of even and odd
numbers

Code-

a = int(input("enter lower range: "))

b = int(input("Enter upper range: "))

evensum=0

oddsum=0

for i in range(a+1,b):

if i%2==0 :

evensum=evensum+i

else :
oddsum=oddsum+i

print ("Sum of even numbers-",evensum)

print ("Sum of odd numbers-",oddsum)

Output-

2. Write a program to accept a number from a user and display the table of that number in
the format A * B = C

Code-

n=eval(input("Enter the number: "))

for i in range (0,11):

a=n*i

print (n,"*",i,"=",a)

Output-
3. Write a program to generate the output.

12

123

1234

Code-

num = eval(input('Enter a number:'))

for num in range(1, num+1):

for column in range(1, num + 1):

print(column, end=' ')

print("")

Output-
4. Write a program to accept a string from the user and remove the white spaces from the
string

Code-

string1 = input('Enter a string:')

string2 = ''

for i in string1:

if (i != ' '):

string2 = string2 + i

print(string2)

Output-

5. Write a program to accept 2 numbers from a user as a range and display all the prime
numbers in that range.
Code-

a = int(input("enter lower range: "))

b = int(input("Enter upper range: "))

for number in range(a,b + 1):

if number > 1:

for i in range(2,number):

if (number % i) == 0:

break

else:

print(number)

Output-

6. Write a program to find HCF of 2 numbers.

Code-

a = int(input("enter first number: "))

b = int(input("enter second number: "))

def hcfcalculate(x, y):


while(y):

x, y = y, x % y

return x

hcf = hcfcalculate(a,b)

print("The HCF is", hcf)

Output-

LAB-5
Use of string and set string

Strings:

A string is a sequence of characters.

A character is simply a symbol. For example, the English language has 26 characters.

Computers do not deal with characters; they deal with numbers (binary). Even though you
may see characters on your screen, internally it is stored and manipulated as a combination
of 0s and 1s.

This conversion of character to a number is called encoding, and the reverse process is
decoding. ASCII and Unicode are some of the popular encodings used.

Syntax:

A string in Python is defined between ‘ ’ or “ ”.

Str1 = “This is a string.”

Str2 = ‘This is a string’

Str3 = input(“Enter a string: ”)

String functions in Python:

1. capitalize() - Converts the first character to upper case

Syntax: String.capitalize()
2. casefold() - Converts string into lower case

Syntax – String.casefold()

3. count() - Returns the number of times a specified value occurs in a string

Syntax – String.count(SubString)

txt = "hello"

x = txt.count("l")

print(x)
4. find() - Searches the string for a specified value and returns the position of where it
was found

Syntax - String.find(SubString)

txt = "shahid"

x = txt.find("a")

print(x)

5. isdigit() - Returns True if all characters in the string are digits

Syntax – String.isdigit()

txt = "137"

x = txt.isdigit()

print(x)
6. replace() - Returns a string where a specified value is replaced with a specified value

Syntax - String.replace(SubStringtobeReplaced,SubStringtobeReplacedWith)

txt = "make"

x = txt.replace("k", "d")

print(x)

7. join() - Joins the elements of an iterable to the end of the string

Syntax - string.join(iterable)

8. strip() - Returns a trimmed version of the string

Syntax - string.strip(characters)
Sets:

A Set is an unordered collection data type that is iterable, mutable and has no duplicate
elements. Python’s set class represents the mathematical notion of a set. The major
advantage of using a set, as opposed to a list, is that it has a highly optimized method for
checking whether a specific element is contained in the set. This is based on a data
structure known as a hash table. Since sets are unordered, we cannot access items using
indexes like we do in lists.

Syntax: set = {"element1", "element2", "element3"}

Set Functions –

1. add() - Adds an element to the set


Syntax - set.add(element)

set = {"apple", "banana", "cherry"}


set.add("orange")
print(set)

2. clear() - Removes all the elements from the set


Syntax - set.clear()

set = {"apple", "banana", "cherry"}


set.clear()
print(set)

3. copy() - Returns a copy of the set


Syntax - set.copy()

mobile = {"apple", "samsung", "oneplus"}


x = mobile.copy()
print(x)

4. pop() - Removes an element from the set


Syntax - set.pop()

mobile = {"apple", "samsung", "oneplus"}


mobile.pop()
print(mobile)
5. remove() - Removes the specified element
Syntax - set.remove(item)

mobile = {"apple", "samsung", "oneplus"}


mobile.remove("apple")
print(mobile)

BASIC PROGRAMS –

1. WAP to accept a string from a user and print it's reverse without using inbuilt
function.

str = (input("Enter a String to reverse : "))


strrev = str[::-1]
print(strrev)

2. WAP to accept a string from the user and replace the 3rd character of string of
string with h.

str = input("Enter a string : ")


print(str[:2] + "h" + str[3:])
3. WAP to fetch 2 string from a user and check whether the 2nd string is part of 1st
string or not.

str1 = input("Enter first string : ")


str2 = input("Enter second string : ")
if str2 in str1:
print(str2 + " is a substring of " + str1)
else:
print(str2 + " is a not a substring of " + str1)

4. WAP to fetch value from a user and add that value in an existing set.

set1={"bmw", "audi", "mercedes"}


x=input("Enter: ")
set1.add(x)
print(set1)

5. Explain the remove discard and clear methods os sets by giving a suitable
example.
Remove() -

The remove() method removes the specified element from the set.
This method is different from the discard() method, because the remove() method will
raise an error if the specified item does not exist, and the discard() method will not.

Syntax: set.remove(item)

Example -
cars = {"bmw", "audi", "mercedes"}
cars.remove("audi")

print(cars)

Discard() -

The discard() method removes the specified item from the set.
This method is different from the remove() method, because the remove() method will
raise an error if the specified item does not exist, and the discard() method will not.

Syntax - set.discard(value)

Example -
cars = {"audi", "bmw", "mwercedes"}
cars.discard("bmw")

print(cars)
Clear() -

The clear() method removes all elements in a set.

Syntax - Set.clear()

Example –
cars = {"audi", "bmw", "mwercedes"}
cars.clear()

print(cars)

LAB – 6
Dictionary, Tuple, Lists

Dictionary –
It is an unordered collection of data values, used to store data values like a map, which
unlike other Data Types that hold only single value as an element, Dictionary
holds key:value pair. Key value is provided in the dictionary to make it more optimized.

Syntax - Dict = {key1:value, key2:value,……..}


Tuple –
A Tuple is a collection of Python objects separated by commas. In someways a tuple is
similar to a list in terms of indexing, nested objects and repetition but a tuple is immutable
unlike lists which are mutable.

Syntax - Tuple = (“x”, “y”, “z”, …..)

Lists –
A list is a collection which is ordered and changeable. In Python lists are written with
square brackets.

Syntax - List = [‘x’, ’y’, ‘z’, ……]

BASIC PROGRAMS –
1.WAP in python to accept keys and values from a user and create a dictionary
with following constraints:
a. The key should not be a number.
b. The length of a key should not be more than 6.
c. The value should be even.
dict = {}
entry = int(input("Enter no. of entries to be inserted:\n"))
for x in range(entry):
key = str(input("Enter key: "))
value = int(input("Enter value: "))
if ((key.isalpha() == True) and (len(key) <= 6) and (value% 2 == 0)):
dict[key] = value
else:
print("Constraints not satisfied.")
print(dict)
2. WAP to create a nested dictionary with following key value pairs: Name, Rollno,
Subjects-nested dictionary having 3 different values for 3 different subjects
dict = {}
name = str(input("Enter Name: "))
rollno = input("Enter Roll No: ")
sub1 = input("Marks in python: ")
sub2 = input("Marks in java: ")
sub3 = input("Marks in php: ")
dict['Name']=name
dict['Roll No'] = rollno
dict['Marks'] = {'Python':sub1, 'java':sub2, 'php':sub3}

print(dict)
3. WAP to show all the possible options for removing an element from a
dictionary.
dict = {'Name':'Sachin Rawat', 'Roll No':'137', 'Batch':'CSF B3'}

print(dict)
#pop
dict.pop('Batch')
print(dict) #del
del dict['Roll No']
print(dict) #popitem
dict.popitem()
print(dict)

4.WAP to create a list with five numbers and display the following:
1. Reverse of the list without using inbuilt function
2. Sum of elements of the list
list = [2, 4, 6, 8, 9]
sum = 0
print(list)

l = len(list)
for i in range(int(l/2)):
x = list[i]
list[i] = list[l-i-1]
list[l - i - 1] = x
print(list)
for i in range(l):
sum = list[i]+sum
print("Sum = ",sum)
LAB – 7

File Handling, open a file, and read/write a file


File Handling
A file is nothing but a source of storing information permanently in the form of a sequence
of bytes on a disk.

File handling allows users to handle files i.e., to read and write files, along with many other
file handling options, to operate on files. The file handling plays an important role when the
data needs to be stored permanently into the file. A file is a named location on disk to store
related information. We can access the stored information (non-volatile) after the program
termination.

Advantages of File Handling:


1)Re usability: It helps in preserving the data or information generated after running the
program.

2)Large storage capacity: Using files, there is no need to worry about the problem of
storing data in bulk.

3)Saves time: There are certain programs that require a lot of input from the user. File
handling reduces the effort there.

4)Portability: Contents of file can easily be transferred from one computer system to
another without the loss of data.

Some function of File Handling:

1. open(): open() function accepts two arguments i.e file name and access mode &
returns a file object which can be used to perform various operations like reading,
writing, etc.
Syntax: file = open(<file-name>, <access-mode>)

2. close(): Any unwritten information gets destroyed once the close() func is called. It is
good practice to close the file once all the operations are done.

Syntax: file.close()

3. write(): Used to write anything to the file, a correct access mode must be used while
opening (basically ‘w’ or ‘a’).

Syntax: file.write(“<Data to enter>”)

4. read(): Sometimes writing is not required and we just need to read the file, in this
case the read func is used. It is generally used with read (‘r’) access mode.

Syntax: file.read(<count>)

BASIC PROGRAMS –
1. WAP to create a file & store the following information (taken from the user)
1)name 2) Add 3) Contact Info
f = open("file.txt", "w")
name=input("Enter Name:")
Address=input("Enter Address:")
ContactNo=int(input("Enter Contact Number:"))
f.write("Name:"+name+"\n")
f.write("Address:"+Address+"\n")
f.write("ContactInfo:"+str(ContactNo)+"\n")
f.close()
2. WAP to create to count the no. of times, the program is accessed.
c=0
f=open("file.txt",'a+')
f.write("a\n")
f.seek(0)
for i in f:
if 'a' in i:
c+=1
print(c)
f.close()

3. WAP to count the no. of occurrences of a word in a text file.


with open('file.txt','r') as f:
a=input("Word to be checked: ")
txt=f.read()
print(txt.count(a))
4. WAP to create a small s/w for banking which should cover only two options i.e.
withdrawal & deposits.
with open('banking.txt') as f:
x=f.read().strip()
print("Current Balance : ",x)
b=int(x)
while(1):
print("Enter 1 to Withdraw")
print("Enter 2 to Deposit")
print("Enter 0 to Exit")
c=int(input("Enter your choice : "))
if(c==1):
n=int(input("Enter Amount: "))
if(n>b):
print("Insufficient Balance")
else:
b-=n
print("Amount Successfully Withdrawn")
elif(c==2):
n=int(input("Enter Amount: "))
b+=n
print("Amount Successfully Deposited")
else:
break
with open('banking.txt','w') as f:
print("Final Balance : ",b)
b=str(b)
f.write(b)
LAB – 8

Methods and Function, Various inbuilt functions and lambda function, NumPy
Arrays, Classes and objects, Constructors

A.
1. Strings
Converting to lower case -
lower_case(string) returns a new string where all upper-case characters in the string
string have been turned to lower case:
lower_case("A Foo IS!") gives the result "a foo is!".
Converting to upper case -
upper_case(string) returns a new string where all lower-case characters in the string
string have been turned to upper case:
upper_case("A Foo IS!") gives the result "A FOO IS!".
Capitalizing -
String.capitalize(string)
If the first character in the string string is a lower-case character, it is converted to upper
case:
String.capitalize("xyz-Foo") gives the result "Xyz-Foo".
Finding a substring in a string -
search(haystack, needle) returns the index of the start of the first occurrence of the
string needle in the string haystack: search("sortohum", "orto") gives the result 1.

2. Array
array(data type, value list) - This function is used to create an array with data type and
value list specified in its arguments.
import array
# initializing array with array values
# initializes array with signed integers
arr= array.array('i',[1, 2, 3, 1, 5])

append() -This function is used to add the value mentioned in its arguments at the end
of the array.
import array

# initializing array with array values


# initializes array with signed integers
arr= array.array('i',[1, 2, 3, 1, 5])
print ("The new created array is : ",end=" ")
for i in range (0, 3):
print (arr[i], end=" ")
print("\r")

# using append() to insert new value at end


arr.append(4);

# printing appended array


print("The appended array is : ", end="")
for i in range (0, 4):
print (arr[i], end=" ")

insert(i,x) -This function is used to add the value(x) at the ith position specified in its
argument.
import array

# initializing array with array values


# initializes array with signed integers
arr = array.array('i', [1, 2, 3])

# printing original array print ("The new created array is : ",end=" ")
for i in range (0, 3):
print (arr[i], end=" ")
print("\r") arr.insert(2, 4)
for i in range (0, 4):
print (arr[i], end=" ")
print("\r")

remove() - This function is used to remove the first occurrence of the value mentioned
in its arguments.

import array

# initializing array with array values


# initializes array with signed integers
arr = array.array('i', [1, 2, 3])

# printing original array


print ("The new created array is : ",end=" ")
for i in range (0, 3):
print (arr[i], end=" ")
print("\r") arr.remove(2)
for i in range (0, 3):
print (arr[i], end=" ")
print("\r")

3. Directory
abspath() – It returns the absolute path of the file/directory name passed as an
argument. import os
os.path.abspath("Downloads")

listdir() – It is used to list the directory contents. The path of directory is passed as an
argument. import os path = "/var/www/html/" dirs = os.listdir( path )

isdir() – It checks whether the passed parameter denotes the path to a directory. If yes
then returns True otherwise False

importos.path

path ='/home/User/Documents/file.txt'
isdir =os.path.isdir(path)
print(isdir)

dir() is a powerful inbuilt function in Python3, which returns list of the attributes and
methods of any object (say functions , modules, strings, lists, dictionaries etc.)

4. List
append(): Used for appending and adding elements to List.It is used to add elements to
the last position of List.
For example
List = ['Mathematics', 'chemistry', 1997, 2000]
List.append(20544)
print(List)

insert(): Inserts an elements at specified position.


Syntax:

list.insert(<position, element)

Note: Position mentioned should be within the range of List, as in this case between 0
and 4, elsewise would throw IndexError.
List = ['Mathematics', 'chemistry', 1997, 2000]
# Insert at index 2 value 10087
List.insert(2,10087)
print(List)

index(): Returns the index of first occurrence. Start and End index are not necessary
parameters. Syntax:
List.index(element[,start[,end]])

reverse(): Sort the given data structure (both tuple and list) in ascending order. Key and
reverse_flag are not necessary parameter and reverse_flag is set to False, if nothing is
passed through sorted().
Syntax:

sorted([list[,key[,Reverse_Flag]]])
list.sort([key,[Reverse_flag]])

List = [2.3, 4.445, 3, 5.33, 1.054, 2.5]

List.sort(reverse=True)

print(List)

5. Lambada Function

In Python, an anonymous function means that a function is without a name. As we already


know that the def keyword is used to define a normal function in Python. Similarly, the
lambda keyword is used to define an anonymous function in Python. It has the following
syntax:

Syntax: lambda arguments: expression


This function can have any number of arguments but only one expression, which is
evaluated and returned.
One is free to use lambda functions wherever function objects are required.
You need to keep in your knowledge that lambda functions are syntactically restricted to a
single expression.
It has various uses in particular fields of programming besides other types of expressions
in functions.

Example:
def cube(y):
return y*y*y
lambda_cube = lambda y: y*y*y
print(cube(5))
print(lambda_cube(5))

6. Python map() function

map() function returns a map object(which is an iterator) of the results after applying the
given function to each item of a given iterable (list, tuple etc.)

Syntax :

map(fun, iter) Parameters :


fun : It is a function to which map passes each element of given iterable.
iter : It is a iterable which is to be mapped.

Example
def addition(n):
return n + n
numbers = (1, 2, 3, 4)
result = map(addition, numbers)
print(list(result))

7. filter() in python
The filter() method filters the given sequence with the help of a function that tests each
element in the sequence to be true or not.
syntax: filter(function, sequence) Parameters:

function: function that tests if each element of a sequence true or not. sequence: sequence
which needs to be filtered, it can be sets, lists, tuples, or containers of any iterators.
Returns: returns an iterator that is already filtered.
Example:
def fun(variable):
letters = ['a', 'e', 'i', 'o', 'u']
if (variable in letters):
return True
else:
return False
sequence = ['g', 'e', 'e', 'j', 'k', 's', 'p', 'r']
filtered = filter(fun, sequence)
print('The filtered letters are:') for s in filtered: print(s)

8. Class and Objects


A class is a user-defined blueprint or prototype from which objects are created. Classes
provide a means of bundling data and functionality together. Creating a new class creates a
new type of object, allowing new instances of that type to be made. Each class instance can
have attributes attached to it for maintaining its state. Class instances can also have
methods (defined by its class) for modifying its state.
An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of
the class with actual values. It’s not an idea anymore, it’s an actual dog, like a dog of breed
pug who’s seven years old. You can have many dogs to create many different instances, but
without the class as a guide, you would be lost, not knowing what information is required.
An object consists of :
 State : It is represented by attributes of an object. It also reflects the properties of an
object.
 Behavior : It is represented by methods of an object. It also reflects the response of
an object with other objects.
 Identity : It gives a unique name to an object and enables one object to interact with
other objects.

Example- class Dog:

# A simple class
# attribute
attr1 = "mamal"
attr2 = "dog"

# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)

Rodger = Dog()

print(Rodger.attr1)
Rodger.fun()

9. Constructor
Constructors are generally used for instantiating an object.The task of constructors is to
initialize(assign values) to the data members of the class when an object of class is
created.In Python the __init__() method is called the constructor and is always called when
an object is created.

Types of constructors :

• default constructor :The default constructor is simple constructor which doesn’t


accept any arguments.It’s definition has only one argument which is a reference to the
instance being constructed.

• parameterized constructor :constructor with parameters is known as


parameterized constructor.The parameterized constructor take its first argument as a
reference to the instance being constructed known as self and the rest of the
arguments are provided by the programmer.

Example:

class Student:
count = 0
def __init__(self):
Student.count = Student.count + 1
s1=Student()
s2=Student()
s3=Student()
print("The number of students:",Student.count)

B. Programs –
1. Write a program to perform basic banking operation like withdraw and deposit
using classes.
Code –
class Bank:
balance = 10000
def Deposite(self):
amount = int(input("Enter the amount to deposite:"))
self.balance += amount
print("Account Balance:", self.balance)

def Withdraw(self):
amount = int(input("Enter the amount to withdraw:"))
print("Withdrawing", amount, "..............")
if self.balance>= amount:
self.balance -= amount
print("Account Balance:", self.balance)
else:
print("Insufficient Balance.")
x=Bank()
x.Deposite()
x.Withdraw()

Output –

2. Write a program to find the area of figure using constructor.


Code –
class Area:
def __init__(self, length, breadth):
self.length = length
self.breadth = breadth

def calArea(self):
return self.length * self.breadth

a = int(input("Enter length of rectangle: "))


b = int(input("Enter breadth of rectangle: "))
x = Area(a, b)
print("Area of rectangle:", x.calArea())
Output –

3. Write a program to accept employee basic salary from function using class A
and in Class B then calculate the net and gross salary using another class using
inheritance by using following condition
1) The da is 30% of base
2) HRA IS 20%
3) Income tax is 5%
Code –
class employee:
def getSalary(self):
print("Enter salary : ", end="")
self.sal = int(input())

class netAndgross(employee):
grossSalary = 0
def calGrossSalary(self):
employee.getSalary(self)
self.grossSalary = (self.sal * 0.3) + (self.sal * 0.2) + self.sal
print("Your gross salary is : ", self.grossSalary)
def calNetSalary(self):
netsalary = self.grossSalary - (self.grossSalary * 0.05)
print("Your net salary is : ", netsalary)
x = netAndgross()
x.calGrossSalary()
x.calNetSalary()

Output –

LAB – 9

GUI in Python, Entry Widgets, Text Widgets, Rendering Script


A. Tkinter Library
Tkinter provides us with a variety of common GUI elements which we can use to build our
interface – such as buttons, menus and various kinds of entry fields and display areas. We
call these elements widgets. We are going to construct a tree of widgets for our GUI – each
widget will have a parent widget, all the way up to the root window of our application. For
example, a button or a text field needs to be inside some kind of containing window.
The widget classes provide us with a lot of default functionality. They have methods for
configuring the GUI’s appearance – for example, arranging the elements according to some
kind of layout – and for handling various kinds of user-driven events. Once we have
constructed the backbone of our GUI, we will need to customise it by integrating it with our
internal application class.
 import the Tkinter module.
 Create the main application window.
 Add the widgets like labels, buttons, frames, etc. to the window.
 Call the main event loop so that the actions can take place on the user's computer
screen.

Widget classes
There are many different widget classes built into tkinter – they should be familiar to you
from other GUIs:
A Frame is a container widget which is placed inside a window, which can have its own
border and background – it is used to group related widgets together in an application’s
layout.
Toplevel is a container widget which is displayed as a separate window.
Canvas is a widget for drawing graphics. In advanced usage, it can also be used to create
custom widgets – because we can draw anything we like inside it, and make it interactive.
Text displays formatted text, which can be editable and can have embedded images.
A Button usually maps directly onto a user action – when the user clicks on a button,
something should happen.
A Label is a simple widget which displays a short piece of text or an image, but usually isn’t
interactive.
A Message is similar to a Label, but is designed for longer bodies of text which need to be
wrapped.
A Scrollbar allows the user to scroll through content which is too large to be visible all at
once.
Checkbutton, Radiobutton, Listbox, Entry and Scale are different kinds of input widgets –
they allow the user to enter information into the program.
Menu and Menubutton are used to create pull-down menus.

Layout options
The GUI in the previous example has a relatively simple layout: we arranged the three
widgets in a single column inside the window. To do this, we used the pack method, which
is one of the three different geometry managers available in tkinter. We have to use one of
the available geometry managers to specify a position for each of our widgets, otherwise
the widget will not appear in our window.
By default, pack arranges widgets vertically inside their parent container, from the top
down, but we can change the alignment to the bottom, left or right by using the optional
side parameter.

Custom events
So far we have only bound event handlers to events which are defined in tkinter by default
– the
Button class already knows about button clicks, since clicking is an expected part of normal
button behaviour. We are not restricted to these particular events, however – we can make
widgets listen for other events and bind handlers to them, using the bind method which we
can find on every widget class.
Events are uniquely identified by a sequence name in string format – the format is
described by a mini-language which is not specific to Python. Here are a few examples of
common events:
"<Button-1>", "<Button-2>" and "<Button-3>" are events which signal that a particular
mouse button has been pressed while the mouse cursor is positioned over the widget in
question. Button 1 is the left mouse button, Button 3 is the right, and Button 2 the middle
button – but remember that not all mice have a middle button.
"<ButtonRelease-1>" indicates that the left button has been released.
"<B1-Motion>" indicates that the mouse was moved while the left button was pressed (we
can use B2 or B3 for the other buttons).
"<Enter>" and "<Leave>" tell us that the mouse curson has entered or left the widget.
"<Key>" means that any key on the keyboard was pressed. We can also listen for specific
key presses, for example "<Return>" (the enter key), or combinations like "<Shift-Up>"
(shift-uparrow). Key presses of most printable characters are expressed as the bare
characters, without brackets – for example, the letter a is just "a".
"<Configure>" means that the widget has changed size.

B. Basic Program –
1. Write a program to make calculator using Tkinter library.
Code –
import tkinter as tk
from functools import partial
def add(label_result, n1, n2):
num1 = (n1.get())
num2 = (n2.get())
result = int(num1)+int(num2)
label_result.config(text=" %d" % result)
return
def sub(label_result, n1, n2):
num1 = (n1.get())
num2 = (n2.get())
result = int(num1)-int(num2)
label_result.config(text=" %d" % result)
return
def mul(label_result, n1, n2):
num1 = (n1.get())
num2 = (n2.get())
result = int(num1)*int(num2)
label_result.config(text=" %d" % result)
return
def div(label_result, n1, n2):
num1 = (n1.get())
num2 = (n2.get())
result = int(num1)/int(num2)
label_result.config(text=" %d" % result)
return
root = tk.Tk()
root.geometry('400x200')
root.title('Calculator')
number1 = tk.StringVar()
number2 = tk.StringVar()
labelTitle = tk.Label(root, text="Calculator").grid(row=0, column=2)
labelNum1 = tk.Label(root, text="A").grid(row=1, column=1)
labelNum2 = tk.Label(root, text="B").grid(row=1, column=3)
labelNum2 = tk.Label(root, text="=").grid(row=1, column=5)
labelResult = tk.Label(root)
labelResult.grid(row=1, column=6)
entryNum1 = tk.Entry(root, textvariable=number1).grid(row=1, column=2)
entryNum2 = tk.Entry(root, textvariable=number2).grid(row=1, column=4)
add = partial(add, labelResult, number1, number2)
sub = partial(sub, labelResult, number1, number2)
mul = partial(mul, labelResult, number1, number2)
div = partial(div, labelResult, number1, number2)
buttonCal = tk.Button(root, text="+", command=add).grid(row=3, column=2)
buttonCal = tk.Button(root, text="-", command=sub).grid(row=3, column=3)
buttonCal = tk.Button(root, text="*", command=mul).grid(row=3, column=4)
buttonCal = tk.Button(root, text="/", command=div).grid(row=3, column=5)
root.mainloop()

Output –
1. Addition –
2. Subtraction –

3. Multiplication –

4. Division –
2. Create a GUI in python to accept two numbers from users and shows all the
even numbers in one text box and odd text box and odd numbers in 2nd text box
also show the sum of all evens.
Code –
import tkinter as tk
from tkinter import *
from tkinter import messagebox
root = tk.Tk()
root.title("Even Odd Calculator")
start = 0
end = 0
listEven = ""
listOdd = ""
sumEven = 0
sumOdd = 0
label_range_start = Label(root, text="Enter Starting Number")
label_range_start.grid(row=0, column=0, padx=(5,10), pady=(10,10))
startnumber = Entry(root)
startnumber.grid(row=0, column=1, padx=(5,10), pady=(10,10))
startnumber.focus_set()
label_range_end = Label(root, text="Enter Ending Number")
label_range_end.grid(row=0, column=3, padx=(5,10), pady=(10,10))
endnumber = Entry(root)
endnumber.grid(row=0, column=4, padx=(5,10), pady=(10,10))
endnumber.focus_set()
def inputRange():
global start, end
try:
start = int(startnumber.get())
end = int(endnumber.get())
processRange()
except ValueError:
tk.messagebox.showerror(title="Error", message="Kindly Enter Both the Numbers
correctly")
def processRange():
global listEven, listOdd, sumEven, sumOdd
for i in range(start, end + 1):
if i % 2 == 0:
listEven = listEven + str(i) + " "
sumEven = sumEven + i
else:
listOdd = listOdd + str(i) + " "
sumOdd = sumOdd + i
label_even_numbers = Label(root, text="Even Numbers")
label_even_numbers.grid(row=3, column=0, padx=(5,10), pady=(25,25))
evenlist = StringVar()
evenlist.set(listEven)
showEven = Entry(textvariable=evenlist, state=DISABLED)
showEven.grid(row=4, column=0, padx=(5,10), pady=(10,10))
label_odd_numbers = Label(root, text="Odd Numbers")
label_odd_numbers.grid(row=3, column=1, padx=(5,10), pady=(25,25))
oddlist = StringVar()
oddlist.set(listOdd)
showOdd = Entry(textvariable=oddlist, state=DISABLED)
showOdd.grid(row=4, column=1, padx=(5,10), pady=(10,10))
lable_sum_even = Label(root, text="Sum: " + str(sumEven), fg="#000000")
lable_sum_even.grid(row=5, column=0)
lable_sum_odd = Label(root, text="Sum: " + str(sumOdd), fg="#000000")
lable_sum_odd.grid(row=5, column=1)
calculateButton = Button(root, text="Calculate", command=inputRange)
calculateButton.grid(row=2, padx=(10,10), pady=(10,10))
root.mainloop()

Output –
LAB – 10

Creating process methods, working with directories, indexing and selecting data,
group by operations.
OS module in Python provides functions for interacting with the operating system. OS
comes under Python’s standard utility modules. This module provides a portable way of
using operating system dependent functionality.
It is possible to automatically perform many operating system tasks. The OS module in
Python provides functions for creating and removing a directory (folder), fetching its
contents, changing and identifying the current directory, etc.

 os.getpid() method in Python is used to get the process ID of the current process.
Syntax:os.getpid()
Parameter: Not required
Return Type: This method returns an integer value denoting process ID of current
process. The return type of this method is of class ‘int’.
For instance:
import os
pid = os.getpid() print(pid)
Output: 5932 here is the current process id.
 os.fork() method in Python is used to create a child process. This method works by
calling the underlying OS function fork (). This method returns 0 in the child
process and child’s process id in the parent process. os.fork() method is available
only on UNIX platforms.
Syntax:os.fork()
Parameter: No parameter is required
Return Type: This method returns an integer value representing child’s process id in
the parent process while 0 in the child process.
For instance:
import os
pid = os.fork()
if pid>0 :
print("I am parent process:")
print("Process ID:", os.getpid())
print("Child's process ID:", pid)
else :
print("\nI am child process:")
print("Process ID:", os.getpid())
print("Parent's process ID:", os.getppid())

Output:

I am Parent process
Process ID: 10793
Child's process ID: 10794
I am child process
Process ID: 10794
Parent's process ID: 10793

• Creating Directory: We can create a new directory using the mkdir() function from the
OS module.
Example:
import osos.mkdir("d:\\tempdir")
A new directory corresponding to the path in the string argument of the function will be
created. If we open D drive in Windows Explorer, we should notice tempdir folder created.
• Changing the Current Working Directory: We must first change the current working
directory to a newly created one before doing any operations in it.
This is done using the chdir () function.
Example: import osos.chdir("d:\\tempdir")
There is a getcwd() function in the OS module using which we can confirm if the current
working directory has been changed or not.
os.getcwd()
Output: 'd:\\tempdir'
Directory paths can also be relative. If the current directory is set to D drive and then to
tempdir without mentioning the preceding path, then also the current working directory
will be changed to d:\tempdir.
In order to set the current directory to the parent directory use ".." as the argument in
the chdir () function.
Example:
os.chdir("d:\\tempdir")
os.getcwd()
Output:
'd:\\tempdir' os.chdir("..")
os.getcwd()
Output: 'd:\\'
• Removing a Directory: The rmdir() function in the OS module removes the specified
directory either with an absolute or relative path. However, we cannot remove the
current working directory. Also, for a directory to be removed, it should be empty. For
example, tempdir will not be removed if it is the current directory. We have to change
the current working directory and then remove tempdir.
os.chdir("tempdir")
os.getcwd()
Output:
'd:\\tempdir'
os.rmdir("d:\\tempdir")
PermissionError: [WinError 32] The process cannot access the file because it is being used
by another process: 'd:\\tempdir'
os.chdir("..")
os.rmdir("tempdir")

List Files and Sub-directories


The listdir() function returns the list of all files and directories in the specified directory.
os.listdir("c:\python37")
Output: ['DLLs', 'Doc', 'fantasy-1.py', 'fantasy.db', 'fantasy.py', 'frame.py',
'gridexample.py', 'include', 'Lib', 'libs', 'LICENSE.txt', 'listbox.py', 'NEWS.txt',
'place.py', 'players.db', 'python.exe', 'python3.dll', 'python36.dll', 'pythonw.exe',
'sclst.py', 'Scripts', 'tcl', 'test.py', 'Tools', 'tooltip.py', 'vcruntime140.dll', 'virat.jpg', 'virat.py']
If we don't specify any directory, then list of files and directories in the current working
directory will be returned.
os.listdir()
Output: ['.config', '.dotnet', 'python']
Indexing and Selecting Data with Pandas
The Python and NumPy indexing operators "[]" and attribute operator "." provide quick
and easy access to Pandas data structures across a wide range of use cases. However, since
the type of the data to be accessed isn’t known in advance, directly using standard
operators has some optimization limits.
Pandas supports three types of Multi-axes indexing:
• .loc()
Pandas provide various methods to have purely label based indexing. When slicing, the
start bound is also included. Integers are valid labels, but they refer to the label and not the
position.
.loc() has multiple access methods like −
 A single scalar label
 A list of labels
 A slice objects • A Boolean array
loc takes two single/list/range operator separated by ','. The first one indicates the row and
the second one indicates columns.
For instance:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(8, 4),
index = ['a','b','c','d','e','f','g','h'], columns = ['A', 'B', 'C', 'D'])
print df.loc[:,'A']

OUTPUT:
a 0.391548 b

-0.070649 c

-0.317212 d

-2.162406 e

2.202797 f

0.613709 g

1.050559 h

1.122680

Name: A, dtype: float64

 .iloc()
Pandas provide various methods in order to get purely integer-based indexing. Like python
and NumPy, these are 0-based indexing.
The various access methods are as follows −
 An Integer
 A list of integers
 A range of values
For instance:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(8, 4), columns = ['A', 'B', 'C', 'D'])
print df.iloc[:4]

OUTPUT:
A B C D
1 0.699435 0.256239 -1.270702 -0.645195
2 -0.685354 0.890791 -0.813012 0.631615
3 -0.783192 -0.531378 0.025070 0.230806
4 0.539042 -1.284314 0.826977 -0.026251
• .ix()
Besides pure label based and integer based, Pandas provides a hybrid method for
selections and subsetting the object using the .ix() operator.
For instance:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(8, 4), columns = ['A', 'B', 'C', 'D'])
print df.ix[:4]

OUTPUT:
A B C D
0 0.699435 0.256239 -1.270702 -0.645195
1 -0.685354 0.890791 -0.813012 0.631615 2 -0.783192 -0.531378 0.025070
0.230806
3 0.539042 -1.284314 0.826977 -0.026251

GROUP BY OPERATIONS
Any group by operation involves one of the following operations on the original object.
They are-
• Splitting the Object
• Applying a function
• Combining the results
In many situations, we split the data into sets and we apply some functionality on each
subset. In the apply functionality, we can perform the following operations −
• Aggregation − computing a summary statistic
• Transformation − perform some group-specific operation
• Filtration − discarding the data with some condition
Split Data into Groups
Pandas object can be split into any of their objects. There are multiple ways to split an
object like −
• obj.groupby('key')
• obj.groupby(['key1','key2'])
• obj.groupby(key,axis=1)

For instance:
import pandas as pd
ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings',
'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'],
'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2, 4,1,2],
'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017],
'Points’: [876,789,863,673,741,812,756,788,694,701,804,690]}
df = pd.DataFrame(ipl_data)
print df.groupby('Team')
OUTPUT:
<pandas.core.groupby.DataFrameGroupBy object at 0x7fa46a977e50>
View Groups For instance:
import pandas as pd
ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings',
'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'],
'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2, 4,1,2],
'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017],
'Points': [876,789,863,673,741,812,756,788,694,701,804,690]} df =
pd.DataFrame(ipl_data) print df.groupby('Team').groups

OUTPUT:
{'Kings': Int64Index([4, 6, 7], dtype='int64'),
'Devils': Int64Index([2, 3], dtype='int64'),
'Riders': Int64Index([0, 1, 8, 11], dtype='int64'),
'Royals': Int64Index([9, 10], dtype='int64'),
'kings': Int64Index([5], dtype='int64')}

You might also like