0% found this document useful (0 votes)
2 views15 pages

Python Study Notes ESCP

Uploaded by

lou.desablins
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views15 pages

Python Study Notes ESCP

Uploaded by

lou.desablins
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming

Complete Study Notes

ESCP · Beginner Level · Targeting 4.0

Weeks 1–5 | Algorithms · Functions · OOP · Inheritance

■ Week 1 – Algorithms, Sequences, Variables, Conditions, Loops

■ Week 3 – Top-Down Analysis, Functions & Sub-programs

■ Week 4 – Object-Oriented Programming – Classes & Objects

■ Week 5 – Inheritance & Polymorphism

■ Mock Exam – Full Answer Key with Explanations


■ Week 1 – Algorithms, Variables, Conditions & Loops

1. What is an Algorithm?
An algorithm is an explicit, step-by-step recipe that solves a problem in a given set of situations. It is written in
pseudo-code (human-readable) before being translated into a programming language like Python.

■ Key idea: every necessary instruction must be stated explicitly — nothing can be left implicit.

2. Sequence of Instructions
The most basic form of an algorithm. Instructions execute top-to-bottom, one at a time.

# Python – sequence example


a = 3
b = 2
a = a + b # a is now 5
print(a) # displays 5

3. Variables
A variable is a named data container. In Python the type is inferred automatically.

Type Python example Notes

Integer age = 20 Whole numbers

Float price = 19.99 Use period, not comma

String (text) name = 'Alice' Always single quotes in course

Boolean flag = True True / False (capital T/F)

■ Assignment always overwrites the previous value. Use int(input(…)) to read a number from the user — input()
always returns text!

4. Conditional Structure (if / elif / else)


Allows the program to take different paths based on a condition.

x = int(input('Enter a number: '))


if x > 0:
print('Positive')
elif x == 0:
print('Zero')
else:
print('Negative')

■ Indentation is mandatory in Python. Use 4 spaces consistently — wrong indentation = syntax error.
Operator Meaning Example

== Equal to a == b

!= Not equal to a != b

< Less than a < b

<= Less than or equal a <= b

> Greater than a > b

>= Greater than or equal a >= b

5. Iterative Structure (while loop)


Used when you need to repeat instructions. The while loop is the most generic — it runs as long as its condition
is True.

# Print numbers 0 to 4
i = 0 # ① initialise BEFORE the loop
while i < 5: # ② test condition
print(i)
i = i + 1 # ③ update – NEVER forget this!

■ Three rules for while: ① initialise the counter before, ② write the correct condition, ③ update inside — otherwise
you get an infinite loop!

■ Mock Exam – Question 1 (trace this loop!)


a = 3
b = 2
i = 0
while i <= 5:
if a < 7:
a = a + b
else:
a = a + 3
i = i + 1
print(a)
Iteration i a (start) condition a<7? action i (end) a (end)

Start 0 3 – – 0 3

1 0 3 Yes a=3+2=5 0 5

2 0 5 Yes a=5+2=7 0 7

3 0 7 No a=7+3=10, i=1 1 10

4 1 10 No a=10+3=13, i=2 2 13

5 2 13 No a=13+3=16, i=3 3 16

6 3 16 No a=16+3=19, i=4 4 19

7 4 19 No a=19+3=22, i=5 5 22
8 5 22 No a=22+3=25, i=6 6 25

Loop ends (i=6


> 5) 6 25

■ ■ Answer: print(a) displays 25


■ Week 3 – Functions & Sub-programs

1. Top-Down Analysis
Break a big problem into smaller sub-problems, each solved by a dedicated function. This makes code
readable, reusable, and easier to test.

2. Defining and Calling a Function


# Definition
def function_name(param1, param2):
# local code
return result # optional

# Call
output = function_name(value1, value2)

Rule Detail

Local variables Created when function starts, deleted when it ends

Parameters Recognised by order, not by name at the call site

return Sends a value back; without it the function returns None

Types Must be respected rigorously (pass int where int expected)

3. Practical Examples
# Simple function – returns double
def twice(x):
res = x * 2
return res

a = twice(7) # a = 14
print(a) # displays 14

# Reading user input correctly


def do_double(x):
return x * 2

# CORRECT – convert input to int first


result = do_double(int(input('type a number')))
print(result)

■ input() always returns a string. Wrap it in int() or float() before passing to numeric functions. Forgetting this is
one of the most common beginner errors!

■ Mock – Q5: Which statement is true about twice(x)?


def twice(x):
res = x * 2
return res
a = twice(7)
print(a)

Optio
n Statement Correct?

A twice is a function, without any parameters ■

B twice is a function with two parameters 'res' and 'x' ■ res is local, not a parameter

C twice is a function with one parameter 'x' which returns a value ■

D twice is a class with one attribute ■

■ ■ Answer: Option C — one parameter (x), returns a value.

■ Mock – Q12: How to return the double of user input?


def do_double(x):
return x*2

■ ■ Answer: Option C — do_double(int(input('type a number')))


Option A fails because input() returns a string and x*2 on a string just repeats it.

■ Mock – Q14: What does fun(8, 0) return?


def fun(x, a):
return 2
num = fun(8,0)
print(num)

■ ■ Answer: 2 — the function always returns the literal 2, ignoring its parameters.
■ Week 4 – Object-Oriented Programming

1. Core Concepts
■ Class ■ Object

A blueprint/template describing a category of A concrete instance of a class. Multiple objects can


objects. Name starts with uppercase (e.g., Robot, be created from the same class.
BankAccount).

■ Attribute ■ Method

A variable attached to an object (e.g., name, A function defined inside a class that objects can
balance). By best practice, always private execute (e.g., deposit(), goForward()).
(__name).

2. Class Structure in Python


class BankAccount:
def __init__(self, b): # constructor – called on creation
self.__balance = b # private attribute (__ prefix)

def deposit(self, amount): # public method


self.__balance += amount

def getBalance(self): # getter


return self.__balance

# Main sequence
account = BankAccount(500) # creates object, balance=500
[Link](200) # balance=700
[Link](100) # balance=800
print([Link]()) # displays 800

■ ■ Mock Q15 answer: 800 (500 + 200 + 100)

3. Encapsulation – Public vs Private


Encapsulation means hiding internal details and exposing only what is necessary.

Visibility Syntax Accessible from

Public [Link] Anywhere

Private self.__name Only inside the class

# Getter and Setter pattern


def getName(self): # getter
return self.__name
def setName(self, new_name): # setter
self.__name = new_name

■ Mock Exam – OOP Questions


Q2 – An object is an instance of a class.
■ ■ Option A — True. A class is the template; an object is a specific realisation.

Q3 – Which code is valid given: class Example: def __init__(self, x): self.__num = x
■ ■ Option A — ex = Example(3) is valid. Option C fails because __num is private and cannot be accessed from
outside. Option B uses Java syntax (new). Option D passes no argument (constructor requires x).

Q4 – Example has __init__, attribute(), method(). How many methods/attributes?


■ ■ Option B — 3 methods: __init__, attribute, method. val is ONE attribute ([Link]). A common trap: don't count
self as a parameter.

Q6 – Dog class: __init__(self,a) sets [Link]=a; printDogAge(self) prints [Link]*7.


■ ■ Option C — d1=Dog(2); [Link]() is correct. Option A: wrong method name. Option B/D: printDogAge
takes no extra argument.

Q7 – Plant class: __init__(self,sp) sets self.__species=sp; species(self) prints it.


■ ■ Option A — 1 attribute (__species) and 2 methods (__init__ + species). Private attributes still count as ONE
attribute.

Q8 – A class may have…


■ ■ Option C — both methods AND attributes.

■ Mock Q17 – Which code works inside [Link](item)?


class Item:
def __init__(self, theReference, theName):
self.__ref = theReference
self.__name = theName
def getRef(self): return self.__ref
def getName(self): return self.__name

class Display:
def displayMyItem(self, item):
# ← which code here?

Optio
n Code Valid? Reason

A print('The name:', [Link]()) ■ Uses the public getter — correct!

B print('Name:' + item.__name) ■ __name is private; cannot access from outside


C print('Name:' + item.__name()) ■ Same issue + __name is not a method
■ Week 5 – Inheritance & Polymorphism

1. Inheritance
A child class automatically inherits all attributes and methods of its parent class. You only need to code what
is new or different.

class Person: # Parent


def __init__(self, fn, ln, by):
self.__firstName = fn
self.__lastName = ln
self.__birthYear = by
def getFirstName(self): return self.__firstName
def getLastName(self): return self.__lastName
def getBirthYear(self): return self.__birthYear

class Professor(Person): # Child – inherits from Person


def __init__(self, fn, ln, by, dept):
super().__init__(fn, ln, by) # call parent constructor
self.__department = dept
def getDepartment(self): return self.__department

class Student(Person): # Child – inherits from Person


def __init__(self, fn, ln, by, prog):
super().__init__(fn, ln, by)
self.__programme = prog
def getProgramme(self): return self.__programme

2. Adding email to Person (Mock Q – Week 5)


Since both Professor and Student need an email, add it to the Person class (DRY – Don't Repeat Yourself).

class Person:
def __init__(self, fn, ln, by, email): # add email param
self.__firstName = fn
self.__lastName = ln
self.__birthYear = by
self.__email = email # new attribute

def getEmail(self): return self.__email # getter


def setEmail(self, e): self.__email = e # setter

■ Rule: if an attribute is shared by ALL sub-classes, put it in the parent class. Child classes inherit it for free.

3. Polymorphism
Polymorphism lets different classes share the same method name but implement it differently. This allows you
to call the same method on objects of different types without knowing exactly which type.
class Person:
def introduce(self):
return f'Hi, I am {[Link]()}'

class Professor(Person):
def introduce(self): # overrides [Link]
return f'Prof {[Link]()}, dept {[Link]()}'

people = [Professor(...), Student(...)]


for p in people:
print([Link]()) # calls the right version automatically

4. Inheritance Summary Table


Concept Definition Python syntax

Parent class The class being inherited from class Animal:

Child class Inherits parent's attributes/methods class Dog(Animal):

super() Calls the parent's constructor super().__init__(…)

Override Redefine a method in the child def speak(self): …

Polymorphism Same method name, different behaviour [Link]() / [Link]()


■ Mock Exam – Remaining Questions & Answers

Q9 – What does the nested if print?


x = 4
if x < 5: # True (4<5)
if x > 8: # False (4>8) → go to else
print('Hola')
else:
if 3 > x: # False (3>4 is False) → go to else
print('Hello')
else:
print('Bonjour') ← THIS executes
else:

■ ■ Answer: Bonjour — Follow the branches: x<5 ✓, x>8 ✗, 3>x ✗ → else prints Bonjour.

Q10 – What does print(example_list[4]) display?


example_list = ['A', 'B', 'C', 'D']
print(example_list[4]) # list has indices 0,1,2,3 only

■ ■ Answer: IndexError: list index out of range — Valid indices are 0–3; index 4 does not exist.

Q11 – What list does this code create?


mylist = []
i = 0
while i <= 5: # runs for i=0,1,2,3,4,5
[Link](i)
i = i + 1

■ ■ Answer: [0, 1, 2, 3, 4, 5] — The loop runs while i ≤ 5, so 0 through 5 inclusive.

Q13 – Which value of y prints only vowels from the list?


x = 3
y = ???
list = ['B','M','C','e','D','G','i','H','J','o']
# 0 1 2 3 4 5 6 7 8 9
# Vowels at indices: 3(e), 6(i), 9(o)
# Pattern: 3, 6, 9 → step of 3 → y = 3

■ ■ Answer: y = 3 — Starting at x=3, adding 3 each time gives indices 3, 6, 9 → e, i, o.


Q16 – What is a Pandas DataFrame?
■ ■ Answer: Option A — A DataFrame is a two-dimensional labeled data structure with rows and columns,
similar to a spreadsheet table. (Option B describes a Series, which is one-dimensional.)
■ Quick Reference Cheat Sheet

Variables & Types


i = 0 # int
price = 9.99 # float
name = 'Alice' # str
flag = True # bool
x = int(input('n: ')) # read int from user

Conditional
if condition:

elif other_condition:

else:

While loop
i = 0 # ① init
while i < 5: # ② test
print(i)
i += 1 # ③ update

Function
def my_func(x, y):
result = x + y
return result

val = my_func(3, 4) # val=7

Class
class MyClass:
def __init__(self, x):
self.__x = x
def getX(self):
return self.__x
def setX(self, v):
self.__x = v

obj = MyClass(10)
[Link]() # 10

Inheritance
class Child(Parent):
def __init__(self, a, b):
super().__init__(a)
self.__b = b

List basics
lst = ['a', 'b', 'c']
lst[0] # 'a'
[Link]('d') # add to end
len(lst) # 4
# Indices: 0-based; max = len-1

■ Top 5 Common Mistakes


1. Wrong indentation Python uses indentation as structure — 4 spaces, consistently.

2. Forgetting int() input() returns a string. Always convert: int(input(…)).

3. Infinite loop Always initialise and update the while-loop variable.

4. Index out of range List indices go from 0 to len(list)−1. list[len(list)] crashes.

5. Accessing private self.__attr from outside the class raises an error. Use getters.

You might also like