Sei sulla pagina 1di 9

Lab: Python

SDSS

Submitted by: Syed Ramiz Sami

Lab # 1
1.2
>>> radius = 1.5
>>> print radius
1.5
>>> pi = 3.14
>>> area = pi*radius*radius
>>> print area
7.0649999999999995
>>>
The answer was correct and it was done by giving values to variables step by step and the putting
them into the formula.

1.3
>>> ================================ RESTART ================================
>>>
7.065
>>>
>>> "%.1f" % 8.7
8.7

1.5
Question: What does the .1 between the first % and f do in the above expressions?
It tells the compiler to store 1 digit after decimal.

1.6
Question a: In which of the following order(s) was it possible for the 2 plusses and 1 minus to be
evaluated to get 10? In which was it not possible to get ten?
Ans: a. all + and - operators from left to right
Question: b. What effect did the round () brackets have on the order of evaluation?
Ans: The round brackets made the expression in brackets to be executed first.
c. How might you use brackets to get the same result you would get without brackets?
Ans: By using (8-5)-3

1.7
Question a: What does the * operator do with the operands 3 and 5?
Ans: It multiplies them

Lab: Python

SDSS

Submitted by: Syed Ramiz Sami

Question b: Which operation was carried out first, multiplication or addition?


Ans: Multiplication
Questions: c. If you asked someone who had learned about division, but not about fractions yet, "what
is 7 divided by 3?" which result would they give for the dividend and the remainder?
Ans: They would give 2 as dividend and 1 as remainder.

1.8
Questions: a. Describe in your own words how the slicing operator [start:end] applies to extracting
parts of the string object called: meal where start and end are starting and ending indexes for the slice.
Ans: The slicing operator takes the integer value of start and indexes to the startth character of the
string. After that it takes the integer till the endth character of the string and gives it as output.
b. What effect does leaving out start or end have on the slice?
Ans: In case of leaving start, it takes zero as the default value of start and in case of leaving out end, it
takes the last index as the end by default.
c. How would you specify a slice of meal that prints 'egg'?
Ans: meal [9:12]
d. What index value does start use for the first letter (s)?
Ans: 0
e. What do you think the len() function does?
Ans: It tells the total number of characters in a string.
f. Run Python to assign your full name (e.g. "Josiah Haddock Cheese") to a string object called name,
and use a slice operator to output just your middle name.
Ans:
Ramiz = "Syed Ramiz Sami"
print Ramiz [5:10]
g. Experiment with the slice [:-1] applied to your full name and write down what happens. Try again
with [:-2] . Try this operation on a string of different length. Write down your conclusions.
Ans: It takes the string from start and indexes to end value minus the value given with the negative
sign at the end part.

1.9
Question a: How would you print out the number of spoonfuls to exactly 2 decimal places?
Ans: >>> "I like %.2f spoonfuls of sugar in my coffee" % (3/2.0)
Question b: Explain in your own words the difference between %f, %d and %s when substituting
different types of variable object within strings. Use the Python interpreter to check what happens
when you use the wrong letter after % for the object you want to substitute and write what happens
in your logbook.

Lab: Python

SDSS

Submitted by: Syed Ramiz Sami

Ans: %f is used for printing floats, %d is used for printing integers, %s is used for printing characters
and strings.
Question c: Why were 2 % symbols needed after .1f to print out a single % symbol?
Ans: The 1st % symbol tells to print next value as it is and the 2nd % symbol tells to print % symbol.

Lab # 2
2.1
Area of circle with radius = 1 is 3.14
ValueError: invalid literal for int() with base 10: '1.5' was received when trying to calculate area of
circle with radius = 1.5.

2.2
Area of circle with radius = 1 is 3.14
Area of circle with radius = 1.5 is 7.065
Area of circle with radius = 2 is 12.56
Does the int() built in function accept floating point (fractional) values ?
Ans: Yes it does.
Does the float() built in function accept integer (whole number) values ?
Ans: Yes it does.
Which built in function seems more useful for this application and why ?
Ans: Float() function is more useful since it accepts both whole numbers and fractional values.
ValueError: could not convert string to float: fred was received when trying to calculate area of
circle with radius = fred.

2.3
Area of circle with radius = 1 is 3.14
Area of circle with radius = 1.5 is 7.065
Area of circle with radius = fred is you entered invalid input

2.4
Outputs from if1.py are:
39 = You failed
40 = You passed
99 = You passed

Lab: Python

SDSS

Submitted by: Syed Ramiz Sami

The program in if2.py gives a comment on marks. It first checks that if marks are less than 40. If that
condition is fulfilled, it prints fail and exits. If the condition of if is not fulfilled then it comes to the
first elif condition and checks if marks are less than 50. If the condition is fulfilled, it prints pass and
exits. If this condition is not fulfilled, it moves to next elif condition and checks if marks are less than
70. If this condition is met, it prints credit and exits. If no condition is fulfilled then it goes to else
condition and executes it by printing distinction and then finally exits.

2.5
The error obtained was TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'. It was
because it tried to perform mathematical operations to a string. The error occurred in line 3 where it
tried to multiply a string with some numbers and it was because we didnt tell the computer in line 2
to convert the input from string to any numeric data type(int or float).

2.6
Following was the output from first two programs:
Please enter your first nameramiz
Please enter your last namesami
Hello ramiz sami
What did the + operator do to the 2 strings? How would you join the 2 names together with a space
between them?
The operator + actually concatenated the two strings. Following statement will be used to join 2
names together with space between them:
name=fname+" "+lname
The output was:
Please enter your first nameramiz
Please enter your last namesami
ramiz sami

To print addresses in 3 lines:


line1=raw_input("Please enter your house number")
line2=raw_input("Please enter your street number")
line3=raw_input("Please enter your sector")
line4=raw_input("Please enter your postal code")
line5=raw_input("Please enter your name")
name=line5+",\n"+line1+",\n"+line2+",\n"+line3+",\n"+line4
print name

Lab: Python

SDSS

Submitted by: Syed Ramiz Sami

2.7
name=raw_input("Enter your name")
if name != "Aladdin":
print "go away"
else:
print "your wish is my command!"

2.8
name=raw_input("Please enter your name")
password=raw_input("Please enter your password")
if name == "Aladdin" and password == "sesame":
print "your wish is my command!"
else:
print "go away"

2.9
happy=raw_input("Are you happy? (enter y/n)")
if happy == "y" or happy == "Y":
print "great"
else:
print "sorry to hear that"

2.10
It checks whether the input number is out of the range(1-10). The statement checks if it is in the
range and the not keyword changes the result and tells that if it is out of range.

2.11
line1=raw_input("Please enter your house number")
line2=raw_input("Please enter your street number")
line3=raw_input("Please enter your sector")
line4=raw_input("Please enter your postal code")
line5=raw_input("Please enter your name")
f = open('fileworld.txt','w')
f.write(line5+",\n"+line1+",\n"+line2+",\n"+line3+",\n"+line4)
f.close()

Lab: Python

SDSS

Submitted by: Syed Ramiz Sami

2.12
f = open('data.txt','r')
a = float(f.readline())
b = float(f.readline())
c = float(f.readline())
f.close()

2.13
f = open('address.txt','r')
name = f.readline()
house= f.readline()
street = f.readline()
sector = f.readline()
postal = f.readline()
f.close()
phone=raw_input("Please enter your phone number")
f = open('address.txt','w')
f.write(name+"\n"+house+"\n"+street+"\n"+sector+"\n"+postal+",\n"+phone)
f.close()

Lab # 3
3.2
b
Using input() instead of raw_input() can be dangerous because input() returns the input as a python
expression.

c.
print "How many wheels does a Rakshaw have, and"
print "what is the colour of Pakistans flag ?"
print "What is the capital of Pakistan?"
print 'to answer 2 and red you would enter (2,"red")'
attempt=tuple(input())
correct=(3,"green", "islamabad")
if attempt==correct:

Lab: Python

SDSS

Submitted by: Syed Ramiz Sami

print "all answers are right"


else:
print "one or more wrong answer"

d.
name, age, height = "Fred",33, 1.92
print name, age, height

3.3
a.
prime = [2, 3, 5, 7]

b.
prime.append(11)
print prime

c.

d.
It appends the list item (b) at the end of list prime.

e.
You can index other elements of a list inside another list by using the following syntax:
primes [5][x]

3.4
a.
a = [1,2,3,4,5,6]

b.
c = a[2:4]

c.
b=a

Lab: Python

SDSS

Submitted by: Syed Ramiz Sami

d.
del a[2:4]

e.
a.insert (2, c[1])

3.5
a.
Start
20
200
-20
100

End
30
300
-30
10

Step
1
5
-1
-5

Function
Range(20,30,1)
Range(200,300,5)
Range(-20,-30,-1)
Range(100,10,-5)

b.
xrange takes more time as compared to range. That is because range makes list in memory and then
performs iterations whereas xrange does it without using any list so it is slower. Xrange is quicker in
handling part of a very large range because it starts without creating a list in memory.

3.6
a.
list = ["the","dead","parrot","sketch"]
list_size = len(list)
for i in range(list_size):
t = list[i][0]
t = (t.upper()) + (list[i][1:])
print(t) + " " + str(len (list[i]))

b.
list = ["the","dead","parrot","sketch"]
list_size = len(list)
for i in range(list_size):
t = list[i][:(i+1)]
t = (t.upper()) + (list[i][(i+1):])
print(t) + " " + str(len (list[i]))

3.7
import math
total=0.0
values=0
squareSum = 0
print ("enter numbers each followed by <enter> and 0 to stop ")
state = True
while state :
inputNo = float(input(": "))
total+= inputNo
squareSum += (inputNo * inputNo)
if inputNo == 0:
state = False
else:

Lab: Python

SDSS

Submitted by: Syed Ramiz Sami

values += 1
print ("total: %.2f" % total)
if values :
print ("average: %.2f" % (total/values))
print ("Sum of Squares: %.2f" % squareSum)
print ("Square Root of Sum of Squares: %.2f" % math.sqrt(squareSum))

3.8
a.
print ("even Numbers between 0 and 100: ")
for i in range(100):
if (i % 2) == 0:
print (str(i) + ",")

b.
print ("odd Numbers between 0 and 100: ")
for i in range(100):
if (i % 2) == 1:
print (str(i) + ",")

c.
a= raw_input ("Enter a number to get its table: ")
a = int(a)
for i in range(11):
b=a*i
print (str(b) + ",")

Potrebbero piacerti anche