0% found this document useful (0 votes)
159 views

Python 101-PCEP Preparation

"Hello" letter or an underscore

Uploaded by

Afnan Alamyreh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
159 views

Python 101-PCEP Preparation

"Hello" letter or an underscore

Uploaded by

Afnan Alamyreh
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Python 101 – PCEP

Prepration
Definition

• A programming language is a computer language that has a special syntax in order


for the computer to understand it and perform the requested.

• A program written in a high-level programming language (such as Python) is called


a source code (in contrast to the machine code executed by computers). Similarly,
the file containing the source code is called the source file.
Machine Language vs. Programming Language

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

Who Created Python?


The very first idea of Python came from Guido van Rossum, but many Python components have been
developed by  thousands (very often anonymous) programmers, testers, users (many of them aren't IT
specialists) and enthusiasts from all over the world.
Python Family
Python is known as Cpython too, since it was implemented at the beginning by C

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.

PyPy and RPython


It's a logo of the PyPy - a Python within a Python. In other words, it represents a Python environment written in
Python-like language named RPython (Restricted Python). It is actually a subset of Python.

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

• Zero-x for hexadecimal

• 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

Operator Meaning Priority


+ Addition 3
- subtraction 3
* multiplication 2
** exponent or Power. 1
/ division 2
// integer division: result is 2
always rounded to the less
integer
% modulo 2

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: Variable’s Name conditions


variable is a literal that carries number and text values, it is • the name of the variable must be composed of
like a box/container that has a value inside. upper-case or lower-case letters, digits, and the
character _ (underscore)
Example • the name of the variable must begin with a
letter;
a = 3.0 • the underscore character is a letter;
b = 4.0 • upper- and lower-case letters are treated as
c = (a ** 2 + b ** 2) ** 0.5 different (a little differently than in the real world
print("c =", c) - Alice and ALICE are the same first names, but in
Python they are two different variable names,
and consequently, two different variables);
• the name of the variable must not be any of
Python's reserved words (the keywords - we'll
explain more about this soon). Such as: ['False',
'None', 'True', 'and', 'as', 'assert', 'break', 'class',
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for',
'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with',
'yield’].
Comments

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

# This program evaluates the hypotenuse c.


# a and b are the lengths of the legs.
a = 3.0
b = 4.0
c = (a ** 2 + b ** 2) ** 0.5 # We use **
instead of square root.
print("c =", c)
Input() function.. and other things
input() Examples

• The input() function is able to read data entered by # Testing TypeError message.


the user and to return the same data to the running anything = input("Enter a number: ")
program. something = anything ** 2.0
• To assign a value inserted by the user to a specific variable : print(anything, "to the power of 2 is", something)
x = input() or input(‘insert a value’), x is always string in this
case
• To convert it into int or float, simply use the functions int(),
float() i.e. x = int(input(“insert any value”)) # example2
anything = float(input("Enter a number: "))
something = anything ** 2.0
print(anything, "to the power of 2 is", something)
Decision Making

• 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

• If Syntax • elif statement


if true_or_not: elif is used to check more than just one
do_this_if_true condition, and to stop when the first
Example statement which is true is found.
if sheep_counter >= 120:
sleep_and_dream() if the_weather_is_good:
• If-else statement go_for_a_walk()
else here is added to have plan B, i.e. if the condition elif tickets_are_available:
in if statement is not met, then do something else as go_to_the_theater()
will be defined by else statement. elif table_is_available:
if true_or_false_condition: go_for_lunch()
perform_if_condition_true else: play_chess_at_home()
else:
perform_if_condition_false
Loops

• 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

• & requires exactly two 1s to provide 1 as the result;


• | requires at least one 1 to provide 1 as the result;
• ^ requires exactly one 1 to provide 1 as the result.
• Bitwise shift operators are used to shift numbers in
binary format; in general, shift left is multiplying by 2 (1
bit is * 2, 2bits is *4), while shifting right is dividing by 2.

Ans: 17, 68(17*4 since shift 2 bits), 8 (shift 1 bit)


Not bitwise

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

• Definition: • To reverse list arguments


List is a multi-value variable, mutable
variable_1, variable_2 = variable_2, variable_1
sequential variable between [ ]
• Syntax: • To Sort ascending
L = [x,y,z] L.sort()
• Indexing: • To reverse
L[0]=x, L[1]=y, L[2]=z L.reverse()
• List length:
len(L)
• Removing list member:
del L[0]
• Reverse index:
Note
L[-1]=z, L[-2]=y •the name of an ordinary variable is the name of its content;
•the name of a list is the name of a memory location where the list is stored. The sol for that is slicing
Ex: list_1 = [1]
list_2 = list_1
list_1[0] = 2
print(list_2)

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

• Array is a list inside list


Ex: array = [[x for i in range(5)] for j in range(5)]

• 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

• You can pass arguments to a function using the following techniques:


1- positional argument passing in which the order of arguments passed matters . Ex :func (1,2)
2- keyword (named) argument passing in which the order of arguments passed doesn't matter func(a=1,b=2),
3- a mix of positional and keyword argument passing ex. Func (1,b=2) ,
note: when a non default parameter follows a defualt parameter that’s a syntax error. Ex : func (a=1,b)
• / at the end of a sentence in a code means continue the sentence on the following line.
Return

• 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

• Lists can be functions’ arguments


None
 None is a keyword.
There are only two kinds of circumstances when None can be safely used:
•when you assign it to a variable (or return it as a function's result)
•when you compare it with a variable to diagnose its internal state.

• 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)

1- Positional invocation : adding(1, 2, 3)


2- Keword arguments : adding(c = 1, a = 2, b = 3)
3- Mix : adding(3, c = 1, b = 2)

 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

:)(def my_function def my_function():


var = 2
print("Do I know that variable?", var) print("Do I know that variable?", var)

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.

def factorial(n): def factorial(n): if n == 1: # The


return n * factorial(n - 1) print(factorial(4)) base case (termination
condition.) return 1 else:
return n * factorial(n - 1)
No termination function so the following error appear:
print(factorial(4)) # 4 * 3 * 2
The factorial function has no termination condition (no * 1 = 24
base case) so Python will raise an exception
(RecursionError: maximum recursion depth exceeded)
Tuples

• Sequential data (the one that can be scanned by for loop)


• Tuples are immutable
• Syntax:
tuple_1 = (1, 2, 4, 8)
tuple_2 = 1., .5, .25, .125

• Note : , should exist to distinguish 1 element tuple from 1 value


one_element_tuple_1 = (1, )
one_element_tuple_2 = 1.,

• 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

• To convert a list into tuple : tup = tuple(list)


• To convert to a dict : xxx = dict(yyy)
• To copy :
dict_copy = dict.copy()
• To clear dict’s items:
dict.clear()
Dictionary
• A real dictionary with key and value, no sequential, and mutable
• Syntax
phone_numbers = {'boss': 5551234567, 'Suzy': 22657854310}

• Indexing is by the key value:


phone_numbers[‘boss’] or phone_numbers.get(‘boss’)

• In and not in can be used with dictionaries

• 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

•To add an item to a dict:


dict[‘a’] = ‘v’
dict.update(‘a’:’v’)
For loop with Dictionary

• 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:

value = int(input('Enter a natural number: '))

print('The reciprocal of', value, 'is', 1/value)

except:

print('I do not know what to do.')


More than 1 exeption

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

You might also like