SlideShare a Scribd company logo
1 of 4
Download to read offline
1
Python Basics - Lab I Prof. Anish Goel
STTP on " Embedded Systems using Raspberry Pi Single Board Computer"
Lab Exercise - I
Basic Python Programming and "Hello World of R-Pi
Note: Try the codes highlighted in BOLD in IDLE and see the results.
Python is a wonderful and powerful programming language that's easy to use (easy to read and write) and
with Raspberry Pi lets you connect your project to the real world.
Python syntax is very clean, with an emphasis on readability and uses standard English keywords. Start
by opening IDLE from the desktop.
IDLE
The easiest introduction to Python is through IDLE, a Python development environment. Open IDLE
from the Desktop or applications menu:
IDLE gives you a REPL (Read-Evaluate-Print-Loop) which is a prompt you can enter Python commands
in to. As it's a REPL you even get the output of commands printed to the screen without using print.
Note two versions of Python are available: Python 2 and Python 3. Python 3 is the newest version and is
recommended, however Python 2 is available for legacy
applications which do not support Python 3 yet. For the
examples on this page you can use Python 2 or 3 (see Python 2
vs. Python 3).
You can use variables if you need to but you can even use it like
a calculator. For example:
>>> 1 + 2
3
>>> name = "Sarah"
>>> "Hello " + name
'Hello Sarah'
IDLE also has syntax highlighting built in and some support for
auto-completion. You can look back on the history of the
commands you've entered in the REPL with Alt + P (previous)
and Alt + N (next).
BASIC PYTHON USAGE
Hello world in Python:
print("Hello world")
Simple as that!
INDENTATION
Some languages use curly braces { and } to wrap around lines of code which belong together, and leave it
to the writer to indent these lines to appear visually nested. However, Python does not use curly braces
but instead requires indentation for nesting. For example a for loop in Python:
for i in range(10):
print("Hello")
The indentation is necessary here. A second line indented would be a part of the loop, and a second line
not indented would be outside of the loop. For example:
for i in range(2):
print("A")
print("B")
2
Python Basics - Lab I Prof. Anish Goel
would print:
A
B
A
B
whereas the following:
for i in range(2):
print("A")
print("B")
Will Print ???
______________________________
VARIABLES
To save a value to a variable, assign it like so:
name = "Bob"
age = 15
Note here I did not assign types to these variables, as types are inferred, and can be changed (it's
dynamic).
age = 15
age += 1 # increment age by 1
print(age)
This time I used comments beside the increment command.
COMMENTS
Comments are ignored in the program but there for you to leave notes, and are denoted by the
hash # symbol. Multi-line comments use triple quotes like so:
"""
This is a very simple Python program that prints "Hello".
That's all it does.
"""
print("Hello")
LISTS
Python also has lists (called arrays in some languages) which are collections of data of any type:
numbers = [1, 2, 3]
Lists are denoted by the use of square brackets [] and each item is separated by a comma.
ITERATION
Some data types are iterable, which means you can loop over the values they contain. For example a list:
numbers = [1, 2, 3]
for number in numbers:
print(number)
This takes each item in the list numbers and prints out the item:
_________________
Note I used the word number to denote each item. This is merely the word I chose for this - it's
recommended you choose descriptive words for variables - using plurals for lists, and singular for each
item makes sense. It makes it easier to understand when reading.
Other data types are iterable, for example the string:
dog_name = "BINGO"
for char in dog_name:
print(char)
This loops over each character and prints them out:
3
Python Basics - Lab I Prof. Anish Goel
_________________???
RANGE
The integer data type is not iterable and tryng to iterate over it will produce an error. For example:
for i in 3:
print(i)
will produce:
TypeError: 'int' object is not iterable
However you can make an iterable object using the range function:
for i in range(3):
print(i)
range(5) contains the numbers 0, 1, 2, 3 and 4 (five numbers in total). To get the
numbers 1 to 5 use range(1, 6).
LENGTH
You can use functions like len to find the length of a string or a list:
name = "Jamie"
print(len(name))
names = ["Bob", "Jane", "James", "Alice"]
print(len(names))
IF STATEMENTS
You can use if statements for control flow:
name = "Joe"
if len(name) > 3:
print("Nice name,")
print(name)
else:
print("That's a short name,")
print(name)
PYTHON FILES IN IDLE
To create a Python file in IDLE, click File > New File and you'll be given a blank window. This is an
empty file, not a Python prompt. You write a Python file in this window, save it, then run it and you'll see
the output in the other window.
For example, in the new window, type:
n = 0
for i in range(1, 101):
n += i
4
Python Basics - Lab I Prof. Anish Goel
print("The sum of the numbers 1 to 100 is:")
print(n)
Then save this file (File > Save or Ctrl + S) and run (Run > Run Moduleor hit F5) and you'll see the
output in your original Python window.
EXECUTING PYTHON FILES FROM THE COMMAND LINE
You can write a Python file in a standard editor like Vim, Nano or LeafPad, and run it as a Python script
from the command line. Just navigate to the directory the file is saved (use cd and ls for guidance) and run
with python, e.g.python hello.py.
GPIO
Input interfacing
Connecting a push switch to a Raspberry Pi
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(18,GPIO.IN, pull_up_down=GPIO.PUD_UP)
while True:
input_state = GPIO.input(18)
if input_state == False:
print('Button Pressed')
time.sleep(0.2)
You will need to run the program as superuser:
pi@raspberrypi ~ $ sudo python switch.py
Instructions to Blink LED:
1.Open terminal and type nano blinkled.py
2.It will open the nano editor. Paste the python LED blink code
and save
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.OUT)
while True:
GPIO.output(25, GPIO.HIGH)
time.sleep(1)
GPIO.output(25, GPIO.LOW)
time.sleep(1)
3. Now run the code python blinkled.py
4.Now LED will be blinking at a interval of 1s. You can also change the interval by modifying time.sleep
in the file.
5.Press Ctrl+C to stop LED from blinking.

More Related Content

What's hot

Python programming msc(cs)
Python programming msc(cs)Python programming msc(cs)
Python programming msc(cs)KALAISELVI P
Β 
Introduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIMLIntroduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIMLVijaySharma802
Β 
First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python ProgrammingDozie Agbo
Β 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming LanguageTahani Al-Manie
Β 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| FundamentalsMohd Sajjad
Β 
Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Chariza Pladin
Β 
Python Tutorial
Python TutorialPython Tutorial
Python TutorialAkramWaseem
Β 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way PresentationAmira ElSharkawy
Β 
Learn python – for beginners
Learn python – for beginnersLearn python – for beginners
Learn python – for beginnersRajKumar Rampelli
Β 

What's hot (20)

Python programming msc(cs)
Python programming msc(cs)Python programming msc(cs)
Python programming msc(cs)
Β 
Python Workshop
Python WorkshopPython Workshop
Python Workshop
Β 
Introduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIMLIntroduction to Python Programming | InsideAIML
Introduction to Python Programming | InsideAIML
Β 
First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python Programming
Β 
Python Session - 2
Python Session - 2Python Session - 2
Python Session - 2
Β 
Python basics
Python basicsPython basics
Python basics
Β 
Learn python
Learn pythonLearn python
Learn python
Β 
Python
PythonPython
Python
Β 
Python programming
Python programmingPython programming
Python programming
Β 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
Β 
Python Session - 5
Python Session - 5Python Session - 5
Python Session - 5
Β 
Python advance
Python advancePython advance
Python advance
Β 
Python basic
Python basicPython basic
Python basic
Β 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
Β 
Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3Zero to Hero - Introduction to Python3
Zero to Hero - Introduction to Python3
Β 
Python Tutorial
Python TutorialPython Tutorial
Python Tutorial
Β 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way Presentation
Β 
Python ppt
Python pptPython ppt
Python ppt
Β 
Python Presentation
Python PresentationPython Presentation
Python Presentation
Β 
Learn python – for beginners
Learn python – for beginnersLearn python – for beginners
Learn python – for beginners
Β 

Similar to Learning Python for Raspberry Pi

Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdfsamiwaris2
Β 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonmckennadglyn
Β 
Notes1
Notes1Notes1
Notes1hccit
Β 
Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentalsnatnaelmamuye
Β 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizeIruolagbePius
Β 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughgabriellekuruvilla
Β 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonRanjith kumar
Β 
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTHBhavsingh Maloth
Β 
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdfCSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdfAbdulmalikAhmadLawan2
Β 
Fundamentals of python
Fundamentals of pythonFundamentals of python
Fundamentals of pythonBijuAugustian
Β 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answerskavinilavuG
Β 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answersRojaPriya
Β 
PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...
PART - 1  Python Introduction- Variables- Data types - Numeric- String- Boole...PART - 1  Python Introduction- Variables- Data types - Numeric- String- Boole...
PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...manikamr074
Β 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...DRVaibhavmeshram1
Β 
Python Introduction
Python IntroductionPython Introduction
Python Introductionvikram mahendra
Β 
PYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdfPYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdfRamakrishna Reddy Bijjam
Β 
Python Programming | JNTUK | UNIT 1 | Lecture 3
Python Programming | JNTUK | UNIT 1 | Lecture 3Python Programming | JNTUK | UNIT 1 | Lecture 3
Python Programming | JNTUK | UNIT 1 | Lecture 3FabMinds
Β 

Similar to Learning Python for Raspberry Pi (20)

Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
Β 
Python tutorial
Python tutorialPython tutorial
Python tutorial
Β 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Β 
Notes1
Notes1Notes1
Notes1
Β 
Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentals
Β 
Python (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualizePython (Data Analysis) cleaning and visualize
Python (Data Analysis) cleaning and visualize
Β 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough
Β 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Β 
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTHWEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
WEB PROGRAMMING UNIT VIII BY BHAVSINGH MALOTH
Β 
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdfCSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
CSC2308 - PRINCIPLE OF PROGRAMMING II.pdf
Β 
Fundamentals of python
Fundamentals of pythonFundamentals of python
Fundamentals of python
Β 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
Β 
Python PPT1.pdf
Python PPT1.pdfPython PPT1.pdf
Python PPT1.pdf
Β 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
Β 
PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...
PART - 1  Python Introduction- Variables- Data types - Numeric- String- Boole...PART - 1  Python Introduction- Variables- Data types - Numeric- String- Boole...
PART - 1 Python Introduction- Variables- Data types - Numeric- String- Boole...
Β 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Β 
Python Introduction
Python IntroductionPython Introduction
Python Introduction
Β 
pyton Notes1
pyton Notes1pyton Notes1
pyton Notes1
Β 
PYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdfPYTHON PROGRAMMING NOTES RKREDDY.pdf
PYTHON PROGRAMMING NOTES RKREDDY.pdf
Β 
Python Programming | JNTUK | UNIT 1 | Lecture 3
Python Programming | JNTUK | UNIT 1 | Lecture 3Python Programming | JNTUK | UNIT 1 | Lecture 3
Python Programming | JNTUK | UNIT 1 | Lecture 3
Β 

More from anishgoel

Computer Organization
Computer OrganizationComputer Organization
Computer Organizationanishgoel
Β 
Learning vhdl by examples
Learning vhdl by examplesLearning vhdl by examples
Learning vhdl by examplesanishgoel
Β 
Dot matrix module interface wit Raspberry Pi
Dot matrix module interface wit Raspberry PiDot matrix module interface wit Raspberry Pi
Dot matrix module interface wit Raspberry Pianishgoel
Β 
Input interface with Raspberry pi
Input interface with Raspberry piInput interface with Raspberry pi
Input interface with Raspberry pianishgoel
Β 
Raspberry Pi
Raspberry PiRaspberry Pi
Raspberry Pianishgoel
Β 
learning vhdl by examples
learning vhdl by exampleslearning vhdl by examples
learning vhdl by examplesanishgoel
Β 
Digital System Design Basics
Digital System Design BasicsDigital System Design Basics
Digital System Design Basicsanishgoel
Β 
digital design of communication systems
digital design of communication systemsdigital design of communication systems
digital design of communication systemsanishgoel
Β 
Rtos concepts
Rtos conceptsRtos concepts
Rtos conceptsanishgoel
Β 
8051 Microcontroller Timer
8051 Microcontroller Timer8051 Microcontroller Timer
8051 Microcontroller Timeranishgoel
Β 
8051 Microcontroller I/O ports
8051 Microcontroller I/O ports8051 Microcontroller I/O ports
8051 Microcontroller I/O portsanishgoel
Β 
Serial Communication Interfaces
Serial Communication InterfacesSerial Communication Interfaces
Serial Communication Interfacesanishgoel
Β 
Embedded systems ppt iv part d
Embedded systems ppt iv   part dEmbedded systems ppt iv   part d
Embedded systems ppt iv part danishgoel
Β 
Embedded systems ppt iv part c
Embedded systems ppt iv   part cEmbedded systems ppt iv   part c
Embedded systems ppt iv part canishgoel
Β 
Embedded systems ppt iv part b
Embedded systems ppt iv   part bEmbedded systems ppt iv   part b
Embedded systems ppt iv part banishgoel
Β 
Embedded systems ppt ii
Embedded systems ppt iiEmbedded systems ppt ii
Embedded systems ppt iianishgoel
Β 
Embedded systems ppt iii
Embedded systems ppt iiiEmbedded systems ppt iii
Embedded systems ppt iiianishgoel
Β 
Embedded systems ppt iv part a
Embedded systems ppt iv   part aEmbedded systems ppt iv   part a
Embedded systems ppt iv part aanishgoel
Β 
Embedded systems ppt i
Embedded systems ppt iEmbedded systems ppt i
Embedded systems ppt ianishgoel
Β 
Cpld fpga
Cpld fpgaCpld fpga
Cpld fpgaanishgoel
Β 

More from anishgoel (20)

Computer Organization
Computer OrganizationComputer Organization
Computer Organization
Β 
Learning vhdl by examples
Learning vhdl by examplesLearning vhdl by examples
Learning vhdl by examples
Β 
Dot matrix module interface wit Raspberry Pi
Dot matrix module interface wit Raspberry PiDot matrix module interface wit Raspberry Pi
Dot matrix module interface wit Raspberry Pi
Β 
Input interface with Raspberry pi
Input interface with Raspberry piInput interface with Raspberry pi
Input interface with Raspberry pi
Β 
Raspberry Pi
Raspberry PiRaspberry Pi
Raspberry Pi
Β 
learning vhdl by examples
learning vhdl by exampleslearning vhdl by examples
learning vhdl by examples
Β 
Digital System Design Basics
Digital System Design BasicsDigital System Design Basics
Digital System Design Basics
Β 
digital design of communication systems
digital design of communication systemsdigital design of communication systems
digital design of communication systems
Β 
Rtos concepts
Rtos conceptsRtos concepts
Rtos concepts
Β 
8051 Microcontroller Timer
8051 Microcontroller Timer8051 Microcontroller Timer
8051 Microcontroller Timer
Β 
8051 Microcontroller I/O ports
8051 Microcontroller I/O ports8051 Microcontroller I/O ports
8051 Microcontroller I/O ports
Β 
Serial Communication Interfaces
Serial Communication InterfacesSerial Communication Interfaces
Serial Communication Interfaces
Β 
Embedded systems ppt iv part d
Embedded systems ppt iv   part dEmbedded systems ppt iv   part d
Embedded systems ppt iv part d
Β 
Embedded systems ppt iv part c
Embedded systems ppt iv   part cEmbedded systems ppt iv   part c
Embedded systems ppt iv part c
Β 
Embedded systems ppt iv part b
Embedded systems ppt iv   part bEmbedded systems ppt iv   part b
Embedded systems ppt iv part b
Β 
Embedded systems ppt ii
Embedded systems ppt iiEmbedded systems ppt ii
Embedded systems ppt ii
Β 
Embedded systems ppt iii
Embedded systems ppt iiiEmbedded systems ppt iii
Embedded systems ppt iii
Β 
Embedded systems ppt iv part a
Embedded systems ppt iv   part aEmbedded systems ppt iv   part a
Embedded systems ppt iv part a
Β 
Embedded systems ppt i
Embedded systems ppt iEmbedded systems ppt i
Embedded systems ppt i
Β 
Cpld fpga
Cpld fpgaCpld fpga
Cpld fpga
Β 

Recently uploaded

Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
Β 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
Β 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
Β 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
Β 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
Β 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
Β 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
Β 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
Β 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
Β 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
Β 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
Β 
call girls in Kamla Market (DELHI) πŸ” >ΰΌ’9953330565πŸ” genuine Escort Service πŸ”βœ”οΈβœ”οΈ
call girls in Kamla Market (DELHI) πŸ” >ΰΌ’9953330565πŸ” genuine Escort Service πŸ”βœ”οΈβœ”οΈcall girls in Kamla Market (DELHI) πŸ” >ΰΌ’9953330565πŸ” genuine Escort Service πŸ”βœ”οΈβœ”οΈ
call girls in Kamla Market (DELHI) πŸ” >ΰΌ’9953330565πŸ” genuine Escort Service πŸ”βœ”οΈβœ”οΈ9953056974 Low Rate Call Girls In Saket, Delhi NCR
Β 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
Β 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
Β 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
Β 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
Β 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
Β 

Recently uploaded (20)

Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
Β 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Β 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
Β 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
Β 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Β 
Model Call Girl in Tilak Nagar Delhi reach out to us at πŸ”9953056974πŸ”
Model Call Girl in Tilak Nagar Delhi reach out to us at πŸ”9953056974πŸ”Model Call Girl in Tilak Nagar Delhi reach out to us at πŸ”9953056974πŸ”
Model Call Girl in Tilak Nagar Delhi reach out to us at πŸ”9953056974πŸ”
Β 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
Β 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
Β 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Β 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
Β 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
Β 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
Β 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
Β 
call girls in Kamla Market (DELHI) πŸ” >ΰΌ’9953330565πŸ” genuine Escort Service πŸ”βœ”οΈβœ”οΈ
call girls in Kamla Market (DELHI) πŸ” >ΰΌ’9953330565πŸ” genuine Escort Service πŸ”βœ”οΈβœ”οΈcall girls in Kamla Market (DELHI) πŸ” >ΰΌ’9953330565πŸ” genuine Escort Service πŸ”βœ”οΈβœ”οΈ
call girls in Kamla Market (DELHI) πŸ” >ΰΌ’9953330565πŸ” genuine Escort Service πŸ”βœ”οΈβœ”οΈ
Β 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
Β 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Β 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
Β 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
Β 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
Β 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
Β 

Learning Python for Raspberry Pi

  • 1. 1 Python Basics - Lab I Prof. Anish Goel STTP on " Embedded Systems using Raspberry Pi Single Board Computer" Lab Exercise - I Basic Python Programming and "Hello World of R-Pi Note: Try the codes highlighted in BOLD in IDLE and see the results. Python is a wonderful and powerful programming language that's easy to use (easy to read and write) and with Raspberry Pi lets you connect your project to the real world. Python syntax is very clean, with an emphasis on readability and uses standard English keywords. Start by opening IDLE from the desktop. IDLE The easiest introduction to Python is through IDLE, a Python development environment. Open IDLE from the Desktop or applications menu: IDLE gives you a REPL (Read-Evaluate-Print-Loop) which is a prompt you can enter Python commands in to. As it's a REPL you even get the output of commands printed to the screen without using print. Note two versions of Python are available: Python 2 and Python 3. Python 3 is the newest version and is recommended, however Python 2 is available for legacy applications which do not support Python 3 yet. For the examples on this page you can use Python 2 or 3 (see Python 2 vs. Python 3). You can use variables if you need to but you can even use it like a calculator. For example: >>> 1 + 2 3 >>> name = "Sarah" >>> "Hello " + name 'Hello Sarah' IDLE also has syntax highlighting built in and some support for auto-completion. You can look back on the history of the commands you've entered in the REPL with Alt + P (previous) and Alt + N (next). BASIC PYTHON USAGE Hello world in Python: print("Hello world") Simple as that! INDENTATION Some languages use curly braces { and } to wrap around lines of code which belong together, and leave it to the writer to indent these lines to appear visually nested. However, Python does not use curly braces but instead requires indentation for nesting. For example a for loop in Python: for i in range(10): print("Hello") The indentation is necessary here. A second line indented would be a part of the loop, and a second line not indented would be outside of the loop. For example: for i in range(2): print("A") print("B")
  • 2. 2 Python Basics - Lab I Prof. Anish Goel would print: A B A B whereas the following: for i in range(2): print("A") print("B") Will Print ??? ______________________________ VARIABLES To save a value to a variable, assign it like so: name = "Bob" age = 15 Note here I did not assign types to these variables, as types are inferred, and can be changed (it's dynamic). age = 15 age += 1 # increment age by 1 print(age) This time I used comments beside the increment command. COMMENTS Comments are ignored in the program but there for you to leave notes, and are denoted by the hash # symbol. Multi-line comments use triple quotes like so: """ This is a very simple Python program that prints "Hello". That's all it does. """ print("Hello") LISTS Python also has lists (called arrays in some languages) which are collections of data of any type: numbers = [1, 2, 3] Lists are denoted by the use of square brackets [] and each item is separated by a comma. ITERATION Some data types are iterable, which means you can loop over the values they contain. For example a list: numbers = [1, 2, 3] for number in numbers: print(number) This takes each item in the list numbers and prints out the item: _________________ Note I used the word number to denote each item. This is merely the word I chose for this - it's recommended you choose descriptive words for variables - using plurals for lists, and singular for each item makes sense. It makes it easier to understand when reading. Other data types are iterable, for example the string: dog_name = "BINGO" for char in dog_name: print(char) This loops over each character and prints them out:
  • 3. 3 Python Basics - Lab I Prof. Anish Goel _________________??? RANGE The integer data type is not iterable and tryng to iterate over it will produce an error. For example: for i in 3: print(i) will produce: TypeError: 'int' object is not iterable However you can make an iterable object using the range function: for i in range(3): print(i) range(5) contains the numbers 0, 1, 2, 3 and 4 (five numbers in total). To get the numbers 1 to 5 use range(1, 6). LENGTH You can use functions like len to find the length of a string or a list: name = "Jamie" print(len(name)) names = ["Bob", "Jane", "James", "Alice"] print(len(names)) IF STATEMENTS You can use if statements for control flow: name = "Joe" if len(name) > 3: print("Nice name,") print(name) else: print("That's a short name,") print(name) PYTHON FILES IN IDLE To create a Python file in IDLE, click File > New File and you'll be given a blank window. This is an empty file, not a Python prompt. You write a Python file in this window, save it, then run it and you'll see the output in the other window. For example, in the new window, type: n = 0 for i in range(1, 101): n += i
  • 4. 4 Python Basics - Lab I Prof. Anish Goel print("The sum of the numbers 1 to 100 is:") print(n) Then save this file (File > Save or Ctrl + S) and run (Run > Run Moduleor hit F5) and you'll see the output in your original Python window. EXECUTING PYTHON FILES FROM THE COMMAND LINE You can write a Python file in a standard editor like Vim, Nano or LeafPad, and run it as a Python script from the command line. Just navigate to the directory the file is saved (use cd and ls for guidance) and run with python, e.g.python hello.py. GPIO Input interfacing Connecting a push switch to a Raspberry Pi import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18,GPIO.IN, pull_up_down=GPIO.PUD_UP) while True: input_state = GPIO.input(18) if input_state == False: print('Button Pressed') time.sleep(0.2) You will need to run the program as superuser: pi@raspberrypi ~ $ sudo python switch.py Instructions to Blink LED: 1.Open terminal and type nano blinkled.py 2.It will open the nano editor. Paste the python LED blink code and save import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(25, GPIO.OUT) while True: GPIO.output(25, GPIO.HIGH) time.sleep(1) GPIO.output(25, GPIO.LOW) time.sleep(1) 3. Now run the code python blinkled.py 4.Now LED will be blinking at a interval of 1s. You can also change the interval by modifying time.sleep in the file. 5.Press Ctrl+C to stop LED from blinking.