School of Computer Science: NAME-Shahid Afridi SAP ID - 500068189 ROLL NO - R134218148 CSF B3
School of Computer Science: NAME-Shahid Afridi SAP ID - 500068189 ROLL NO - R134218148 CSF B3
A. Python Installation
Step2 Click on Download Python 3.8.5 to download python latest version for windows
setup. python-3.8.5.exe will be downloaded.
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-
Code:
import cmath
a=2
b=5
c=8
Output-
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
(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:
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-
sum = x1+x2
print(sum)
Output-
2. Write a program to Check whether a number is Amstrong or not?
Code-
sum = 0
temp = num
digit = temp % 10
sum += digit ** 3
temp //= 10
if num == sum:
else:
C. Operators-
OPERATOR DESCRIPTION
SYNTAX
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
mod = a % b
# Power
p = a ** b
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
print(p)
Output-
= 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
Python Comparison Operators- Comparison operators are used to compare two values.
== Equal x == y
!= Not equal x != y
Python Logical Operators- Logical operators are used to combine conditional statements.
and Returns True if both statements are true x < 5 and x < 10
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.
is not Returns True if both variables are not the same object x is not y
<< Zero fill left shift Shift left by pushing zeros in from the
>> 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
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):
# condition is true
else:
# condition is false
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-
print(x1,"is even.")
print(x2,"is even.")
else:
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)
print("1st Prize")
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-
if num == 0:
print(num,"is Zero")
print(num,"is Poisitive")
else:
print(num,"is Negative")
Output-
Code-
else:
Output-
LAB-4
LOOPS IN PYTHON
A. Theory of loops-
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:
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-
evensum=0
oddsum=0
for i in range(a+1,b):
if i%2==0 :
evensum=evensum+i
else :
oddsum=oddsum+i
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-
a=n*i
print (n,"*",i,"=",a)
Output-
3. Write a program to generate the output.
12
123
1234
Code-
print("")
Output-
4. Write a program to accept a string from the user and remove the white spaces from the
string
Code-
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-
if number > 1:
for i in range(2,number):
if (number % i) == 0:
break
else:
print(number)
Output-
Code-
x, y = y, x % y
return x
hcf = hcfcalculate(a,b)
Output-
LAB-5
Use of string and set string
Strings:
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:
Syntax: String.capitalize()
2. casefold() - Converts string into lower case
Syntax – String.casefold()
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)
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)
Syntax - string.join(iterable)
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.
Set Functions –
BASIC PROGRAMS –
1. WAP to accept a string from a user and print it's reverse without using inbuilt
function.
2. WAP to accept a string from the user and replace the 3rd character of string of
string with h.
4. WAP to fetch value from a user and add that value in an existing set.
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() -
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.
Lists –
A list is a collection which is ordered and changeable. In Python lists are written with
square brackets.
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 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.
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.
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’).
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()
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
insert(i,x) -This function is used to add the value(x) at the ith position specified in its
argument.
import array
# 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
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)
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.sort(reverse=True)
print(List)
5. Lambada Function
Example:
def cube(y):
return y*y*y
lambda_cube = lambda y: y*y*y
print(cube(5))
print(lambda_cube(5))
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 :
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)
# 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 :
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 –
def calArea(self):
return self.length * self.breadth
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
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")
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
.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')}