Python is a multi-paradigm programming language created in 1989 by Guido van Rossum. It is based on ABC and Modula-3 and was named after Monty Python. Python has a simple syntax and dynamic typing and memory management. It can be used for web development, data science, scientific computing, and more. The core philosophy is summarized in the Zen of Python document. Python code is written, tested, and executed using integrated development environments like PyCharm or directly from the command line.
3. History
● Created in 1989 by Guido van Rossum.
● Created as a scripting language for administrative(OS) tasks.
● Based on All Basic Code (ABC) Language and Modula-3.
● Named after Monty Python’s Flying Circus ( A British comedy
series created by the comedy group ‘ Monty Python’ ).
● Released publicly in 1991.
● Guido takes the title “ Benevolent Dictator For Life “ (a title given
to a small number of open-source development leaders, typically
project founders who retain the final say in disputes or arguments
within the community )
5. Language Features
01 Python is a
- Multi-Paradigm Programming Language( Object-Oriented Programming and Structured
Programming are fully supported).
02 Many of its features support Functional Programming and aspect-oriented programming
(adding additional features to exciting code without modifying the code itself).
03 Python uses Dynamic Typing, Dynamic memory management.
6. Language Philosophy
The Language core’s philosophy is summarized in the document “ Zen of Python” ( a
collection of 20 software principles).
● Beautiful is better than ugly.
● Simple is better than complex.
● Complex is better than complicated.
● Errors should never pass silently.
● Special cases aren’t special enough to break the rule.
7. Language Usage
The python libraries made the python to be used in many fields like:
● Web Scraping
● Automation.
● AI, Machine learning, Data Science.
● Scientific Computing.
● System administration.
● Image and Text processing.
● Embedded systems.
● Hacking
● Graphical User Interfaces.
● Web Frameworks(Django, Flask).
● Mobile Development.
● Multimedia.
● Databases.
● Networking.
● Test Frameworks.
● ERP Systems ( Odoo ).
● Documentation (html to pdf,
Reporting )
8. Installing python
>> Sudo apt-get install python3
● Download from
https://www.python.org/do
wnloads/windows/
● Run the .exe file and have
fun.
PyCharm IDE
9. Syntax and Semantics
● Print statement >> print(‘Hello World!’)
● Variable assignment >> x, y, z = 1, 2.0, ‘ahmed’
Var = 5 if 10>20 else 10
● Expressions >> 1 + 2 ** 2 - 1 = 4
● Math Commands >>
min(x, y, z, ) -- max(x, y, z, ) → get maximum/minimum # from
items.
● Variables >> var = 5 / var = ‘python’ / var = 2.5 / var = [1, 3, 4]
● Input statement >> age = input(‘How old are you? ‘)
● Variable print statement >> print(‘Your age is:’, age)
● Variable deletion >> del x, y, z
10. Logic
● Logical expressions:
== (equals)
!= (not equals)
< (less than)
> (greater than)
<= (less than or equal)
>= (greater than or equal)
● Examples:
If 5 == 4:
print(‘true’)
If 5 > 3:
print(‘True’)
Else:
print(‘False’)
● Logical Operators: Combine logical expressions together.
&& > and
|| > or
! > not
● If age==22 and gpa>3.3:
print(‘Your are accepted for a master degree)
● If not 7<0:
print(‘7>0’)
● If x>5 and x<20: # This could be if 5 < x < 20
print(X)
11. Selection (if/else)
if statement: Executes a group of
statements only if a certain condition is true.
Otherwise, the statements are skipped.
● No need for () in the if statement
● Example:
gpa = 2.0
If gpa > 2.0:
print(“ your application is accepted”)
if/else statement: Executes one block of
statements if a certain condition is True, and a second
block of statements if it is False.
● Example:
gpa = 1.6
If gpa >3.0:
print(“your application is accepted”)
elif gpa >= 2.0 and gpa < 3.0:
print(‘You have to take our test’)
else:
print(‘Sorry, Your application is rejected’)
15. String Operations
● “PYTHON”.lower() # python
● “python”.upper() # PYTHON
● “python”.capitalize() # Python
● ‘python’.find(‘o’) # 4, Return -1 if not found.
● ‘Hello python world’.find(‘world) # 12
● ’Hello world’.find(‘l’, 4) # Start looking after 4 > 9
● “Hello, world”.split(‘,’) # [‘Hello’, ‘world’]
● “a.salama@gmail.com”.endswith(“.com”) # True
● “ahmed”.startswith(“A”) # False
● Names = [‘aml’, ‘ahmed’, ‘ali’]
‘ and ’.join(names) # ‘aml and ahmed and ali’
● Strings are read only >
X = ‘python’
X[0] = ‘C’ # Error, TypeError: 'str' object does not support item assignment
( Should be x = ‘C’ + x[1:] )
16. Tuples
● Tuples are immutable lists > Cannot be edited after creation
● Point = (x, y, z) # parenthesis are optional >> point = x, y, z
● Reversing tuple called unpaking > x, y, z = point
● yellow = (255, 255, 0) # r, g, b
● One = (1,) > Tuple with one element [ must write the comma ]
● Yellow[1:] > (255, 0)
● yellow[0] = 0 # Error, TypeError: 'tuple' object does not support item assignment
● Used for list zipping
Ex:
x_values = [3, 5, 7]
y_values = [ 1, 4, 6]
z_values = [5, 7, 10]
Domain = zip(x_values, y_values, z_values)
print(list(domain)) # [ (3, 1, 5), (5, 4, 7), (7, 6, 10) ]
17. Dictionary
● Dictionaries are lookup tables, They map a “key” to a “value”.
● Ex:
symbol_to_name = {
"H": "hydrogen",
"He": "helium",
"Li": "lithium",
"C": "carbon",
"O": "oxygen",
"N": "nitrogen"
}
● Duplicate keys are not allowed
● Duplicate values are just fine
● Keys can be any immutable value > numbers, strings, tuples.
and cannot be list, dictionary, set, ...
● Values can be any value > numbers, strings, tuples, frozenset, list,
dictionary.
● Nested Dictionary >> x = {0: {‘H’: [1, ‘x’, True]} }
18. Repetition (loops)
The ‘For’ Loop as range: for count in range(start, end):
Statements
● Python uses : and whitespace instead of {} or keywords to indicate a
block of code
● range(start, end) >> this function gives us a range of values and
automatically increase itself till end-1….. range(5) will take 0, 1, 2, 3, 4.
● range(start, end, step) >> range( 5, 50, 2) [ 5, 7, 9, etc.]
range(5, 0, -1) > 5, 4, 3, 2, 1
● Example:
for x in range(1, 6):
print(x, "squared is", x * x) # Can you guess the output ?!
19. Repetition (loops)
The ‘For’ Loop as part of group:
for item in itemsGroup:
Statements
● Example:
humans = [‘ahmed’, ‘ali’, ‘python’, ‘angle’]
for human in humans:
print("Hello, ", human)
20. Guess!
pythonDict = {0: ”A”, 1: “B”, 2: ”C”}
For key, value in pythonDict.items():
print(key, end=”:”)
print(value)
21. Functions
def name(arg1, arg2, ...):
"""documentation""" # optional doc string
Statements
return expression # from function
● def person(name, age, nationality=’egyptian’): # nationality is optional parameter
greeting = ‘hello, ‘ + name
return name, age, greeting
x, y, z = Person(age=22, name=’Ahmed’) # parameters not ordered, some not given
# x = ‘Ahmed’ / y = 22 / z = ‘hello, Ahmed’ >> you must assign the return values to eq. Vars.
● All parameters (arguments) in the Python language are passed by reference.
22. Anonymous Functions (Lambda)
● lambda [arg1 [,arg2,.....argn]]:one-line expression
● sum = lambda arg1, arg2: arg1 + arg2
print ("Value of total : ", sum( 10, 20 ))
24. Stack Class
class Stack:
"A well-known data structure…"
def __init__(self): # constructor
self.items = []
def push(self, x):
self.items.append(x) # the sky is the limit
def pop(self):
x = self.items[-1] # what happens if it’s empty?
del self.items[-1]
return x
def empty(self):
return len(self.items) == 0 # Boolean result
● x = Stack() # no 'new' operator!
● x.empty() # -> 1
● x.push(1) # [1]
● x.empty() # -> 0
● x.push("hello") # [1, "hello"]
● x.pop() # -> "hello" # [1]
● x.items # -> [1]
25. Keep track of your time
● We need to make a program that opens a song we love every an hour.
● Python uses webbrowser and time modules for this
import time
import webbrowser
br = 1*60*60
while True:
webbrowser.open("https://www.youtube.com/watch?v=M_kTSBqQkME")
time.sleep(br)
26. Turtle is the fastest animal in the world!
Let’s play with it!
27. Further reading
● Learning Python: Lutz, Ascher (O'Reilly '98)
● Python Essential Reference: Beazley (New Riders '99)
● Programming Python, 2nd Ed.: Lutz (O'Reilly '01)
● Core Python Programming: Chun (Prentice-Hall '00)
● The Quick Python Book: Harms, McDonald (Manning '99)
● The Standard Python Library: Lundh (O'Reilly '01)
● Python and Tkinter Programming: Grayson (Manning '00)
● Python Programming on Win32:
Hammond, Robinson (O'Reilly '00)
● Learn to Program Using Python: Gauld (Addison-W. '00)
● And many more titles...