Introduction To Raspberry Pi
Introduction To Raspberry Pi
What is Python ?
Python programming language is one of the most sought out programming
languages nowadays. Developers want to focus on the implementation part rather
than spending time writing complex programs. This is where python actually
delivers, with the ease of access and readability. Fundamental concepts are the
foundation of any programming language and hence in this blog we will learn the
concept of variables and data types in python.
https://www.javatpoint.com/python-tutorial
Python Identifiers
A Python identifier is a name used to identify a variable, function, class, module or
other object. An identifier starts with a letter A to Z or a to z or an underscore (_)
followed by zero or more letters, underscores and digits (0 to 9). Python does not allow
punctuation characters such as @, $, and % within identifiers. Python is a case
sensitive programming language. Thus, Manpower and manpower are two different
identifiers in Python. The maximum possible length of an identifier is not
defined in the python language. It can be of any number.
Here, 100, 165.12 and " Electronics " are the values assigned to counter, miles, and name variables,
respectively. This produces the following result after print −
100
165.12
Electronics
1.2 Multiple Assignment
Python allows you to assign a single value to several variables simultaneously. For example −
a=b=c=1
Here, an integer object is created with the value 1, and all three variables are assigned to the same
memory location. You can also assign multiple objects to multiple variables. For example −
a,b,c = 1,2,"john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one
string object with the value "john" is assigned to the variable c.
2. Standard Data Types
The data stored in memory can be of many types. For example, a person's age is stored as a
numeric value and his or her address is stored as alphanumeric characters. Python has various
standard data types that are used to define the operations possible on them and the storage
method for each of them.
Python has five standard data types −
• Numbers
• String
• List
• Tuple
• Dictionary
1. Python Numbers
Number data types store numeric values. Number objects are created when you assign a value to
them. For example −
var1 = 1
var2 = 10
You can also delete the reference to a number object by using the del statement. The syntax of the del
statement is −
del var1[,var2[,var3[....,varN]]]]
You can delete a single object or multiple objects by using the del statement. For example −
del var
del var_a, var_b
Python supports four different numerical types −
int (signed integers)
long (long integers, they can also be represented in octal and hexadecimal)
float (floating point real values)
complex (complex numbers)
Examples
Here are some examples of numbers −
Strings in Python are identified as a contiguous set of characters represented in the quotation
marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken
using the slice operator ([ ] and [:] ) with indexes starting at 0 in the beginning of the string and
working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition
operator. For example −
print list # Prints complete list =['abcd', 786, 2.23, 'john', 70.2]
print list[0] # Prints first element of the list =abcd
print list[1:3] # Prints elements starting from 2nd till 3rd =[786, 2.23]
print list[2:] # Prints elements starting from 3rd element =[2.23, 'john', 70.2]
print tinylist * 2 # Prints list two times =[123, 'john', 123, 'john']
print list + tinylist # Prints concatenated lists =['abcd', 786, 2.23, 'john', 70.2, 123, 'john']
Python Tuples
A tuple is another sequence data type that is similar to the list. A tuple consists of a number of
values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their
elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be
updated. Tuples can be thought of as read-only lists. For example
print tuple # Prints the complete tuple =('abcd', 786, 2.23, 'john', 70.2)
print tuple[0] # Prints first element of the tuple =abcd
print tuple[1:3] # Prints elements of the tuple starting
from 2nd till 3rd =(786, 2.23)
print tuple[2:] # Prints elements of the tuple starting from
3rd element =(2.23, 'john', 70.2)
print tinytuple * 2 # Prints the contents of the tuple twice =(123, 'john', 123, 'john')
print tuple + tinytuple # Prints concatenated tuples =('abcd', 786, 2.23, 'john', 70.2, 123, 'john')
The following code is invalid with tuple, because we attempted to update a tuple, which is not
allowed. Similar case is possible with lists −
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found
in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are
usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.
Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square
braces ([]). For example −
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
Dictionaries have no concept of order among elements. It is incorrect to say that the elements are
"out of order"; they are simply unordered.
Data Type Conversion
Sometimes, you may need to perform conversions between the built-in types. To convert between
types, you simply use the type name as a function. There are several built-in functions to perform
conversion from one data type to another. These functions return a new object representing the
converted value.
Sr.No. Function & Description
1 int(x [,base]) Converts x to an integer. base specifies the base if x is a string.
2 long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string.
- Subtraction Subtracts right hand operand from left hand operand. a – b = -10
% Modulus Divides left hand operand by right hand operand and b%a=0
returns remainder
** Exponent Performs exponential (power) calculation on operators a**b =10 to the power 20
// Floor Division - The division of operands where the result 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 =
is the quotient in which the digits after the decimal point -4.0
are removed. But if one of the operands is negative, the
result is floored, i.e., rounded away from zero (towards
negative infinity) −
Python Comparison Operators
These operators compare the values on either sides of them and decide the relation among
them. They are also called Relational operators. Assume variable a holds 10 and variable b holds
20, then −
Operator Description Example
== If the values of two operands are equal, then the (a == b) is not true.
condition becomes true.
<> If values of two operands are not equal, then condition (a <> b) is true. This is similar to != operator.
becomes true.
> If the value of left operand is greater than the value of (a > b) is not true.
right operand, then condition becomes true.
< If the value of left operand is less than the value of right (a < b) is true.
operand, then condition becomes true.
>= If the value of left operand is greater than or equal to the (a >= b) is not true.
value of right operand, then condition becomes true.
<= If the value of left operand is less than or equal to the (a <= b) is true.
value of right operand, then condition becomes true.
Python Assignment Operators
Assume variable a holds 10 and variable b holds 20, then −
Operator Description Example
= Assigns values from right side operands to left side c = a + b assigns value of a + b into
operand c
+= Add AND It adds right operand to the left operand and assign
c += a is equivalent to c = c + a
the result to left operand
-= Subtract AND It subtracts right operand from the left operand and
c -= a is equivalent to c = c – a
assign the result to left operand
*= Multiply AND It multiplies right operand with the left operand and
c *= a is equivalent to c = c * a
assign the result to left operand
/= Divide AND It divides left operand with the right operand and
c /= a is equivalent to c = c / a
assign the result to left operand
%= Modulus AND It takes modulus using two operands and assign the
c %= a is equivalent to c = c % a
result to left operand
**= Exponent AND Performs exponential (power) calculation on operators
c **= a is equivalent to c = c ** a
and assign value to the left operand
//= Floor Division It performs floor division on operators and assign
c //= a is equivalent to c = c // a
value to the left operand
Python Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now
in the binary format their values will be 0011 1100 and 0000 1101 respectively. Following table lists
out the bitwise operators supported by Python language with an example each in those, we use the
above two variables (a and b) as operands −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
There are following Bitwise operators supported by Python language
Operator Description Example
& Binary AND Operator copies a bit to the result if it exists in both
(a & b) (means 0000 1100)
operands
^ Binary XOR It copies the bit if it is set in one operand but not both. (a ^ b) = 49 (means 0011 0001)
<< Binary Left Shift The left operands value is moved left by the number of
a << 2 = 240 (means 1111 0000)
bits specified by the right operand.
>> Binary Right Shift The left operands value is moved right by the number of
a >> 2 = 15 (means 0000 1111)
bits specified by the right operand.
Python Logical Operators
There are following logical operators supported by Python language. Assume variable a holds 10
and variable b holds 20 then
and Logical If both the operands are true then (a and b) is true.
AND condition becomes true.
not Logical Used to reverse the logical state of Not(a and b) is false.
NOT its operand.
not in Evaluates to true if it does not finds a variable in x not in y, here not in results in a 1 if x is not a
the specified sequence and false otherwise. member of sequence y.
1 while loop
2 for loop
3 nested loops
You can use one or more loop inside any another while, for or do..while
loop.
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed. Python supports the
following control statements. Click the following links to check their detail.
Let us go through the loop control statements briefly
1 break statement
Terminates the loop statement and transfers execution to the statement immediately following
the loop.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior to
reiterating.
3 pass statement
The pass statement in Python is used when a statement is required syntactically but you do
not want any command or code to execute.
I/O function ( GPIO, Digital)
Wedge Silk Python WiringPi Name P1 Pin Number Name WiringPi Python Wedge Silk
(BCM) GPIO GPIO (BCM)
RPi.GPIO
Raspberry-gpio-python or RPi.GPIO, is a Python module to control the GPIO interface on the
Raspberry Pi. It was developed by Ben Croston and released under an MIT free software license.
The RPi.GPIO module is installed by default on recent versions of Raspbian Linux. To use the
module from Python programs
first import it using:
import RPi.GPIO as GPIO
This way you can refer to all functions in the module using the shorter name "GPIO".
RPi.GPIO supports referring to GPIO pins using either the physical pin numbers on the GPIO
connector or using the BCM channel names from the Broadcom SOC that the pins are connected
to. For example, pin 24 is BCM channel GPIO8. To use physical board pin numbers
call:
GPIO.setmode(GPIO.BOARD)
and to use the BCM channel numbers
GPIO.setmode(GPIO.BCM)
Either method will work. The BOARD number scheme has the advantage that the library is aware
of the Raspberry Pi model it is running on and will work correctly even if the Broadcom SOC
channel names change in the future.
GPIO.output(channel, state)
where channel is the channel number and state is the desired output level: either 0, GPIO.LOW, or
False for a low value or 1, GPIO.HIGH, or True for a high level.
When you are done with the library, it is good practice to free up any resources used and return all
channels back to the safe default of being inputs. This is done by calling:
GPIO.cleanup()
Here is a very simple standalone example that toggles an output pin on and off for 200 milliseconds,
ten times. It also reports the level on input pin 31. If you put the commands in a file and make it
executable
Time Functions in Python
Python provides library to read, represent and reset the time information in many ways by
using “time” module. Date, time and date time are an object in Python, so whenever we do any
operation on them, we actually manipulate objects not strings or timestamps.
In this section we’re going to discuss the “time” module which allows us to handle various
operations on time.
The time module follows the “EPOCH” convention which refers to the point where the time
starts. In Unix system “EPOCH” time started from 1 January, 12:00 am, 1970 to year 2038.
To determine the EPOCH time value on your system
just type below code -
>>> import time
>>> time.gmtime(0)
Output
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0,
tm_wday=3, tm_yday=1, tm_isdst=0)
Most common functions in Python Time Module -
1. time.time() function
The time() is the main function of the time module. It measures the number of seconds since
the epoch as a floating point value.
Syntax
time.time()
import time
print("Number of seconds elapsed since the epoch are : ", time.time())
Output
Number of seconds elapsed since the epoch are : 1553262407.0398576
2. time.clock() function
The time.clock() function return the processor time. It is used for performance
testing/benchmarking.
Syntax time.clock()
The clock() function returns the right time taken by the program and it more accurate than its
counterpart.
Let’s write a program using above two time functions (discussed above) to differentiate:
Output
PROGRAM: time()# 1553263728.08, clock()# 0.00
---Sleeping for: 5 sec.
import time time()# 1553263733.14, clock()# 5.06
template = 'time()# {:0.2f}, clock()# {:0.2f}' ---Sleeping for: 4 sec.
print(template.format(time.time(), time.clock())) time()# 1553263737.25, clock()# 9.17
for i in range(5, 0, -1): ---Sleeping for: 3 sec.
print('---Sleeping for: ', i, 'sec.') time()# 1553263740.30, clock()# 12.22
time.sleep(i) ---Sleeping for: 2 sec.
print(template.format(time.time(), time.clock()) time()# 1553263742.36, clock()# 14.28
) ---Sleeping for: 1 sec.
time()# 1553263743.42, clock()# 15.34
3. time.ctime() function
time.time() function takes the time in “seconds since the epoch” as input and translates into a
human readable string value as per the local time. If no argument is passed, it returns the current
time.
Program:
import time
print('The current local time is :', time.ctime())
newtime = time.time() + 60
print('60 secs from now :', time.ctime(newtime))
Output
The current local time is : Fri Mar 22 19:43:11 2019
60 secs from now : Fri Mar 22 19:44:11 2019
4. time.sleep() function
time.sleep() function halts the execution of the current thread for the specified number of
seconds. Pass a floating point value as input to get more precise sleep time.
The sleep() function can be used in situation where we need to wait for a file to finish closing
or let a database commit to happen.
Program:
import time
# using ctime() to display present time Output
print ("Time starts from : ",end="") Time starts from : Fri Mar 22 20:00:00 2019
print (time.ctime()) Waiting for 5 sec.
# using sleep() to suspend execution Time ends at : Fri Mar 22 20:00:05 2019
print ('Waiting for 5 sec.')
time.sleep(5)
# using ctime() to show present time
print ("Time ends at : ",end="")
print (time.ctime())
https://www.javatpoint.com/python-tutorial
Python First Program
Unlike the other programming languages, Python provides the facility to execute the code using
few lines. For example - Suppose we want to print the "Hello World" program in Java; it will
take three lines to print it.
Java code
public class HelloWorld {
public static void main(String[] args)
{
System.out.println("Hello World"); // Prints "Hello, World" to the terminal window.
}
}
Both programs will print the same result, but it takes only one statement without using a
semicolon or curly braces in Python
Python program to do arithmetical operations
The arithmetic operations are performed by calculator where we can perform addition, subtraction,
multiplication and division. This example shows the basic arithmetic operations i.e.
Addition, Subtraction, Multiplication, Division
See this example:
Python program to swap two variables
Variable swapping:
In computer programming, swapping two variables specifies the mutual exchange of values of
the variables. It is generally done by using a temporary variable.
For example:
Python Program to Check if a Number is Odd or Even
Odd and Even numbers:
If you divide a number by 2 and it gives a remainder of 0 then it is known as even number,
otherwise an odd number.
Even number examples: 2, 4, 6, 8, 10, etc.
Odd number examples:1, 3, 5, 7, 9 etc.
For more basic programs refer to the following web site
https://www.javatpoint.com/python-programs