Python Graphics Worksheet With Answers

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

ASTU

CSE

Work sheet for python

1. In a company XYZ there are employees called commissioned-salaried employee which is


paid their salary based on the fixed salary plus percent they sold. Suppose that there is a
list which contains the name, sell, percent and fixed _salary of 6 employee in this company.
The program uses a dictionary, where the key is the name of employee and value is a list
containing sell and percent and Fixed_salary of employee, like this {“seid”: [10000,
0.05,5000],”chala”: [2000,0.05,5000] …}.

Name Sell percent Fixed_salary

seid 10000 0.05 5000


chala 2000 0.05 5000
abenezer 4000 0.05 5000
abel 20000 0.05 5000
kebede 8000 0.05 5000
Mohammed 5000 0.05 5000

A. Calculate the salary of each employee (salary=fixed _ salary+(sell*percent)) and


append them to your original lists inside the dictionary: Similar to {“seid”: [10000,
0.05,5000,5500],”chala”: [2000,0.05,5000,5100] …}.

sellDict={"seid":[10000,0.05,5000], "chala":[2000,0.05,5000],
"abenezer":[4000,0.05,5000],"abel":[20000,0.05,5000],
"kebede":[8000,0.05,5000],"mohammed":[5000,0.05,5000]}
list1=[]
for key in sellDict:
list1=sellDict[key] # assigns the value mapped to each key to list1
for i in range (len(list1)): # get the element of the list
salary=int(list1[2]+list1[0]*list1[1]) # calculate the salary
sellDict[key].append(salary) # append the salary to the end of the list which is the
#value mapped to the current key
print sellDict

B. Print the dictionary in the following format


Name total salary

Introduction to computing Python worksheet Page 1


ASTU
CSE

Seid 5500
chala 5100
abenezer 5200
abel 6000
kebede 5400
mohammed 5250

sellDict={"seid":[10000,0.05,5000], "chala":[2000,0.05,5000],
"abenezer":[4000,0.05,5000],"abel":[20000,0.05,5000],
"kebede":[8000,0.05,5000],"mohammed":[5000,0.05,5000]}

list1=[]
for key in sellDict:
list1=sellDict[key]
for i in range (len(list1)):
salary=int(list1[2]+list1[0]*list1[1])
sellDict[key].append(salary)

print "%-10s %14s"%("Name","total salary")


List2=[]
for key in sellDict:
List2=sellDict[key]
print"%-10s %6d"% (key, List2[3])

C. Print top 3 employee which is highly paid


sellDict={"seid":[10000,0.05,5000], "chala":[2000,0.05,5000],
"abenezer":[4000,0.05,5000],"abel":[20000,0.05,5000],

Introduction to computing Python worksheet Page 2


ASTU
CSE

"kebede":[8000,0.05,5000],"mohammed":[5000,0.05,5000]}

List2=[]
list3=[]
key=None
list1=[]
for key in sellDict:
list1=sellDict[key]
for i in range (len(list1)):
salary=int(list1[2]+list1[0]*list1[1])
sellDict[key].append(salary)

print "%-10s %14s"%("Name","total salary")

for key in sellDict:


List2=sellDict[key]
list3.append(List2[3])
list3.sort()
for i in range(len(list3)-1,len(list3)-4,-1):
print list3[i]

D. Print total salary >5500


sellDict={"seid":[10000,0.05,5000], "chala":[2000,0.05,5000],
"abenezer":[4000,0.05,5000],"abel":[20000,0.05,5000],
"kebede":[8000,0.05,5000],"mohammed":[5000,0.05,5000]}

List2=[]
list3=[]
key=None

Introduction to computing Python worksheet Page 3


ASTU
CSE

list1=[]
for key in sellDict:
list1=sellDict[key]
for i in range (len(list1)):
salary=int(list1[2]+list1[0]*list1[1])
sellDict[key].append(salary)

print "%-10s %14s"%("Name","total salary")

for key in sellDict:


List2=sellDict[key]
list3.append(List2[3])
for i in list3:
if i>5500:
print"%-10s %6d"% (key, i)
2. Write a python program that check a word from a file is palindrome or not
def is_Palindrome(s):
start = 0
end = len(s) - 1
for i in range(len(s)/2):
if s[start] != s[end]:
return False
else:
start += 1
end -= 1
return True
is_Palindrome(“madam”) # prints True
is_Palindrome(“very”) # prints False

Introduction to computing Python worksheet Page 4


ASTU
CSE

3. Write a python program that read the following word in reverse order
Name=”I love python” after reverse name=”nohtyp evol I”
from __future__ import print_function
String= input("Input a word to reverse: ")
for char in range(len(String) - 1, -1, -1):
print(String[char], end="") print("\n")

4. What is the output of the following program


str1="hello" # str1 is a string type variable
str2="world" # str2 is a string type variable
str1 +=str2 # str1 +=str2 expression means str1=str1 + str2, + is concatenation when
applied to strings, so the answer is hello+world
print str1 helloworld
print len(str1) # The length of str1, which is number of characters in str1. The str1 values is
already changed to helloworld through concatenation. The length of str1 is 10.
print "helloworld" in str1 # “helloworld” is str1 means like is string “helloworld” is part of
string assigned to str1, so the answer True (bool value)
print str1.split() applying split() to any string S will divide string into word. Return a list of
the words in the string S, using sep as the delimiter string. But in this
case the value in str1 is helloworld which is consider as a single string. So the result is
[“helloworld”].
Example if we apply split() to msg="Hello Preengineering students.”
print msg.split(), it will return [‘Hello’,’Preengineering’,’students.’]
please check other function which can be applied to string type.

5. What is the output of the following program


from math import *

Introduction to computing Python worksheet Page 5


ASTU
CSE

def square_root(a, b=2,c=4):


x=sqrt(a*b*c)
print x
square_root(2)
square_root(2,8)
square_root(1,2,2)

In the function definition, parameters b, c are assigned a default value, b is assigned 2 and c
is assigned 4. So, when the function square_root() is called with just one argument, that
argument will be assigned to parameter a.
Square_root(2) # since the square_root() function is called with one argument, parameter
a is mapped to 2, parameter b and are mapped to the default values(b=2, c=4).
So the answer is 4.0
square_root (2,8) # since the square_root() function is called with two arguments,
parameter a is mapped to 2, parameter b is mapped to 8 and c is mapped to the default
values( c=4).
So the answer is 8.0
square_root (1,2,2) ) # since the square_root() function is called with three arguments,
each parameter , i.e., is mapped to respective argument, parameter a is mapped to 1,
parameter b is mapped to 2 and c is mapped to 2.
So the answer is 2.0

6. What is the output of the following program?


b=2
def calc():
for a in range(1,20,4): # the value is initialized to 1, condition runs until a’s value is 20,
a is increased by 2
if a%b==0: # if the modulo of a by b is zero then, it will multiple a with itself
and print a’s square. So a should be even number.
print a*a
else: # if a is not even then a should be odd. Which is true according
the definition of this function.
print a*b # a is multiplied with b

Introduction to computing Python worksheet Page 6


ASTU
CSE

calc() # The output will be: 1*2, 5*2, 9*2, 13*2, 17*2 which is
2
10
18
26
34

7. Write a Python program to get a string made of the first 2 and the last 2 chars from a given
a string. If the string length is less than 2, return instead of the empty string. 
Sample String : 'university'
Expected Result : 'unty'
Sample String : 'un'
Expected Result : 'unun'
def print_first2Last2(String):
if len(String)<2:
return
else:
str1=String[0:2]
str2=String[len(String)-2:len(String)]
str3=str1+str2
return str3
print print_first2Last2("university")# prints unty
print print_first2Last2("un")# prints unun
print print_first2Last2("u") # prints None

8. Write a Python program to get a string from a given string where all occurrences of its first
char have been changed to '$', except the first char itself.

def change_char(str1):
char = str1[0] # gets the first character of a given string.
str1 = str1.replace(char, '$') # replace first char if appeared
again in the given string. For example,
“communicationcommunication”, char 1 is ‘c’, all c’s except
first will be replaced with ‘$’ like
“communi$ation$ommuni$ation”
str1 = char + str1[1:]
return str1
print(change_char(' communicationcommunication '))
# output is “communi$ation$ommuni$ation”

Introduction to computing Python worksheet Page 7


ASTU
CSE

9. Write a Python function that takes a list of words and returns the length of the longest one.

mylist=[“hello”,”world”,”Introduction”,”computing”]
longest=len(mylist[0]) # initialize longest as the first element of the list. In-built function
len() is used to find a length of the string. Compare it with the remaining
element in the list.
for i in mylist:
if len(i)>longest:
longest=i
print longest

10. Write a Python program to get the largest number from a list.
mylist=[10,20,30,15,45,25,13,100,150,5]
largest=mylist[0] # initialize the first list element as the largest element and go through
the list to find the largest element through comparing
it with the remaining elements in the list.
for i in mylist:
if i>largest:
largest=i
print largest

11.  Write a Python program to get a list, sorted in increasing order by the last element in each
tuple from a given list of non-empty tuples. 
Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]

mylist=[(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)] # sample list
def last_element(mylist):
return mylist[-1] # to get the last value of each
#tuple in the list as element.
def sortList_bylast(tuples):
return sorted(tuples, key=last_element)

Introduction to computing Python worksheet Page 8


ASTU
CSE

print(sortList_bylast(mylist))

12. Write a Python program to remove duplicates from a list.


mylist=[‘a’,’b’,’c’,’a’,’c’,’c’] # sample list with duplicate items
dup_items = [] # empty list to store duplicate list items
uniq_items = [] # empty list to store unique list items

for x in mylist:
if x not in dup_items:
uniq_items.append(x) # add x to uniq_items[] list
dup_items.append(x) # add x to dup_items[] list
print(dup_items)

In program above, we populate both dup_items and uniq_items with same


element if not in dup_items list.

13. What is the output of the following program?


c = 1 # global as defined outside any function
def foo():
c = 0
c += 1 # changes c from 0 to 1, since c+=1 means c=c+1
print c

def bar():
global c
c += 1
print c

foo() # In the foo() function, variable c is defined on the left


side of the assignment and so, c is local to the function.
# so, the answer is 1
foo() # c is local, so still print c gives 1
foo() # c is local, so still print c gives 1
bar() # In bar(), as a key word global indicates the scope of the
variable is global, c is 1. So c+=1, is c=c+1, which is c=1+1=2
print c, displays 2
bar() # when function bar() is called again, as c is global
variable, its value is already changed to 2 in the first
bar() call, so the second call of bar() increases the c
value by 1 to 3. Print c, gives 3

Introduction to computing Python worksheet Page 9


ASTU
CSE

14. Draw the output of the following python program on the canvas.
from cs1graphics import *
paper=Canvas(300,350)
defdraw_face():
c=Circle(40,Point(170,170))
b=Path(Point(170,210),Point(170,280))
paper.add(c)
paper.add(b)
defdraw_leg():

leg=Path(Point(170,280),Point(170,320))
return leg
theleg=draw_leg()
leftleg=theleg.clone()
rightleg=theleg.clone()
leftleg.rotate(90)

Introduction to computing Python worksheet Page 10


ASTU
CSE

rightleg.rotate(-90)
paper.add(theleg)
paper.add(leftleg)
paper.add(rightleg)
draw_face()

You need to trace as in the figure above. I correct the code for you. Can=Canvas(300,350)
changed to paper=Canvas(300,350)
15. Write a Python script to print a dictionary where the keys are numbers between 1 and 15
(both included) and the values are square of keys.

Answer: since the questions requires to write a program to print the dictionary, we need
to write a program to create a diction first and then use print function to print the
dictionary.

Sample Dictionary 
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14:
196, 15: 225}

Introduction to computing Python worksheet Page 11


ASTU
CSE

One way is:

dict1 = {i:i**2 for i in range(1, 16)}


print dict1

OR

Defined an empty dictionary then populate it with values as follows:

dict1={}
for i in range(1, 16):
dict1[i]=i**2
print dict1

16. This program is for reflecting an object in cs1media

from cs1media import *


statue = load_picture("photos/statue1.jpg")
def reflection(img):
w, h = img.size()
for y in range(0,h):
for x in range(0, w/2):
pl = img.get(x, y)
pr = img.get(w-1-x, y)
img.set(x, y, pr)
img.show()

reflection(statue)

Run it and check and learn it. It is like seeing yourself in the mirror.

Introduction to computing Python worksheet Page 12


ASTU
CSE

Introduction to computing Python worksheet Page 13

You might also like