Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
8 views42 pages

Introduction To Raspberry Pi

Raspberry Pi with Python programming

Uploaded by

Pratiksha Kodag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views42 pages

Introduction To Raspberry Pi

Raspberry Pi with Python programming

Uploaded by

Pratiksha Kodag
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Programming using Python

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 are naming conventions for Python identifiers −


Class names start with an uppercase letter. All other identifiers start with a lowercase
letter.
Starting an identifier with a single leading underscore indicates that the identifier is
private.
Starting an identifier with two leading underscores indicates a strongly private
identifier.
If the identifier also ends with two trailing underscores, the identifier is a language-
defined special name.
Reserved Words
The following list shows the Python keywords. These are reserved
words and you cannot use them as constant or variable or any other
identifier names. All the Python keywords contain lowercase letters
only.

and exec not


assert finally or
break for pass
class from print
continue global raise
def if return
del import try
elif in while
else is with
except lambda yield
1. Variables
Variables are nothing but reserved memory locations to store values. This means that when you
create a variable you reserve some space in memory. Based on the data type of a variable, the
interpreter allocates memory and decides what can be stored in the reserved memory. Therefore,
by assigning different data types to variables, you can store integers, decimals or characters in these
variables.
1.1 Assigning Values to Variables
Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to assign
values to variables. The operand to the left of the = operator is the name of the variable and the
operand to the right of the = operator is the value stored in the variable. For example −
counter = 100 # An integer assignment
miles = 165.12 # A floating point
name = “Electronics" # A string

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 −

int long float complex


10 51924361L 0.0 3.14j

100 -0x19323L 15.20 45.j

-782 0122L -21.9 9.322e-36j

080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j

-0490 535633629843L -90. -.6545+0J

-0x260 -052318172735L -32.54e100 3e+26J

0x69 -4721885298529L 70.2-E12 4.53e-7j


• Python allows you to use a lowercase l with long, but it is recommended that you use only an
uppercase L to avoid confusion with the number 1. Python displays long integers with an
uppercase L.
• A complex number consists of an ordered pair of real floating-point numbers denoted by
x + yj, where x and y are the real numbers and j is the imaginary unit.
2. Python Strings

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 −

str = 'Hello World!' This will produce the following result −

print str # Prints complete string =Hello World!


print str[0] # Prints first character of the string =H
print str[2:5] # Prints characters starting from 3rd to 5th =llo
print str[2:] # Prints string starting from 3rd character =llo World!
print str * 2 # Prints string two times =Hello World!Hello World!
print str + "TEST" # Prints concatenated string =Hello World!TEST
3. Python Lists
Lists are the most versatile of Python's compound data types. A list contains items separated by
commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C.
One difference between them is that all the items belonging to a list can be of different data type.
The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting
at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list
concatenation operator, and the asterisk (*) is the repetition operator.
For example −
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john'] This produce the following result −

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

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


tinytuple = (123, 'john') This produce the following result −

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 −

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )


list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list
5. Python Dictionary

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'}

print dict['one'] # Prints value for 'one' key =This is one


print dict[2] # Prints value for 2 key =This is two
print tinydict # Prints complete dictionary ={'dept': 'sales', 'code': 6734, 'name': 'john'}
print tinydict.keys() # Prints all the keys =['dept', 'code', 'name']
print tinydict.values() # Prints all the values =['sales', 6734, 'john']

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.

3 float(x) Converts x to a floating-point number.

4 complex(real [,imag]) Creates a complex number.

5 str(x) Converts object x to a string representation.

6 repr(x) Converts object x to an expression string.

7 eval(str) Evaluates a string and returns an object.

8 tuple(s) Converts s to a tuple.


Continued…….

9 list(s) Converts s to a list.

10 set(s) Converts s to a set.

11 dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.

12 frozenset(s) Converts s to a frozen set.

13 chr(x) Converts an integer to a character.

14 unichr(x) Converts an integer to a Unicode character.

15 ord(x) Converts a single character to its integer value.

16 hex(x) Converts an integer to a hexadecimal string.

17 oct(x) Converts an integer to an octal string.


Python Operators
Operators are the constructs which can manipulate the value of operands. Consider the expression 4 +
5 = 9. Here, 4 and 5 are called operands and + is called operator.
Types of Operator
Python language supports the following types of operators.
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
Let us have a look on all operators one by one.
Python Arithmetic Operators
Assume variable a holds 10 and variable b holds 20, then −

Operator Description Example


+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand operand. a – b = -10

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b/a=2

% 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.


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 OR It copies a bit if it exists in either operand. (a | b) = 61 (means 0011 1101)

^ Binary XOR It copies the bit if it is set in one operand but not both. (a ^ b) = 49 (means 0011 0001)

~ Binary Ones (~a ) = -61 (means 1100 0011 in 2's


Complement It is unary and has the effect of 'flipping' bits. complement form due to a signed
binary number.

<< 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

Operator Description Example

and Logical If both the operands are true then (a and b) is true.
AND condition becomes true.

or Logical OR If any of the two operands are non- (a or b) is true.


zero then condition becomes true.

not Logical Used to reverse the logical state of Not(a and b) is false.
NOT its operand.

Python Membership Operators


Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below −
Operator Description Example

In Evaluates to true if it finds a variable in the x in y, here in results in a 1 if x is a member of


specified sequence and false otherwise. sequence y.

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.

Python Identity Operators


Identity operators compare the memory locations of two objects. There are two Identity
operators explained below −

Operator Description Example

Is Evaluates to true if the variables on either side


of the operator point to the same object and x is y, here is results in 1 if id(x) equals id(y).
false otherwise.

is not Evaluates to false if the variables on either side


x is not y, here is not results in 1 if id(x) is not equal
of the operator point to the same object and
to id(y).
true otherwise.
Decision making in Python
Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions. Decision structures evaluate multiple
expressions which produce TRUE or FALSE as outcome. You need to determine which action to take
and which statements to execute if outcome is TRUE or FALSE otherwise. Following is the general
form of a typical decision making structure found in most of the programming languages −
Python programming language assumes any non-zero and non-null values as
TRUE, and if it is either zero or null, then it is assumed as FALSE value.
Python programming language provides following types of decision making
statements.

Sr.No Statement & Description


.

1 if statements An if statement consists of a boolean expression followed


by one or more statements.

2 if...else statements An if statement can be followed by an optional else


statement, which executes when the boolean expression is FALSE.

3 nested if statements You can use one if or else if statement inside


another if or else if statement(s).
Loop Statments
In general, statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on. There may be a situation when you need to execute a block of
code several number of times. Programming languages provide various control structures that
allow for more complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple times. The
following diagram illustrates a loop statement −
Python programming language provides following types of loops to handle
looping requirements.
Sr. No. Loop Type & Description

1 while loop

Repeats a statement or group of statements while a given condition is


TRUE. It tests the condition before executing the loop body.

2 for loop

Executes a sequence of statements multiple times and abbreviates the


code that manages the loop variable.

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

Sr.No. Control Statement & Description

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)

3.3v DC Power 1 2 5v DC Power

SDA 8 GPIO02 (SDA1, I2C) 3 4 5v DC Power


Serial Data Line
SCL 9 GPIO03 (SCL1, I2C) 5 6 Ground
Serial Clock Line
G4 4 7 GPIO04 (GPIO_GCLK) 7 8 GPIO14 (TXD0) 15 TXO

Ground 9 10 GPIO15 (RXD0) 16 RXI

G17 17 0 GPIO17 (GPIO_GEN0) 11 12 GPIO18 (GPIO_GEN1) 1 18 G18

G27 27 2 GPIO27 (GPIO_GEN2) 13 14 Ground

G22 22 3 GPIO22 (GPIO_GEN3) 15 16 GPIO23 (GPIO_GEN4) 4 23 G23

3.3v DC Power 17 18 GPIO24 (GPIO_GEN5) 5 24 G24

MOSI 12 GPIO10 (SPI_MOSI) 19 20 Ground

MISO 13 GPIO09 (SPI_MISO) 21 22 GPIO25 (GPIO_GEN6) 6 25 G25

CLK (no worky GPIO11 (SPI_CLK) 23 24 GPIO08 (SPI_CE0_N) 10 CD0


14)
Ground 25 26 GPIO07 (SPI_CE1_N) 11 CE1

IDSD 30 ID_SD (I2C ID EEPROM) 27 28 ID_SC (I2C ID EEPROM) 31 IDSC

G05 5 21 GPIO05 29 30 Ground

G6 6 22 GPIO06 31 32 GPIO12 26 12 G12

G13 13 23 GPIO13 33 34 Ground

G19 19 24 GPIO19 35 36 GPIO16 27 16 G16

G26 26 25 GPIO26 37 38 GPIO20 28 20 G20

Ground 39 40 GPIO21 29 21 G21


A Bit about Python
Python is an interpreted, high-level, general-purpose programming language that has been
around since 1991. It is currently one of the most popular and fastest growing programming
languages. The "Pi" in Raspberry Pi standards for "Python Interpreter," reflecting the fact that
this is the recommended language on the platform.
A nice feature of Python is that, being an interpreter, you can type in and try commands
interactively without needing to create a program. Being an interpreter there is no need to
explicitly compile programs. They are compiled at run time into an intermediate byte code which
is executed by a virtual machine.
The example code in this blog post is written for Python 3 and should work on any Raspberry Pi
model.

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.

To set up a channel as an input or an output, call either:


GPIO.setup(channel, GPIO.IN)
or
GPIO.setup(channel, GPIO.OUT)
Where channel is the channel number based on the numbering system you specified when you
called setmode.
To read the value of an input channel, call:
GPIO.input(channel)
where channel is the channel number as used in setup. It will return a value of 0, GPIO.LOW, or
False (all are equivalent) if it is low and 1, GPIO.HIGH, or True if it was at a high level.

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()

Program to demonstrate above function:

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.
}
}

On the other hand, we can do this using one statement in Python.


print("Hello World")

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

You might also like