Pythonbasics Exercise Answers
Pythonbasics Exercise Answers
print("Albert")
print("line 1")
print("line 1")
print("line 1")
Variables
Display several numbers
x = 5
y = 6
print(x)
print(y)
print(8)
x = 64 + 32
print(x)
create a program that sums x + y
x = 3
y = 4
z = x + y
print(x)
Strings
Print the word lucky inside s
_
_
_
_
_
Random numbers
Make a program that creates a random number and stores it into x.
import random
x = random.randrange(0,10)
print(x)
import random as r
print(r.randrange(0,10))
print(r.randrange(0,10))
print(r.randrange(0,10))
Keyboard input
Make a program that asks a phone number.
If statements
Exercise 1
x = input("Number: ")
Exercise 2
if password == "code":
print("Correct")
else:
print("Incorrect")
_
_
_
_
For loop
solution
clist = ['Canada','USA','Mexico','Australia']
for c in clist:
print(c)
While loop
clist = ["Canada","USA","Mexico"]
size = len(clist)
i = 0
we combined a while loop with a list. don’t forget to increase the iterator (i).
Functions
Solution for exercise 1
#!/usr/bin/env python3
def sum(list):
sum = 0
for e in list:
sum = sum + e
return sum
mylist = [1,2,3,4,5]
print(sum(mylist))
_
_
_
_
_
_
_
_
_
_
_
_
_
_
_
Lists
Display every state
states = [
'Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','
Delaware','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kan
sas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minn
esota','Mississippi','Missouri','Montana','Nebraska','Nevada','New
Hampshire','New Jersey','New Mexico','New York','North Carolina','North
Dakota','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South
Carolina','South
Dakota','Tennessee','Texas','Utah','Vermont','Virginia','Washington','West
Virginia','Wisconsin','Wyoming' ]
List operations
Exercises 1 and 2
y = [6,4,2]
y.append(12)
y.append(8)
y.append(4)
y[1] = 3
print(y)
Sorting
sorting on first element
x = [ (3,6),(4,7),(5,9),(8,4),(3,1)]
x.sort()
You can sort on the 2nd element with the operator module.
_
_
_
Range
Large list
x = list(range(1,1001))
print(x)
x = list(range(1,1001))
print(min(x))
print(max(x))
Two lists
x = list(range(1,11,2))
y = list(range(2,11,2))
print(x)
print(y)
Dictionary
Map country to short codes
words = {}
words["US"] = "United States"
words["UK"] = "United Kingdom"
words["AUS"] = "Australia"
Read file
Solution
filename = "test.py"
with open(filename) as f:
lines = f.readlines()
i = 1
for line in lines:
print(str(i) + " " + line),
i = i + 1
_
Write file
Solution
f = open("test.txt","w")
f.write("Take it easy\n")
f.close()
f = open("test.txt","w")
f.write("open(\"text.txt\")\n")
f.close()
Nested loops
Solution nested loop
for x in range(1,4):
for y in range(1,4):
print(str(x) + "," + str(y))
Meeting
for p1 in persons:
for p2 in persons:
print(p1 + " meets " + p2)
O(n)^2
Slices
Slices
pizzas = ["Hawai","Pepperoni","Fromaggi","Napolitana","Diavoli"]
slice = pizzas[2]
print(slice)
slice = pizzas[3:5]
print(slice)
Slicing with text
s = "Hello World"
slices = s.split(" ")
print(slices[1])
_
_
_
_
_
Multiple return
Return a+b
def sum(a,b):
return a+b
print( sum(2,4) )
def getUser():
name = "Laura"
age = 26
job = "Pilot"
education = "University"
nationality = "Spain"
data = getUser()
print(data)
Scope
Return global variable using a function
balance = 10
def reduceAmount(x):
global balance
balance = balance - x
reduceAmount(1)
print(balance)
local variable function
def calculate():
x = 3
y = 5
return x+y
x = calculate()
print(x)
_
_
_
_
_
Time and date
Return global variable using a function
import time
timenow = time.localtime(time.time())
year,month,day,hour,minute = timenow[0:5]
print(str(year) + "-" + str(month) + "-" + str(day))
Class
Yes, a python file can define more than one class.
Yes, you can create multiple objects from the same class
Objects cannot create classes, but you can create objects from classes
Object creation
example = Website('archive.org')
example.showTitle()
#!/usr/bin/python
class Website:
def __init__(self,title):
self.title = title
self.location = "the web"
def showTitle(self):
print(self.title)
def showLocation(self):
print(self.location)
obj = Website('pythonbasics.org')
obj.showTitle()
obj.showLocation()
Constructor
Solution for exercise
Alice = Human()
Chris = Human()
second solution
class Human:
def __init__(self):
self.legs = 2
self.arms = 2
self.eyes = 2
Getter and setter
Display several numbers
class Friend:
def __init__(self):
self.job = "None"
self.age = 0
def getJob(self):
return self.job
def getAge(self):
return self.age
Alice = Friend()
Alice.setJob("Carpenter")
Alice.setAge(33)
print(Alice.job)
print(Alice.age)
A getter and setter help you to create clean code. By calling the methods instead of changing
variables, you can prevent accidentally changing the variable to a number you do not want.
Say you have a class Human with a variable age, in the setter you could prevent the variable
from being set to negative numbers of numbers higher than 150 using an if statement.
Modules
Display several numbers
import math
print(math.sin(3))
Inheritance
first exercise
class iPhone(App):
def getVersion(self):
print('iPhone version')
multiple inheritance
#!/usr/bin/python
class A:
def start(self):
print('starting')
class B:
def go(self):
print('go')
class C(A,B):
def getVersion(self):
print('Multiple inheritance class')
app = C()
app.start()
app.go()
Enummerate
for loop with enumerable
Static methods
Yes, such a method is a static method
Because static methods go against the paradigm of object orientation. The general consensus
is that objects are created from classes. The objects methods are defined in the class. If you
create a static method, that method is accessible without creating an object.
Iterable
an object that can be used as a sequence lists, strings, dictionaries and sets
Classmethod
a method that's accessible by all objects and the class
a static method doesn't have access to the class
Multiple inheritance
No, only some programming languages support multiple inheritance.
It increases cohesion between the classes. If you have very strong cohesion throughout your
code, your classes are not reusable in other projects.
No, there is no limit.