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

PPTX
Intro to Python Programming Language
PPTX
Object oriented programming in python
PPTX
Introduction to python
PPTX
Python basics
PDF
Datatypes in python
PPTX
Introduction to the basics of Python programming (part 1)
PPTX
Python
PDF
Python programming : Control statements
Intro to Python Programming Language
Object oriented programming in python
Introduction to python
Python basics
Datatypes in python
Introduction to the basics of Python programming (part 1)
Python
Python programming : Control statements

What's hot (20)

PPTX
Python Tutorial Part 1
PDF
Introduction to Python
PPTX
Object Oriented Programming in Python
PPTX
Control structures in java
PPTX
Member Function in C++
PDF
Introduction to c++ ppt 1
PDF
Object oriented approach in python programming
PDF
Python functions
PPTX
Python Exception Handling
PPT
Data types
PPTX
Class, object and inheritance in python
PPT
Abstract class in java
PDF
Introduction to python
PDF
An Introduction to Python Concurrency
PDF
Python Programming
PPT
Operators in C++
PPT
C++ Function
PPTX
PPTX
File handling in c++
Python Tutorial Part 1
Introduction to Python
Object Oriented Programming in Python
Control structures in java
Member Function in C++
Introduction to c++ ppt 1
Object oriented approach in python programming
Python functions
Python Exception Handling
Data types
Class, object and inheritance in python
Abstract class in java
Introduction to python
An Introduction to Python Concurrency
Python Programming
Operators in C++
C++ Function
File handling in c++
Ad

Similar to Introduction to python (20)

PDF
Introduction To Programming with Python
PPTX
Python Workshop - Learn Python the Hard Way
PPTX
Python bible
PDF
Python Part 1
PPT
Python tutorialfeb152012
PDF
ppt_pspp.pdf
PPTX
python_computer engineering_semester_computer_language.pptx
PPT
Python Kick Start
PPT
python within 50 page .ppt
PPTX
Python Demo.pptx
PPTX
Python chapter presentation details.pptx
PPTX
Python Scipy Numpy
PPTX
Python For Data Science.pptx
PPTX
Python Demo.pptx
PDF
Python: An introduction A summer workshop
PPTX
Introduction to Python , Overview
PDF
Pythonintro
PDF
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
PDF
Becoming a Pythonist
PPT
python language programming presentation
Introduction To Programming with Python
Python Workshop - Learn Python the Hard Way
Python bible
Python Part 1
Python tutorialfeb152012
ppt_pspp.pdf
python_computer engineering_semester_computer_language.pptx
Python Kick Start
python within 50 page .ppt
Python Demo.pptx
Python chapter presentation details.pptx
Python Scipy Numpy
Python For Data Science.pptx
Python Demo.pptx
Python: An introduction A summer workshop
Introduction to Python , Overview
Pythonintro
Q-Step_WS_02102019_Practical_introduction_to_Python.pdf
Becoming a Pythonist
python language programming presentation
Ad

More from Ahmed Salama (10)

PPTX
Introduction to Computer science and its fields
PDF
Seven Ways To Be a Healthy Programmer!.pdf
PDF
10 Code Anti-Patterns to Avoid in Software Development.pdf
PPTX
Introduction to web development
PPTX
Introduction to Django
PDF
Quick Start to marketing.
PPT
Distributed database
PPTX
Konard zuse
PPT
DDOS Attack
PDF
Introduction to Computer Science Department
Introduction to Computer science and its fields
Seven Ways To Be a Healthy Programmer!.pdf
10 Code Anti-Patterns to Avoid in Software Development.pdf
Introduction to web development
Introduction to Django
Quick Start to marketing.
Distributed database
Konard zuse
DDOS Attack
Introduction to Computer Science Department

Recently uploaded (20)

PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Empathic Computing: Creating Shared Understanding
PDF
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
PPTX
MYSQL Presentation for SQL database connectivity
PDF
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Big Data Technologies - Introduction.pptx
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
PDF
Advanced IT Governance
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPT
Teaching material agriculture food technology
PDF
Sensors and Actuators in IoT Systems using pdf
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Spectral efficient network and resource selection model in 5G networks
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Empathic Computing: Creating Shared Understanding
CIFDAQ's Market Wrap: Ethereum Leads, Bitcoin Lags, Institutions Shift
MYSQL Presentation for SQL database connectivity
GDG Cloud Iasi [PUBLIC] Florian Blaga - Unveiling the Evolution of Cybersecur...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Big Data Technologies - Introduction.pptx
Per capita expenditure prediction using model stacking based on satellite ima...
CIFDAQ's Market Insight: SEC Turns Pro Crypto
HCSP-Presales-Campus Network Planning and Design V1.0 Training Material-Witho...
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Advanced IT Governance
Chapter 3 Spatial Domain Image Processing.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
20250228 LYD VKU AI Blended-Learning.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Teaching material agriculture food technology
Sensors and Actuators in IoT Systems using pdf
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf

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’] ● “[email protected]”.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...
  • 28. 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/