Download answers

Share to download answers.

Execute Python Scripts

  1. Print your name

    print("Albert")
  2. Print song lyrics

    print("line 1")
    print("line 1")
    print("line 1")

Variables

  1. Display several numbers

    x = 5
    y = 6

    print(x)
    print(y)
    print(8)
  2. shows the summation of 64 + 32.

    x = 64 + 32
    print(x)
  3. create a program that sums x + y

    x = 3
    y = 4
    z = x + y
    print(x)

Strings

  1. Print the word lucky inside s

    s = "My lucky number is %d, what is yours?" % 7
    print(s[3:8])
  2. Print the day, month, year

    s = "The date is %d/%d/%d" % (7, 7, 2016)
    print(s)

Random numbers

  1. Make a program that creates a random number and stores it into x.

    import random

    x = random.randrange(0,10)
    print(x)
  2. Make a program that prints \3 random numbers.

    import random as r

    print(r.randrange(0,10))
    print(r.randrange(0,10))
    print(r.randrange(0,10))

Keyboard input

  1. Make a program that asks a phone number.

    number = input("Enter number: ")
    print("Your phone number is : " + number)
  2. Make a program that asks the users preferred programming language.

    lang = input("Python or Ruby?: ")
    print("You chose : " + lang)

If statements

  1. Exercise 1

    x = input("Number: ")

    if x < 0 or x > 10:
    print("Invalid number")
    else:
    print("Good choice")
  2. Exercise 2

    password = raw_input("Password: ")

    if password == "code":
    print("Correct")
    else:
    print("Incorrect")

For loop

  1. solution
    clist = ['Canada','USA','Mexico','Australia']
    for c in clist:
    print(c)

While loop

  1. Solution for exercise
    clist = ["Canada","USA","Mexico"]
    size = len(clist)
    i = 0

    while i < size:
    print(clist[i])
    i = i + 1

we combined a while loop with a list. don’t forget to increase the iterator (i).

Functions

  1. Solution for exercise 1
    #!/usr/bin/env python3

    def sum(list):
    sum = 0
    for l in list:
    sum = sum + l
    return sum

    mylist = [1,2,3,4,5]
    print(sum(mylist))

Lists

  1. Display every state

    states = [ 'Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','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' ] 

    for state in states:
    print(state)
  2. Display all states starting with letter m

    for state in states:
    if state[0] == 'M':
    print(state)

List operations

  1. Exercises 1 and 2
    y = [6,4,2]
    y.append(12)
    y.append(8)
    y.append(4)
    y[1] = 3
    print(y)

Sorting

  1. sorting on first element

    x = [ (3,6),(4,7),(5,9),(8,4),(3,1)]
    x.sort()
  2. sorting on second element

    You can sort on the 2nd element with the operator module.

    from operator import itemgetter
    x = [ (3,6),(4,7),(5,9),(8,4),(3,1)]
    x.sort(key=itemgetter(1))
    print(x)

Range

  1. Large list
    x = list(range(1,1001))
    print(x)
  2. Smallest and largest number
    x = list(range(1,1001))
    print(min(x))
    print(max(x))
  3. Two lists
    x = list(range(1,11,2))
    y = list(range(2,11,2))
    print(x)
    print(y)

Dictionary

  1. Map country to short codes

    words["US"] = "United States"
    words["UK"] = "United Kingdom"
    words["AUS"] = "Australia"
  2. Print each item

    words = {}
    words["US"] = "United States"
    words["UK"] = "United Kingdom"
    words["AUS"] = "Australia"

    for key, value in words.items():
    print(key + " = " + value)

Read file

  1. 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

  1. Solution

    f = open("test.txt","w")
    f.write("Take it easy\n")
    f.close()
  2. writing special characters

    f = open("test.txt","w")
    f.write("open(\"text.txt\")\n")
    f.close()

Nested loops

  1. Solution nested loop

    for x in range(1,4):
    for y in range(1,4):
    print(str(x) + "," + str(y))
  2. Meeting

    persons = [ "John", "Marissa", "Pete", "Dayton" ]

    for p1 in persons:
    for p2 in persons:
    print(p1 + " meets " + p2)
  3. O(n)^2

Slices

  1. Slices

    pizzas = ["Hawai","Pepperoni","Fromaggi","Napolitana","Diavoli"]

    slice = pizzas[2]
    print(slice)

    slice = pizzas[3:5]
    print(slice)
  2. Slicing with text

    s = "Hello World"
    slices = s.split(" ")
    print(slices[1])

Multiple return

  1. Return a+b

    def sum(a,b):
    return a+b

    print( sum(2,4) )
  2. Create a function that returns 5 variables

    def getUser():
    name = "Laura"
    age = 26
    job = "Pilot"
    education = "University"
    nationality = "Spain"

    return name,age,job,education, nationality

    data = getUser()
    print(data)

Scope

  1. Return global variable using a function

    balance = 10

    def reduceAmount(x):
    global balance
    balance = balance - x

    reduceAmount(1)
    print(balance)
  2. local variable function

    def calculate():
    x = 3
    y = 5

    return x+y

    x = calculate()
    print(x)

Time and date

  1. 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

  1. Object creation

    example = Website('archive.org')
    example.showTitle()
  2. add a method to the class

    #!/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

  1. Solution for exercise

    Alice = Human()
    Chris = Human()
  2. second solution

    class Human:
    def __init__(self):
    self.legs = 2
    self.arms = 2
    self.eyes = 2

Getter and setter

  1. Display several numbers

    class Friend:
    def __init__(self):
    self.job = "None"
    self.age = 0

    def getJob(self):
    return self.job

    def setJob(self, job):
    self.job = job

    def getAge(self):
    return self.age

    def setAge(self, age):
    self.age = age

    Alice = Friend()
    Alice.setJob("Carpenter")
    Alice.setAge(33)
    print(Alice.job)
    print(Alice.age)

Modules

  1. Display several numbers
    import math

    print(math.sin(3))

Inheritance

  1. first exercise

    class iPhone(App):
    def getVersion(self):
    print('iPhone version')
  2. 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

  1. for loop with enumerable
    for item in enumerate(["a", "b", "c","d"]):
    print(item)