Python 101-PCEP Preparation
Python 101-PCEP Preparation
Prepration
Definition
• Machine Language: ones and zeros, the language that the computer
understand. So any code written in high-level programming language
should be interpretted/translated into machine language
• Translation is done in 2 different ways:
1- Compilation
the source code is translated one time and used globally, through a
compilar
2- Interprettation
the source code is translated each time it run
• Python is an interpreted language. This means that it inherits all the described advantages and
disadvantages. Of course, it adds some of its unique features to both sets.
• If you want to program in Python, you'll need the Python interpreter. You won't be able to run
your code without it. Fortunately, Python is free. This is one of its most important advantages.
• Due to historical reasons, languages designed to be utilized in the interpretation manner are often
called scripting languages, while the source programs encoded using them are called scripts
Python Story
What is Python?
Python is a widely-used, interpreted, object-oriented, and high-level programming language with dynamic
semantics, used for general-purpose programming. And while you may know the python as a large snake, the
name of the Python programming language comes from an old BBC television comedy sketch series
called Monty Python's Flying Circus.
Cython
One solution is to write your mathematical ideas using Python, and when you're absolutely sure that your code is
correct and produces valid results, you can translate it into "C". Certainly, "C" will run much faster than pure Python
Jython
"J" is for "Java". Imagine a Python written in Java instead of C. Jython can communicate with existing Java
infrastructure more effectively. This is why some projects find it useful and necessary.
Note: the current Jython implementation follows Python 2 standards. There is no Jython conforming to Python 3, so
far.
Hey, don’t
Panic; you
Don’t need them
All now
How to Install Python
• You can use python online without download using google colab:
https://colab.research.google.com/
• I am using Anaconda
https://www.anaconda.com/products/distribution
Functions in Python
A function (in this context) is a separate part of the computer code able to:
• cause some effect (e.g., send text to the terminal, create a file, draw an image,
play a sound, etc.); this is something completely unheard of in the world of
mathematics;
• evaluate a value (e.g., the square root of a value or the length of a given text)
and return it as the function's result; this is what makes Python functions the
relatives of mathematical concepts.
Functions Types
1- Built in : exist in python such as print
2- exist in specific modules : modules is like a big library of function
where they can be imported from that specific modules and used freely
within the code
3- wrriten by the user : yes, you can define your own function as well be
seen later
print() function
The first task in this module is to Print ‘ Hello,World!’
Print is a built-in function that used “as its name indicates” to printout variables
- To print anything : Print(xxx), Now you try to print Hello! World
print(”Hello,World!”)
- The “ “ is always associating string variables
- To produce a new line:
use empty print: print()
use escape character \n : print(“xxx\nyyy”)….. \ is called escape character, \n is a new line
- Note when print(“\”) : syntax error will appear, while print(“\\”) will print \
- To print more than 1 argument in the same line with space use commas btn arguments: print(x,’A’)
- end = “ x“
this argument is put at the end of print statement to separate the printed sentence according to the
argument x. ex:
print(“Hello”, end=“:”)
print(“World”)
Out >>> Afnan:Amayreh
- sep = “x”
to separate the outputted arguments
- Ex: print("Programming","Essentials","in",sep="***", end= "...")
print("Python")
out >>> Programming***Essentials***in...Python
Literals
A literal is data whose values are determined by the literal itself.
Famous Literals:
1- Integers : 1,2,3, ..
2- floats : 1.0, 0.5, …
3- strings : “Hi”
4- Boolean : True, False
5- None is a literal
Special Cases
• Zero-o at the beginning means that the number is in Octal (This means that the number must contain digits
taken from the [0..7] range only).
• print(0x123): out will be the decimal value, same for the Octal numbers
• 10^4 : in python 1e4
• \’, \”, \”\” : prints >>> ‘ , “, “” inside a print statement
Python 3.6 has introduced underscores in numeric literals, allowing for placing single underscores between digits
and after base specifiers for improved readability. This feature is not available in older versions of Python.
NOTE *
Therefore, you can write this number either like this: 11111111, or like that: 11_111_111.
And how do we code negative numbers in Python? As usual - by adding a minus. You can write: -11111111, or -
11_111_111.
Arithmatic Operators
Notes
• The + (plus) sign, when applied to two strings, becomes
• In case of *,**, and // a concatenation operator:
result is integer whenever the ‘a’+’a’ = aa
two arguments are both integers, • The * (asterisk) sign, when applied to a string and number
while the result is float when at (or a number and string, as it remains commutative in this
least 1 of the arguments is float position) becomes a replication operator:
• In case of / ‘a’*3 = aaa
the result is always float • Str(x) covert x into string
Shortcut Operators
Python offers you a shortened way of writing operations like these, which can be coded as follows:
x *= 2 instead of x = x*2
sheep += 1 instead of sheep = sheep+1
Arithmatic Operators – Binding
Definition
The binding of the operator determines the order of computations performed by some operators with
equal priority, put side by side in one expression.
Most of Python's operators have left-sided binding, which means that the calculation of the expression
is conducted from left to right.
Example:
print(2 ** 2 ** 3):
2 possible results
left-sided binding : 64
right-sided binding : 2**3 then 2**8 = 256 i.e. taking the two numbers on the right first
Parentheses
Any expression inside parentheses has the priority over the remaining.
Example:
print((5 * ((25 % 13) + 100) / (2 * 13)) // 2)
Variables
Definition
A remark inserted into the program, which
is omitted at runtime, is called
TipP
a comment; it begins with # sign.
If you'd like to quickly comment or uncomment
multiple lines of code, select the line(s) you wish to
modify and use the following keyboard
Example shortcut: CTRL + / (Windows) or CMD + / (Mac OS).
• Comparison Operators
below table contains the comparison operator that are used for decision making, where the result each time the
condition met is True, while it is False whenever the statement fails
Operator Meaning
== equality check;
!= not equal
< a<b, a less than b
<= a<=b, a less than or equal b
> a>b, a is greater than b
>= a>=b, a is greater than or equal b
Conditional sentences
• Conditional statements are statements which check if a condition is met or not, based on that a specific statement
is excuted
• While • Example
while repeats the execution as long as the condition evaluates # A program that reads a sequence of numbers
to True. # and counts how many numbers are even and how many are
odd.
# The program terminates when zero is entered.
While conditional_expression: odd_numbers = 0
instruction_one instruction_two even_numbers = 0
# Read the first number.
instruction_three number = int(input("Enter a number or type 0 to stop:
… instruction_n "))
# 0 terminates execution.
while number != 0:
# Check if the number is odd.
• Infinite Loop if number % 2 == 1:
An infinite loop, also called an endless loop, is a sequence of # Increase the odd_numbers counter.
odd_numbers += 1
instructions in a program which repeat indefinitely (loop else:
endlessly.) # Increase the even_numbers counter.
even_numbers += 1
while True: # Read the next number.
print("I'm stuck inside a loop.") number = int(input("Enter a number or type 0 to stop:
"))
# Print results.
print("Odd numbers count:", odd_numbers)
print("Even numbers count:", even_numbers)
Loops
• For Loop
• break
Another kind of loop available in Python comes from the exits the loop immediately, and unconditionally
observation that sometimes it's more important to count the ends the loop's operation; the program begins to
"turns" of the loop than to check the conditions. execute the nearest instruction after the loop's body;
for i in range(10): • continue
print("The value of i is currently", i) behaves as if the program has suddenly
reached the end of the body; the next turn is started
Note: and the condition expression is tested immediately.
• the loop has been executed ten times (it's (The continue statement is used to skip the current
the range() function's argument) block and move ahead to the next iteration, without
• the last control variable's value is 9 (not 10, as it executing the statements inside the loop.)
starts from 0, not from 1)
Bitwise operators
When finding the negation of any number, the following steps should be followed, it is the way how numbers stored
in python:
1- Convert the number into it’s binary format (consider always 5 bits)
2- reserve the least bit to signe (0: +ve , 1: -ve)
3- flip the bits
4- add 1 : 1+1 = 10
example: not 4 = -5
Lists
Out: 2
Lists Slicing
• A slice is an element of Python syntax that allows you to make a brand new copy of a list, or parts of a list.
• Syntax:
my_list[start:end], end here is the end element-1
ex:
my_list = [10, 8, 6, 4, 2]
new_list = my_list[1:3]
Note
print(new_list)
Ans: [8 6]
L = my_list : both lists will indicate the
• to copy all list’s contents : L[:] same location in the memory, whatever
• L [0:end] = L[:end] (no start means start from 0) change happens to 1 of them, the other
• L[start:] all the elements till the end got affected.
• In and not in: checks if a specific elements are in a list L = my_list[:] : contents of my_list will be
my_list = [0, 3, 12, 8, 2]
print(5 in my_list) : False
copied into L , different lists.
print(5 not in my_list) : True
print(12 in my_list): True
Examples
(1)
my_list = [17, 3, 11, 5, 1, 9, 7, 15, 13]
largest = my_list[0]
for i in my_list:
if i > largest:
largest = i
print(largest)
(2)
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
to_find = 5
found = False
for i in range(len(my_list)):
found = my_list[i] == to_find
if found:
break
if found:
print("Element found at index", i)
else:
print("absent")
Arrays
• 2-dimensional arrays
It's also called, by analogy to algebraic terms, a matrix.
Try this:
board = [[EMPTY for i in range(8)] for j in range(8)]
• 3-dimensional arrays
rooms = [[[False for r in range(20)] for f in range(15)] for t in range(3)]
Functions vs. methods
• Method is a specific kind of function, syntax : result = data.method(arg), data here represents the data that
owns the method
Examples
L.append(h) : it will add h t the end of the list L
L.insert(3,K) : inserting K at location3 in list L
• Function : result = funct(arg) >>> functions are not owned by data
• Function syntax:
def function_name():
function_body
• It's legal, and possible, to have a variable named the same as a function's parameter, in this case the
function parameter will shadow the variable inside the function i.e. the variable can’t be used inside the
func
• Python keyword
• When used inside a function it terminatess the function excution
• Don't forget this: if a function doesn't return a certain value using a return expression clause, it is assumed that it
implicitly returns None.
Ex:
def test1(a,b=1):
c = a+b
print(test1(2)). >> out: None
• Don't forget this: if a function doesn't return a certain value using a return expression clause, it is
assumed that it implicitly returns None.
Where do functions come from
Functions Invocation
def adding(a, b, c):
print(a, "+", b, "+", c, "=", a + b + c)
one unbreakable rule: you have to put positional arguments before keyword arguments
adding(3, c = 1, b = 2)
adding(4, 3, c = 2)
adding(3, a = 1, b = 2)
TypeError: adding() got multiple values for argument ‘a’
also:
Adding(a=1,b=2,3) : positional argument follows keyword argument
Variable scope
var = 1 var = 1
)(my_function my_function()
print(var) print(var)
Out: Out:
Do I know that variable: 2 Do I know that variable? 1
1 1
Global Variable
def my_function():
global var
var = 2
print("Do I know that variable?", var)
var = 1
my_function()
print(var)
Out :
Do I know that variable? 2
2
Some simple functions: Fibonacci numbers
Some simple functions: factorials
Some simple functions: recursion
recursion is a technique where a function invokes itself.
The Fibonacci numbers definition is a clear example of recursion.
def fib(n):
if n < 1:
return None
if n < 3:
return 1
return fib(n - 1) + fib(n - 2)
def factorial_function(n):
if n < 0:
return None
if n < 2:
return 1
return n * factorial_function(n - 1)
• You can use recursive functions in Python to write clean, elegant code, and divide it into smaller,
organized chunks. On the other hand, you need to be very careful as it might be easy to make a
mistake and create a function which never terminates. You also need to remember that recursive
calls consume a lot of memory, and therefore may sometimes be inefficient.
• Indexing: tuple[i]
•the len() function accepts tuples, and returns the number of elements contained inside;
•the + operator can join tuples together (we've shown you this already) : (1,2)+(3,4)=(1,2,3,4)
•the * operator can multiply tuples, just like lists: (1,2)*3 = (1,2,1,2,1,2)
•the in and not in operators work in the same way as in lists.
• error when trying to modify tuple:
AttributeError: 'tuple' object has no attribute 'append’
•Tup.count(2) will count the duplicates inside a tuple
Notes
• hanging indents.:
When you write a big or lengthy expression, it may be a good idea to keep it vertically
aligned. This is how you can make your code more readable and more programmer-
friendly, e.g.:
phone_numbers =
{
'boss': 5551234567,
'Suzy': 22657854310
}
•keys are case-sensitive: 'Suzy' is something different from 'suzy’.
•Trying to access non exist key will cause run time error
• Using Keys
for key in dictionary.keys(): Update dictionary:
…. 1- update existing item : dic [‘a’] = ‘b’
for key in sorted(dictionary.keys()): 2- add new item : dic[‘c’] = ‘d’
…. 3-to delete : del dic[‘a’]
Sorted() will sort keys 4- remove the last item: dic.popitem()
• Using items()
for a,b in dictionary.items():
….
A is the key, b is the value
• Using values()
for b in dictionary.values():
….
B is the value
The try-except branch
•the try keyword marks the place where you try to do something without permission;
•the except keyword starts a location where you can show off your apology talents.
try:
except:
Syntax example
try:
value = int(input('Enter a natural number: '))
print('The reciprocal of', value, 'is', 1/value)
except ValueError:
print('I do not know what to do.')
except ZeroDivisionError:
print('Division by zero is not allowed in our Universe.’)
except:
print('Something strange has happened here... Sorry!')
The 3rd except above is the default one, when none of the first 2 applies it will be valid
Error Types
ZeroDivisionError AttributeError
This appears when you try to force Python to perform any operation This exception arrives – among other occasions – when you try to
which provokes division in which the divider is zero, or is activate a method which doesn't exist in an item you're dealing with.
indistinguishable from zero. Note that there is more than one Python For example:
operator which may cause this exception to raise. Can you guess them short_list = [1]
all? short_list.append(2)
Yes, they are: /, //, and %. short_list.depend(3)
ValueError
Expect this exception when you're dealing with values which may be The third line of our example attempts to make use of a method
inappropriately used in some context. In general, this exception is which isn’t contained in the lists. This is the place
raised when a function (like int() or float()) receives an argument of a where AttributeError is raised.
proper type, but its value is unacceptable. SyntaxError
TypeError This exception is raised when the control reaches a line of code which
This exception shows up when you try to apply a data whose type violates Python's grammar. It may sound strange, but some errors of
cannot be accepted in the current context. Look at the example: this kind cannot be identified without first running the code. This kind
short_list = [1] of behavior is typical of interpreted languages – the interpreter
one_value = short_list[0.5] always works in a hurry and has no time to scan the whole source
code. It is content with checking the code which is currently being run.
An example of such a category of issues will be presented very soon.
It's a bad idea to handle this exception in your programs. You should
produce code that is free of syntax errors, instead of masking the
faults you’ve caused.
Debugging
Bug vs. debug print debugging
The basic measure a developer can use against bugs is – This form of debugging, which can be applied to your code
unsurprisingly – a debugger, while the process during which using any kind of debugger, is sometimes called interactive
bugs are removed from the code is called debugging. debugging. The meaning of the term is self-explanatory – the
According to an old joke, debugging is a complicated mystery process needs your (the developer's) interaction to be
game in which you are simultaneously the murderer, the performed.
detective, and – the most painful part of the intrigue – the Some other debugging techniques can be used to hunt bugs.
victim. Are you ready to play all these roles? Then you must It's possible that you aren't able or don't want to use a
arm yourself with a debugger. debugger (the reasons may vary). Are you helpless then?
A debugger is a specialized piece of software that can control Absolutely not!
how your program is executed. Using the debugger, you can You may use one of the simplest and the oldest (but still
execute your code line-by-line, inspect all the variables' states useful) debugging tactics known as print debugging. The
and change their values on demand without modifying the name speaks for itself – you just insert several
source code, stop program execution when certain conditions additional print() invocations inside your code to output data
are or aren't met, and do lots of other useful tasks. which illustrates the path your code is currently negotiating.
You can output the values of the variables which may affect
the execution.
Notes
• L1 = [1,2], L2 = [1,2], L1 is L2 >>> False, since they are 2 different variables while if we make L2 = L1 it’ll be True
Tests
https://www.edusum.com/python-institute/python-institute-entry-level-python-programmer-pcep-certification-sa
mple-questions