SlideShare a Scribd company logo
Introduction to
Python
Ahmed Salama,Software Engineer at Ibtikar.
TOC
History
Language Features
Language Philosophy
Language Usage
Installing Python
Language Syntax
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 )
Python 2
● Released on
16 Oct. 2000
● Print ‘Hello’
● print(‘Hello’)
● 3 / 2 = 1
● 3 // 2 = 1
● 3 / 2.0 = 1.5
● 3 // 2.0 = 1.0
● Released on 3 Des.
2008.
● Initially called python
3000 or py3k.
● print(‘Hello’)
● 3 / 2 = 1.5
● 3 // 2 = 1
● 3 / 2.0 = 1.5
● 3 // 2.0 = 1.0
Python 3
2 to 3 Converter
Find more differences: https://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html
www.python.org
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.
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.
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 )
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
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
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)
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’)
Lists
● Flexible arrays >> L = [2.0, “name”, 20/2, 4*3-2, len(“hello”)]
● Multi list> a = [99, True, "bottles of beer", ["on", "the", "wall"]]
● [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] # concatenation
● [1, 2, 3] * 2 [1, 2, 3, 1, 2, 3] # repetition
● [1, 2, 3] [0] 1 # indexing
● [1, 2, 3][-1] 3 # (from end)
● [1, 2, 3, 4, 5][1:3] [2, 3] # slicing
● [1, 2, 3, 4, 5][2:] [3, 4, 5]
● [1, 2, 3, 4, 5][:3] [1, 2, 3]
● len([1, 2, 3, 4, 5]) 5 # size
● [1, 2, 3, 4] < [1,2,3] False # comparison
● 3 in [1, 2, 3, 4] True # search
● [1, 2, 3, 4][1:3] = [5, 6, 7, 8] > [1, 5, 6, 7, 8, 4]
Operations on lists
● a = range(5) # [0,1,2,3,4]
● a.append(5) # [0,1,2,3,4,5]
● a.pop() # [0,1,2,3,4] >> Remove 5 and return it
● a.insert(0, 42) # [42,0,1,2,3,4]
● a.pop(2) # [0,1,2,3,4] > Remove element from position >> removes 2 and return it
● a.reverse() # [4,3,2,1,0]
● a.sort() # [0,1,2,3,4]
Strings
● 'single quotes' OR """triple quotes""" OR "double quotes"
● "Hello" + "world" "helloworld" # concatenation
● "Hello" * 3 "hellohellohello" # repetition
● "hello"[0] "h" # indexing
● "hello"[-1] "o" # (from end)
● "hello"[1:4] "ell" # slicing
● “hello”[2:] “llo”
● “hello”[:3] “hell”
● len("hello") 5 # size
● "hello" < "jello" True # comparison
● "e" in "hello" True # search
● “@” not in “python” True
● "escapes: n, t, , etc"
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:] )
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) ]
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]} }
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 ?!
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)
Guess!
pythonDict = {0: ”A”, 1: “B”, 2: ”C”}
For key, value in pythonDict.items():
print(key, end=”:”)
print(value)
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.
Anonymous Functions (Lambda)
● lambda [arg1 [,arg2,.....argn]]:one-line expression
● sum = lambda arg1, arg2: arg1 + arg2
print ("Value of total : ", sum( 10, 20 ))
Classes
class name:
"Documentation”
Statements
-or-
class name(base1, base2, ...):
…
Most, statements are method definitions:
def name(self, arg1, arg2, ...):
…
May also be class variable assignments
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]
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)
Turtle is the fastest animal in the world!
Let’s play with it!
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...
Resources
● Programming Paradigm:
https://en.wikipedia.org/wiki/Programming_paradigm#Support_for_multiple_paradig
ms
● http://starship.python.net
● http://www.python.org/psa/bookstore/
Thank you!

More Related Content

Introduction to python

  • 2. TOC History Language Features Language Philosophy Language Usage Installing Python Language Syntax
  • 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 )
  • 4. Python 2 ● Released on 16 Oct. 2000 ● Print ‘Hello’ ● print(‘Hello’) ● 3 / 2 = 1 ● 3 // 2 = 1 ● 3 / 2.0 = 1.5 ● 3 // 2.0 = 1.0 ● Released on 3 Des. 2008. ● Initially called python 3000 or py3k. ● print(‘Hello’) ● 3 / 2 = 1.5 ● 3 // 2 = 1 ● 3 / 2.0 = 1.5 ● 3 // 2.0 = 1.0 Python 3 2 to 3 Converter Find more differences: https://sebastianraschka.com/Articles/2014_python_2_3_key_diff.html www.python.org
  • 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’)
  • 12. Lists ● Flexible arrays >> L = [2.0, “name”, 20/2, 4*3-2, len(“hello”)] ● Multi list> a = [99, True, "bottles of beer", ["on", "the", "wall"]] ● [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] # concatenation ● [1, 2, 3] * 2 [1, 2, 3, 1, 2, 3] # repetition ● [1, 2, 3] [0] 1 # indexing ● [1, 2, 3][-1] 3 # (from end) ● [1, 2, 3, 4, 5][1:3] [2, 3] # slicing ● [1, 2, 3, 4, 5][2:] [3, 4, 5] ● [1, 2, 3, 4, 5][:3] [1, 2, 3] ● len([1, 2, 3, 4, 5]) 5 # size ● [1, 2, 3, 4] < [1,2,3] False # comparison ● 3 in [1, 2, 3, 4] True # search ● [1, 2, 3, 4][1:3] = [5, 6, 7, 8] > [1, 5, 6, 7, 8, 4]
  • 13. Operations on lists ● a = range(5) # [0,1,2,3,4] ● a.append(5) # [0,1,2,3,4,5] ● a.pop() # [0,1,2,3,4] >> Remove 5 and return it ● a.insert(0, 42) # [42,0,1,2,3,4] ● a.pop(2) # [0,1,2,3,4] > Remove element from position >> removes 2 and return it ● a.reverse() # [4,3,2,1,0] ● a.sort() # [0,1,2,3,4]
  • 14. Strings ● 'single quotes' OR """triple quotes""" OR "double quotes" ● "Hello" + "world" "helloworld" # concatenation ● "Hello" * 3 "hellohellohello" # repetition ● "hello"[0] "h" # indexing ● "hello"[-1] "o" # (from end) ● "hello"[1:4] "ell" # slicing ● “hello”[2:] “llo” ● “hello”[:3] “hell” ● len("hello") 5 # size ● "hello" < "jello" True # comparison ● "e" in "hello" True # search ● “@” not in “python” True ● "escapes: n, t, , etc"
  • 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 ))
  • 23. Classes class name: "Documentation” Statements -or- class name(base1, base2, ...): … Most, statements are method definitions: def name(self, arg1, arg2, ...): … May also be class variable assignments
  • 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...