SlideShare une entreprise Scribd logo
1  sur  49
Télécharger pour lire hors ligne
Prepared by: Mohamed AbdAllah
Raspberry pi interfacing
Lecture 5: Python for raspberry pi
1
Python Agenda
 Python syntax.
 Strings and console output.
 Conditional and control flow.
 Functions.
 Lists and dictionaries.
 Loops.
 Bitwise operators.
 Classes.
 File Input/output
2
Python Agenda
3
Python syntax
4
 #!/usr/bin/python
• It should be written at the start of any python script to tell the shell to
execute the script using python, so the script should have execute
permission.
 print “Hello”
• Prints Hello to console
 x = 3
• Define integer variable x with value 3
 y = 4.5
• Define float variable y with value 4.5
 z = True
• Define Boolean variable z with value True
 x = 5/2
• Value of x will be 2 as operation is all on integers
Python syntax
5
 x = 5.0/2
• Value of x will be 2.5
 x = float(5)/2
• Value of x will be 2.5
 # comment
• # is used to comment out any line
 “””Comment multiple lines”””
• “”” any number of lines “”” is used to comment out any number of
lines.
Python syntax
6
 x = 10 + 20
• X is sum of 10 and 20
 x = 4 ** 2
• X is 4 to the power of 2
 x = 101 % 2
• X is 101 modulo 2 which will equal 1
Python syntax
7
Strings and console output
8
 var = “Hello Python”
• Put string “Hello Python” in variable var
 c = “Hello”[0]
• Put character at index zero of string “Hello” which is ‘H’ in variable c, so
c will contain the value ‘H’
 c = var[4]
• c will have the value at index 4 which is ‘o’
 len(var)
• Returns the length of the given string
 d = str(32)
• d will contain the string representation of the value 32, so d will contain
“32” as a string.
Strings and console output
9
 print var.lower()
• Print string in variable var with all letters lower case.
 print var.upper()
• Print string in variable var with all letters upper case.
 mystr = var + “Scripting”
• Concatenate strings, value of mystr will be “Hello Python Scripting”
 print “Welcome” + “ to” + “ python”
• Prints Welcome to python
 mystr = var[2:len(var)]
• Variable mystr will contain string inside var from index 2 (third
character) till the end of the string inside var.
 Print “value1 is %s, value2 is %s” %(var1, var2)
• Prints the values inside variables var1 and var2.
Strings and console output
10
 Date and time
# import is used to include external library to be used inside our script
from datetime import datetime
now = datetime.now()
print now.year
print now.month
print now.day
print '%s/%s/%s' % (now.month, now.day, now.year)
print ("%s:%s:%s") % (now.hour, now.minute, now.second)
print ("%s/%s/%s %s:%s:%s") % (now.month, now.day, now.year, now.hour,
now.minute, now.second)
Strings and console output
11
Conditional and control flow
12
 Comparators > == <= <
• Compare between two values, returns True or False
 and, or operators
• Combine between 2 or more conditions
 not operator
• Returns the inverse of the condition
• not is evaluated first, and is evaluated next, or is evaluated last. So use
Parentheses better
Conditional and control flow
13
 If syntax
if x>10 : #note the ‘:’
print “Greater” # note the indentation (4 white spaces)
elif x<10 :
print “Less”
else :
print “Equal”
Conditional and control flow
14
 Take input from user
name = raw_input("What's your name?") # returns string
integer = int(raw_input("Enter number: ")) # convert returned string to integer
integer = input("enter integer") # returns integer
if name.isalpha() # check that name contains alphabetical characters only
Conditional and control flow
15
Functions
16
 Python functions
import math
print math.sqrt(25) # print square root of 25
from math import sqrt # to be able to use sqrt by its name
print sqrt(25)
import math # Imports the math module
everything = dir(math) # Sets everything to a list of function from math
print everything # Prints all available functions in math module
Functions
17
 Python functions
maximum = max(-2,3,1,15) # return maximum of given values
minimum = min(3,7,2,9) # return maximum of given values
absolute = abs(-42) # return absolute value of given number
print type(3) # prints <type 'int'>
print type(2.4) # prints <type 'float'>
print type("Hello") # prints <type 'str'>
#no need to import any module to be able to use previous functions as
they are built in functions.
Functions
18
 User defined functions
def print_positive(arg) : # take one argument
if agr>=0 :
print arg
return True # return value to the caller
else :
return False
Functions
19
Lists and dictionaries
20
 list = [item1, item2, item3]
• Create list of the given 3 items
 list.append(newItem)
• Add new element at the end of the list
 list[0:3]
• Values of the list from index 0 and stop before index 3
 list[:2]
• Grabs the first two items
 list[3:]
• Grabs the fourth through last items
 string_index = list.index(“mystring")
• Find index of “mystring"
Lists and dictionaries
21
 list.insert(index, item)
• insert item at index and shift all next items down by 1
 list.sort()
• sort list ascending
 list.remove(item3)
• remove item3 from list
 Loop on all list items
my_list = [1,9,3,8,5,7]
for number in my_list:
print 2 * number # print 2 18 6 16 10 14
Lists and dictionaries
22
 students= {‘std1' : 90, ‘std2' : 85, ‘std2' : 93}
• Assigning a dictionary with three key-value pairs to students
 print students[‘std1']
• Prints std1 grade which is 90
 dict_name[new_key] = new_value
• add new value to dictionary
 del dict_name[key_name]
• delete key-value pair from dictionary
 dict_name[key] = new_value
• change value
Lists and dictionaries
23
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# print even numbers in list
for number in a :
if number%2 == 0 :
print number
# loop on string characters
for letter in “Mystring":
print letter # print all letters each one on separate line
Lists and dictionaries
24
# function take list as argument
def count_small(numbers): # returns number of values less than 10
total = 0
for n in numbers:
if n < 10:
total = total + 1
return total
num = [4, 8, 15, 16, 23, 42]
small = count_small(num)
print small # print number of values in list that are less than 10
Lists and dictionaries
25
# shop example
shopping_list = ["banana", "orange", "apple"]
stock = {"banana": 6, "apple": 0, "orange": 32}
prices = {"banana": 4, "apple": 2, "orange": 1.5}
def compute_bill(food) : # compute the total price of given food list
total = 0
for item in food : # loop on all items in food list
if stock[item]>0 : # if item exists in stock
stock[item]-=1 # reduce stock by 1
total+=prices[item] # add item price to total
return total
Print compute_bill(shopping_list)
Lists and dictionaries
26
n = [1, 3, 5]
n.pop(1)
# Returns 3 (the item at index 1) and remove it from list
n.remove(1)
# Removes 1 from the list,
# NOT the item at index 1
del(n[1])
# Doesn't return anything, but removes item at index 1
Lists and dictionaries
27
def my_function(x):
for i in range(0, len(x)): # loop on all indices in list x
x[i] = x[i] * 2 # change value at index i with the double of this value
return x # return the edited list
 Note
range(6) # [0,1,2,3,4,5]
range(1,6) # [1,2,3,4,5]
range(1,6,3) # [1,4] from 1 to 6 with step 3
letters = ['a', 'b', 'c', 'd']
print " ".join(letters) # prints a b c d
print "---".join(letters) # prints a---b---c---d
Lists and dictionaries
28
# list comprehension
evens_to_50 = [i for i in range(51) if i % 2 == 0] # list of even numbers till
50
my_list[::2] # from start to end with stride of 2
my_list[::-1] # from end to start with stride of 1
squares = [x**2 for x in range(5)] # contains squares of numbers from 0
to 4
Lists and dictionaries
29
Loops
30
 Note
# to use random numbers
from random import randint
coin = randint(0, 1)
dice = randint(1, 6)
Loops
31
count = 0
while count < 10 : # Add a colon
print count
# Increment count
count +=1
# or
while True :
print count
count +=1
if count >= 10:
break #### using break
Loops
32
count = 0
count = 0
while count < 3:
num = random.randint(1, 6)
print num
if num == 5:
print "Sorry, you lose!"
break
count += 1
else:
print "You win!" ## will be executed only if didn't enter loop, or loop
terminated normally, but it will not be executed if loop terminated by
"break" statement, the same like "for/else"
Loops
33
choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are:'
for index, item in enumerate(choices):
print index+1, item # >> Your choices are: 1 pizza 2 pasta 3 salad 4
nachos
Loops
34
Bitwise operators
35
print 0b11 # print 3
print bin(2) # print bin() returns binary representation of a number
(similar oct() hex())
#note you can't use the return as number any more
print int("0b11001001", 2) # print the integer base ten of the given binary
number
Bitwise operators
36
 shift_right
0b1001 >> 1 # 0b0100
 shift_left
0b1001 << 1 # 0b0010
0b1110 & 0b0101 # 0b0100
0b1110 | 0b0101 # 0b1111
0b1110 ^ 0b0101 # 0b1011
print ~1 # print -2
print ~2 # -3
print ~3 # -4
Bitwise operators
37
# check value of bit 4
def check_bit4(input):
mask = 0b1000
result = input & mask # using mask
if result > 0:
return "on"
else:
return "off"
Bitwise operators
38
a = 0b10111011
print bin(a|0b100) # set on bit3
print bin(a^0b11111111) # flip all bits in a
(0b1 << n-1) ^ number # much simpler to flip bit number n
Bitwise operators
39
Classes
40
 Class: is an object oriented programing concept, class means a
collection of some attributes (variables) and methods (functions) that
are related to the same physical meaning.
 Defining a class: means defining a new collection of attributes and
methods that are related to each other to be used later.
 Using class: is done by making a variable (instance) of that class, one
can make multiple instances of the same class and they are all
independent.
Classes
41
# define new class
class Animal(object):
# attributes section definition
is_alive = True
health = "good“
# init method, called automatically each time an instance is made of
the class
def __init__(self, name, age): #all methods must take (self) as first as
this is the variable that points to the current instance
self.name = name
self.age = age
# any methods are added here
def description(self):
print self.name
print self.age
Classes
42
# using class
hippo = Animal("any1", 3) # make new instance
hippo.description() # use the method for hippo instance
sloth = Animal("any2", 3) # make new different instance
ocelot = Animal("any3", 4) # make new different instance
# they all will print “good” as no one changed the initial value
print hippo.health
print sloth.health
print ocelot.health
Classes
43
File Input/output
44
# Read from file
my_file = open("output.txt", "r") # open file with read only permission
print my_file.read() # read file content and print it
my_file.close() # close file
# Write to file
my_file = open("output.txt", “r+") # open file with read / write
permission
my_file.write(“Hello”) # write hello to file
my_file.close() # close file
File Input/output
45
# make python close the file by itself after finishing
with open("text.txt", "w") as textfile:
textfile.write("Success!")
if my_file.closed == False: # check if file not closed through closed
attribute
my_file.close()
print my_file.closed # print closed attribute current value, it
should now be True as the file is closed
File Input/output
46
 Different access modes:
r Opens a file for reading only. The file pointer is placed at the
beginning of the file. This is the default mode.
r+ Opens a file for both reading and writing. The file pointer placed at
the beginning of the file.
w Opens a file for writing only. Overwrites the file if the file exists. If the
file does not exist, creates a new file for writing.
w+ Opens a file for both writing and reading. Overwrites the existing file if
the file exists. If the file does not exist, creates a new file for reading and
writing.
File Input/output
47
 Different access modes:
a Opens a file for appending. The file pointer is at the end of the file if
the file exists. That is, the file is in the append mode. If the file does not
exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the
end of the file if the file exists. The file opens in the append mode. If the
file does not exist, it creates a new file for reading and writing.
File Input/output
48
Mohamed AbdAllah
Embedded Systems Engineer
mohabdallah8@gmail.com
49

Contenu connexe

Tendances

C programming session 09
C programming session 09C programming session 09
C programming session 09
Dushmanta Nath
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]
MomenMostafa
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
TAlha MAlik
 

Tendances (20)

Functions, Strings ,Storage classes in C
 Functions, Strings ,Storage classes in C Functions, Strings ,Storage classes in C
Functions, Strings ,Storage classes in C
 
C programming session 09
C programming session 09C programming session 09
C programming session 09
 
C++ theory
C++ theoryC++ theory
C++ theory
 
C programming & data structure [arrays & pointers]
C programming & data structure   [arrays & pointers]C programming & data structure   [arrays & pointers]
C programming & data structure [arrays & pointers]
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambala45 Days C++ Programming Language Training in Ambala
45 Days C++ Programming Language Training in Ambala
 
Advanced C - Part 3
Advanced C - Part 3Advanced C - Part 3
Advanced C - Part 3
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
C Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.comC Programming Tutorial - www.infomtec.com
C Programming Tutorial - www.infomtec.com
 
04. Console Input Output
04. Console Input Output 04. Console Input Output
04. Console Input Output
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
 
Arrays in C++
Arrays in C++Arrays in C++
Arrays in C++
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
 
Introduction to Python Language and Data Types
Introduction to Python Language and Data TypesIntroduction to Python Language and Data Types
Introduction to Python Language and Data Types
 
Hooking signals and dumping the callstack
Hooking signals and dumping the callstackHooking signals and dumping the callstack
Hooking signals and dumping the callstack
 
C++ 11 Features
C++ 11 FeaturesC++ 11 Features
C++ 11 Features
 
Ascii us
Ascii usAscii us
Ascii us
 
C++ Programming Language Training in Ambala ! Batra Computer Centre
C++ Programming Language Training in Ambala ! Batra Computer CentreC++ Programming Language Training in Ambala ! Batra Computer Centre
C++ Programming Language Training in Ambala ! Batra Computer Centre
 
Linked list
Linked listLinked list
Linked list
 

En vedette

Programming atmega using boot loader
Programming atmega using boot loaderProgramming atmega using boot loader
Programming atmega using boot loader
ruyanchung
 
Python for text processing
Python for text processingPython for text processing
Python for text processing
Xiang Li
 
Embedded c & working with avr studio
Embedded c & working with avr studioEmbedded c & working with avr studio
Embedded c & working with avr studio
Nitesh Singh
 
Interfacing rs232
Interfacing rs232Interfacing rs232
Interfacing rs232
PRADEEP
 

En vedette (20)

Raspberry Pi - Lecture 4 Hardware Interfacing Special Cases
Raspberry Pi - Lecture 4 Hardware Interfacing Special CasesRaspberry Pi - Lecture 4 Hardware Interfacing Special Cases
Raspberry Pi - Lecture 4 Hardware Interfacing Special Cases
 
Raspberry Pi - Lecture 3 Embedded Communication Protocols
Raspberry Pi - Lecture 3 Embedded Communication ProtocolsRaspberry Pi - Lecture 3 Embedded Communication Protocols
Raspberry Pi - Lecture 3 Embedded Communication Protocols
 
Raspberry Pi - Lecture 2 Linux OS
Raspberry Pi - Lecture 2 Linux OSRaspberry Pi - Lecture 2 Linux OS
Raspberry Pi - Lecture 2 Linux OS
 
Raspberry Pi - Lecture 1 Introduction
Raspberry Pi - Lecture 1 IntroductionRaspberry Pi - Lecture 1 Introduction
Raspberry Pi - Lecture 1 Introduction
 
Raspberry Pi - Lecture 6 Working on Raspberry Pi
Raspberry Pi - Lecture 6 Working on Raspberry PiRaspberry Pi - Lecture 6 Working on Raspberry Pi
Raspberry Pi - Lecture 6 Working on Raspberry Pi
 
Hardware interfacing basics using AVR
Hardware interfacing basics using AVRHardware interfacing basics using AVR
Hardware interfacing basics using AVR
 
Embedded C - Lecture 4
Embedded C - Lecture 4Embedded C - Lecture 4
Embedded C - Lecture 4
 
Embedded C - Lecture 3
Embedded C - Lecture 3Embedded C - Lecture 3
Embedded C - Lecture 3
 
Embedded C - Lecture 1
Embedded C - Lecture 1Embedded C - Lecture 1
Embedded C - Lecture 1
 
Embedded C programming based on 8051 microcontroller
Embedded C programming based on 8051 microcontrollerEmbedded C programming based on 8051 microcontroller
Embedded C programming based on 8051 microcontroller
 
Programming atmega using boot loader
Programming atmega using boot loaderProgramming atmega using boot loader
Programming atmega using boot loader
 
Bootloader
BootloaderBootloader
Bootloader
 
Python Day1
Python Day1Python Day1
Python Day1
 
Plc dasar
Plc dasarPlc dasar
Plc dasar
 
Python for text processing
Python for text processingPython for text processing
Python for text processing
 
Embedded c & working with avr studio
Embedded c & working with avr studioEmbedded c & working with avr studio
Embedded c & working with avr studio
 
Emertxe : Linux training portfolio
Emertxe : Linux training portfolioEmertxe : Linux training portfolio
Emertxe : Linux training portfolio
 
Physical computing with Python and Raspberry Pi
Physical computing with Python and Raspberry PiPhysical computing with Python and Raspberry Pi
Physical computing with Python and Raspberry Pi
 
Emertxe : Training portfolio
Emertxe : Training portfolioEmertxe : Training portfolio
Emertxe : Training portfolio
 
Interfacing rs232
Interfacing rs232Interfacing rs232
Interfacing rs232
 

Similaire à Raspberry Pi - Lecture 5 Python for Raspberry Pi

Similaire à Raspberry Pi - Lecture 5 Python for Raspberry Pi (20)

Parts of python programming language
Parts of python programming languageParts of python programming language
Parts of python programming language
 
ECE-PYTHON.docx
ECE-PYTHON.docxECE-PYTHON.docx
ECE-PYTHON.docx
 
Introduction to python programming 1
Introduction to python programming   1Introduction to python programming   1
Introduction to python programming 1
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
 
Python lecture 05
Python lecture 05Python lecture 05
Python lecture 05
 
Python
PythonPython
Python
 
scripting in Python
scripting in Pythonscripting in Python
scripting in Python
 
Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
Python study material
Python study materialPython study material
Python study material
 
Lec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questionsLec2_cont.pptx galgotias University questions
Lec2_cont.pptx galgotias University questions
 
Python
PythonPython
Python
 
Python course
Python coursePython course
Python course
 
Lec04-CS110 Computational Engineering
Lec04-CS110 Computational EngineeringLec04-CS110 Computational Engineering
Lec04-CS110 Computational Engineering
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
Python-CH01L04-Presentation.pptx
Python-CH01L04-Presentation.pptxPython-CH01L04-Presentation.pptx
Python-CH01L04-Presentation.pptx
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
Python
PythonPython
Python
 
Farhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionariesFarhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionaries
 
Python.pdf
Python.pdfPython.pdf
Python.pdf
 

Dernier

DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
MayuraD1
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Dernier (20)

DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
Hazard Identification (HAZID) vs. Hazard and Operability (HAZOP): A Comparati...
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
 
2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects2016EF22_0 solar project report rooftop projects
2016EF22_0 solar project report rooftop projects
 
Air Compressor reciprocating single stage
Air Compressor reciprocating single stageAir Compressor reciprocating single stage
Air Compressor reciprocating single stage
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Rums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdfRums floating Omkareshwar FSPV IM_16112021.pdf
Rums floating Omkareshwar FSPV IM_16112021.pdf
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
kiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal loadkiln thermal load.pptx kiln tgermal load
kiln thermal load.pptx kiln tgermal load
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 

Raspberry Pi - Lecture 5 Python for Raspberry Pi

  • 1. Prepared by: Mohamed AbdAllah Raspberry pi interfacing Lecture 5: Python for raspberry pi 1
  • 2. Python Agenda  Python syntax.  Strings and console output.  Conditional and control flow.  Functions.  Lists and dictionaries.  Loops.  Bitwise operators.  Classes.  File Input/output 2
  • 5.  #!/usr/bin/python • It should be written at the start of any python script to tell the shell to execute the script using python, so the script should have execute permission.  print “Hello” • Prints Hello to console  x = 3 • Define integer variable x with value 3  y = 4.5 • Define float variable y with value 4.5  z = True • Define Boolean variable z with value True  x = 5/2 • Value of x will be 2 as operation is all on integers Python syntax 5
  • 6.  x = 5.0/2 • Value of x will be 2.5  x = float(5)/2 • Value of x will be 2.5  # comment • # is used to comment out any line  “””Comment multiple lines””” • “”” any number of lines “”” is used to comment out any number of lines. Python syntax 6
  • 7.  x = 10 + 20 • X is sum of 10 and 20  x = 4 ** 2 • X is 4 to the power of 2  x = 101 % 2 • X is 101 modulo 2 which will equal 1 Python syntax 7
  • 9.  var = “Hello Python” • Put string “Hello Python” in variable var  c = “Hello”[0] • Put character at index zero of string “Hello” which is ‘H’ in variable c, so c will contain the value ‘H’  c = var[4] • c will have the value at index 4 which is ‘o’  len(var) • Returns the length of the given string  d = str(32) • d will contain the string representation of the value 32, so d will contain “32” as a string. Strings and console output 9
  • 10.  print var.lower() • Print string in variable var with all letters lower case.  print var.upper() • Print string in variable var with all letters upper case.  mystr = var + “Scripting” • Concatenate strings, value of mystr will be “Hello Python Scripting”  print “Welcome” + “ to” + “ python” • Prints Welcome to python  mystr = var[2:len(var)] • Variable mystr will contain string inside var from index 2 (third character) till the end of the string inside var.  Print “value1 is %s, value2 is %s” %(var1, var2) • Prints the values inside variables var1 and var2. Strings and console output 10
  • 11.  Date and time # import is used to include external library to be used inside our script from datetime import datetime now = datetime.now() print now.year print now.month print now.day print '%s/%s/%s' % (now.month, now.day, now.year) print ("%s:%s:%s") % (now.hour, now.minute, now.second) print ("%s/%s/%s %s:%s:%s") % (now.month, now.day, now.year, now.hour, now.minute, now.second) Strings and console output 11
  • 13.  Comparators > == <= < • Compare between two values, returns True or False  and, or operators • Combine between 2 or more conditions  not operator • Returns the inverse of the condition • not is evaluated first, and is evaluated next, or is evaluated last. So use Parentheses better Conditional and control flow 13
  • 14.  If syntax if x>10 : #note the ‘:’ print “Greater” # note the indentation (4 white spaces) elif x<10 : print “Less” else : print “Equal” Conditional and control flow 14
  • 15.  Take input from user name = raw_input("What's your name?") # returns string integer = int(raw_input("Enter number: ")) # convert returned string to integer integer = input("enter integer") # returns integer if name.isalpha() # check that name contains alphabetical characters only Conditional and control flow 15
  • 17.  Python functions import math print math.sqrt(25) # print square root of 25 from math import sqrt # to be able to use sqrt by its name print sqrt(25) import math # Imports the math module everything = dir(math) # Sets everything to a list of function from math print everything # Prints all available functions in math module Functions 17
  • 18.  Python functions maximum = max(-2,3,1,15) # return maximum of given values minimum = min(3,7,2,9) # return maximum of given values absolute = abs(-42) # return absolute value of given number print type(3) # prints <type 'int'> print type(2.4) # prints <type 'float'> print type("Hello") # prints <type 'str'> #no need to import any module to be able to use previous functions as they are built in functions. Functions 18
  • 19.  User defined functions def print_positive(arg) : # take one argument if agr>=0 : print arg return True # return value to the caller else : return False Functions 19
  • 21.  list = [item1, item2, item3] • Create list of the given 3 items  list.append(newItem) • Add new element at the end of the list  list[0:3] • Values of the list from index 0 and stop before index 3  list[:2] • Grabs the first two items  list[3:] • Grabs the fourth through last items  string_index = list.index(“mystring") • Find index of “mystring" Lists and dictionaries 21
  • 22.  list.insert(index, item) • insert item at index and shift all next items down by 1  list.sort() • sort list ascending  list.remove(item3) • remove item3 from list  Loop on all list items my_list = [1,9,3,8,5,7] for number in my_list: print 2 * number # print 2 18 6 16 10 14 Lists and dictionaries 22
  • 23.  students= {‘std1' : 90, ‘std2' : 85, ‘std2' : 93} • Assigning a dictionary with three key-value pairs to students  print students[‘std1'] • Prints std1 grade which is 90  dict_name[new_key] = new_value • add new value to dictionary  del dict_name[key_name] • delete key-value pair from dictionary  dict_name[key] = new_value • change value Lists and dictionaries 23
  • 24. a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] # print even numbers in list for number in a : if number%2 == 0 : print number # loop on string characters for letter in “Mystring": print letter # print all letters each one on separate line Lists and dictionaries 24
  • 25. # function take list as argument def count_small(numbers): # returns number of values less than 10 total = 0 for n in numbers: if n < 10: total = total + 1 return total num = [4, 8, 15, 16, 23, 42] small = count_small(num) print small # print number of values in list that are less than 10 Lists and dictionaries 25
  • 26. # shop example shopping_list = ["banana", "orange", "apple"] stock = {"banana": 6, "apple": 0, "orange": 32} prices = {"banana": 4, "apple": 2, "orange": 1.5} def compute_bill(food) : # compute the total price of given food list total = 0 for item in food : # loop on all items in food list if stock[item]>0 : # if item exists in stock stock[item]-=1 # reduce stock by 1 total+=prices[item] # add item price to total return total Print compute_bill(shopping_list) Lists and dictionaries 26
  • 27. n = [1, 3, 5] n.pop(1) # Returns 3 (the item at index 1) and remove it from list n.remove(1) # Removes 1 from the list, # NOT the item at index 1 del(n[1]) # Doesn't return anything, but removes item at index 1 Lists and dictionaries 27
  • 28. def my_function(x): for i in range(0, len(x)): # loop on all indices in list x x[i] = x[i] * 2 # change value at index i with the double of this value return x # return the edited list  Note range(6) # [0,1,2,3,4,5] range(1,6) # [1,2,3,4,5] range(1,6,3) # [1,4] from 1 to 6 with step 3 letters = ['a', 'b', 'c', 'd'] print " ".join(letters) # prints a b c d print "---".join(letters) # prints a---b---c---d Lists and dictionaries 28
  • 29. # list comprehension evens_to_50 = [i for i in range(51) if i % 2 == 0] # list of even numbers till 50 my_list[::2] # from start to end with stride of 2 my_list[::-1] # from end to start with stride of 1 squares = [x**2 for x in range(5)] # contains squares of numbers from 0 to 4 Lists and dictionaries 29
  • 31.  Note # to use random numbers from random import randint coin = randint(0, 1) dice = randint(1, 6) Loops 31
  • 32. count = 0 while count < 10 : # Add a colon print count # Increment count count +=1 # or while True : print count count +=1 if count >= 10: break #### using break Loops 32
  • 33. count = 0 count = 0 while count < 3: num = random.randint(1, 6) print num if num == 5: print "Sorry, you lose!" break count += 1 else: print "You win!" ## will be executed only if didn't enter loop, or loop terminated normally, but it will not be executed if loop terminated by "break" statement, the same like "for/else" Loops 33
  • 34. choices = ['pizza', 'pasta', 'salad', 'nachos'] print 'Your choices are:' for index, item in enumerate(choices): print index+1, item # >> Your choices are: 1 pizza 2 pasta 3 salad 4 nachos Loops 34
  • 36. print 0b11 # print 3 print bin(2) # print bin() returns binary representation of a number (similar oct() hex()) #note you can't use the return as number any more print int("0b11001001", 2) # print the integer base ten of the given binary number Bitwise operators 36
  • 37.  shift_right 0b1001 >> 1 # 0b0100  shift_left 0b1001 << 1 # 0b0010 0b1110 & 0b0101 # 0b0100 0b1110 | 0b0101 # 0b1111 0b1110 ^ 0b0101 # 0b1011 print ~1 # print -2 print ~2 # -3 print ~3 # -4 Bitwise operators 37
  • 38. # check value of bit 4 def check_bit4(input): mask = 0b1000 result = input & mask # using mask if result > 0: return "on" else: return "off" Bitwise operators 38
  • 39. a = 0b10111011 print bin(a|0b100) # set on bit3 print bin(a^0b11111111) # flip all bits in a (0b1 << n-1) ^ number # much simpler to flip bit number n Bitwise operators 39
  • 41.  Class: is an object oriented programing concept, class means a collection of some attributes (variables) and methods (functions) that are related to the same physical meaning.  Defining a class: means defining a new collection of attributes and methods that are related to each other to be used later.  Using class: is done by making a variable (instance) of that class, one can make multiple instances of the same class and they are all independent. Classes 41
  • 42. # define new class class Animal(object): # attributes section definition is_alive = True health = "good“ # init method, called automatically each time an instance is made of the class def __init__(self, name, age): #all methods must take (self) as first as this is the variable that points to the current instance self.name = name self.age = age # any methods are added here def description(self): print self.name print self.age Classes 42
  • 43. # using class hippo = Animal("any1", 3) # make new instance hippo.description() # use the method for hippo instance sloth = Animal("any2", 3) # make new different instance ocelot = Animal("any3", 4) # make new different instance # they all will print “good” as no one changed the initial value print hippo.health print sloth.health print ocelot.health Classes 43
  • 45. # Read from file my_file = open("output.txt", "r") # open file with read only permission print my_file.read() # read file content and print it my_file.close() # close file # Write to file my_file = open("output.txt", “r+") # open file with read / write permission my_file.write(“Hello”) # write hello to file my_file.close() # close file File Input/output 45
  • 46. # make python close the file by itself after finishing with open("text.txt", "w") as textfile: textfile.write("Success!") if my_file.closed == False: # check if file not closed through closed attribute my_file.close() print my_file.closed # print closed attribute current value, it should now be True as the file is closed File Input/output 46
  • 47.  Different access modes: r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode. r+ Opens a file for both reading and writing. The file pointer placed at the beginning of the file. w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing. w+ Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing. File Input/output 47
  • 48.  Different access modes: a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing. a+ Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing. File Input/output 48
  • 49. Mohamed AbdAllah Embedded Systems Engineer mohabdallah8@gmail.com 49