Jump to content

Python Concepts/Quizzes/Introduction

From Wikiversity

Python quiz — Introduction: It is sometimes said that Python is a very readable language. So if you have some previous experience with a programming language you might be able to guess and answer the following questions even though you haven't learnt Python. The Python prompt with the command from an interactive Python session is indicated with ">>>".

1 The following Python code

>>> 3 + 9

results in

12
An error: You need to make an assignment to a variable
Another result

2 The following Python code

>>> 2.0 + 2

results in

4
4.0
An error: You need to make a conversion between a float and an integer
Another result

3 The following Python code

>>> 9 % 2

results in

4.5
4
1
Another result

4 The following Python code

s = "Hello there"
a = s.islower()
b = s.lower()

results in

a is the boolean False
a is the boolean True
a is the string 'hello there'
b is the boolean False
b is the boolean True
b is the string 'hello there'

5 The following control structure

n = 3
if n == 2:
    print("Hello")
elif n == 3:
    print("World")
else: 
    print("Nothing")

results in

n is assigned to 2
The string "Hello" is printed to the standard out
The string "World" is printed to the standard out
The string "Nothing" is printed to the standard out

6 The following control structures

n = 3
if False:
    n += 2

n += 3
if True: 
    n += 4

results in 'n' being assigned

3
7
8
10
12
Another integer
An error since the first 'if' sentence is not completed.

7

def f(n):
    return n*n

a = f(2)

results in

A function "f" is defined
A integer "f" is defined
A variable 'a' is assigned the value of 4

8

a = [1, 2, 3]
a.extend([6, 8, 12])
if 8 in a:
    a.append(17)
else:
    a.append(18)

results 'a' being

[1, 2, 3]
[6, 8, 12]
[6, 8, 12, 17]
[6, 8, 12, 18]
[1, 2, 3, 6, 8, 12]
[1, 2, 3, 6, 8, 12, 17]
[1, 2, 3, 6, 8, 12, 18]
[1, 2, 3, 6, 8, 12, 17, 18]
An error
Other result

9

class Rational():
    def __init__(self, numerator, denominator):
        self.numerator = numerator
        self.denominator = denominator
    def __str__(self):
        return str(self.numerator) + '/' + str(self.denominator)
    def reduce(self, n):
        if (self.numerator % n)==0 and (self.denominator % n)==0:
            self.numerator /= n
            self.denominator /= n
             

r = Rational(3, 9)

True False
'Rational' is a function
'Rational' is a class
'__init__' is a constructor
'__init__' is a destructor
'reduce' is a method
'print(r)' will print '3'
'r.reduce(3); print(r)' will print '1/3'

10 The following code defines 3 variables

oeis = {'A000079': lambda x: 2**x} #
seq = [oeis['A000079'](n) for n in range(10)]
b = 'A000079' in oeis

It results in:

seq is list: [ <something in here> ]
'oeis' is a data structure that can be indexed by a string.
oeis['A000079'] is a function
'b' is True