100% found this document useful (1 vote)
1K views

Python Hands On

This document contains code snippets demonstrating various Python concepts including functions, namespaces, imports, ranges, data types (int, float, string), operations on lists, tuples, sets and dictionaries, loops (while, for), if/else conditional statements and more. The snippets provide examples of defining and calling functions, performing calculations, formatting and printing output.

Uploaded by

prashant pal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
1K views

Python Hands On

This document contains code snippets demonstrating various Python concepts including functions, namespaces, imports, ranges, data types (int, float, string), operations on lists, tuples, sets and dictionaries, loops (while, for), if/else conditional statements and more. The snippets provide examples of defining and calling functions, performing calculations, formatting and printing output.

Uploaded by

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

Python

(HandsOn)

CourseID: 55193
Print:
def Greet(Name):
# Write your code here
print("Welcome {}.\nIt is our pleasure inviting you.\nHave
a wonderful day.".format(Name))

Namespaces 1:
def Assign(i, f, s, b):
# Write your code here
w,x,y,z = i,f,s,b

print("{}\n{}\n{}\n{}".format(w,x,y,z))
print(dir())

Get Additional Info:


def docstring(functionname):
# Write your code here
help(functionname)

Namespaces 2:
def Prompt():
# Write your code here
x = input("Enter a STRING:\n")
print(x)
print(type(x))
Usage Imports:
import math

def calc(c):
# Write your code here
radius = c/(2*math.pi)
area = math.pi * (radius * radius)

return(round(radius,2), round(area,2))

Range 1:
def rangefunction(startvalue, endvalue, stepvalue):
# Write your code here
for i in range(startvalue, endvalue, stepvalue):
print(i*i,end="\t")

Using int:
def Integer_fun(a, b):
# Write your code here
c = int(a)
d = int(b)

print(type(a))
print(type(b))
print(c)
print(d)
print(type(c))
print(type(d))
Using int - Operations:
def find(num1, num2, num3):
# Write your code here
print(True if(num1<num2 and num2>=num3) else False,end=" ")
print(True if(num1>num2 and num2<=num3) else False,end=" ")
print(True if(num3==num1 and num1!=num2) else False)

Using int – Math Operations:


def Integer_Math(Side, Radius):
# Write your code here
pi = 3.14

squareArea = round(Side*Side,2)
cubeVolume = round(Side*Side*Side,2)
circleArea = round(pi*Radius*Radius,2)
sphereVolume = round((4*pi*Radius*Radius*Radius)/3,2)

print("Area of Square is {}".format(squareArea))


print("Volume of Cube is {}".format(cubeVolume))
print("Area of Circle is {}".format(circleArea))
print("Volume of Sphere is {}".format(sphereVolume))

Using float 1:
import math
def triangle(n1, n2, n3):
# Write your code here
area = (n1*n2)/2
return (round(area,n3), round(math.pi,n3))
Using float 2:
def Float_fun(f1, f2, Power):
# Write your code here
print("#Add\n{}".format(f1+f2))
print("#Subtract\n{}".format(f1-f2))
print("#Multiply\n{}".format(f1*f2))
print("#Divide\n{}".format(f2/f1))
print("#Remainder\n{}".format(f1%f2))
print("#To_The_Power_Of\n{}".format(f1**Power))
print("#Round\n{}".format(round(f1**Power,4)))

String Operations – 1
def stringoperation(fn, ln, para, number):
# Write your code here
n=number
print(fn+number*"\n"+ln)
print(fn+"\t"+ln)
print(fn*number);
print("The sentence is {}".format(para))

Newline & Tab Spacing:


def Escape(s1, s2, s3):
# Write your code here
s="Python\tRaw\nString\tConcept"

print("{}\n{}\n{}".format(s1,s2,s3))
print("{}\t{}\t{}".format(s1,s2,s3))
print(s)
print(r"Python\tRaw\nString\tConcept")
String Operations – 2
def resume(first, second, parent, city, phone, start, strfind,
string1):
first = first.replace(" ","")
second = second.replace(" ","")
parent = parent.replace(" ","")
city = city.replace(" ","")
phone = phone.replace(" ","")
First = first.title()
Second = second.title()
Parent = parent.title()

print(First+" "+Second+" "+Parent+" "+city)

if(phone.isdigit()):
print(True)
else:
print(False)

c=0
for i in range(len(start)):
if(start[i] == phone[i]):
c+=1

if(c == len(start)):
print(True)
else:
print(False)

full=first+second+parent+city
count = 0
for i in range(len(full)):
if(full[i]==strfind):
count+=1

print(count)
print(string1.split())
print(city.find(strfind))
List Operations 1:
def List_Op(Mylist, Mylist2):
# Write your code here
print(Mylist)
print(Mylist[1])
print(Mylist[-1])
Mylist.append(3)
Mylist[3] = 60
print(Mylist)
print(Mylist[1:5])
Mylist.append(Mylist2)
print(Mylist)
Mylist.extend(Mylist2)
print(Mylist)
Mylist.pop()
print(Mylist)
print(len(Mylist))

List Operations 2:
def tuplefunction(list1, list2, string1, n):
# Write your code here
tuple1 = tuple(list1)
tuple2 = tuple(list2)

mixTuple = tuple1 + tuple2


print(mixTuple)
print(mixTuple[4])

nestedTuple = ((tuple1,) + (tuple2,))


print(nestedTuple)
print(len(nestedTuple))

lst = []
lst.append(string1)
print(tuple(lst*n))
print(max(tuple1))
Slicing:
def sliceit(mylist):
# Write your code here
print(mylist[1:3])
print(mylist[1::2])
print(mylist[-1:-4:-1])

Range:
def generateList(startvalue, endvalue):
# Write your code here
lst = []
while(startvalue<=endvalue):
lst.append(startvalue)
startvalue+=1

print(lst[0:3])
print(lst[-1:-6:-1])
print(lst[0::4])
print(lst[-1::-2])
Set
def setOperation(seta, setb):
lst = []
a = set(seta)
b = set(setb)

if (len(a)<= 10000) and (len(b)<= 10000):


un = a.union(b)
inter = a.intersection(b)
diffa = a.difference(b)
diffb = b.difference(a)
symm = a ^ b
fset = frozenset(a)

lst.append(list(un))
lst.append(list(inter))
lst.append(list(diffa))
lst.append(list(diffb))
lst.append(list(symm))
lst.append(fset)

return lst

Dict:
def myDict(key1, value1, key2, value2, value3, key3):
# Write your code here
Dict = dict({key1:value1})
print(Dict)
Dict = dict({key1:value1, key2:value2})
print(Dict)
Dict[key1] = value3
print(Dict)
Dict.pop(key3)
return(Dict)
While Loop:
def calculateNTetrahedralNumber(startvalue, endvalue):
# Write your code here
lst = []
n=0;

while(startvalue<=endvalue):
n = startvalue
value = int(n*(n+1)*(n+2)/6)
lst.append(value)
startvalue = startvalue +1

return lst

For Loop:
def sumOfNFibonacciNumbers(n):
# Write your code here

if n==1:
return 0

List = [0,1]
f0 = 0
f1 = 1

while(n-2>0):
f2 = f1 + f0
List.append(f2)
f0 = f1
f1 = f2
n-=1

return sum(List)
Using If:
def calculateGrade(students_marks):
# Write your code here
lst = []
sum1 = 0

for i in range (students_marks_rows):


sum1=0
for j in range(students_marks_columns):
sum1 += students_marks[i][j]
avg = sum1/students_marks_columns

if(avg >= 90):


lst.append("A+")
elif(avg < 90 and avg >=80):
lst.append("A")
elif(avg < 80 and avg >=70):
lst.append("B")
elif(avg < 70 and avg >=60):
lst.append("C")
elif(avg < 60 and avg >=50):
lst.append("D")
elif (avg <50):
lst.append("F")

return lst

You might also like