Professional Documents
Culture Documents
Module Handbook
Module Handbook
Module Handbook
Python Programming Introduction
Objectives
At the end of this module, you should be able to understand:
▪ Start writing basic codes in Python
▪ Work with Numbers, variables & basic operations in python
▪ Work with Data Types – Lists, tuples & dictionary in python
▪ Create Rule based systems using if else, for and while loop
▪ Write user defined functions
▪ Writing codes using OOPs
www.bootup.ai
Python
Getting Started –
Type the following text at the Python prompt and press Enter −
If you are running the older version of Python (Python 2.x), use of parenthesis as
inprint function is optional. This produces the following result −
Hello, World!
www.bootup.ai
Python
Declaring Variables
Variables are nothing but reserved memory locations to store values. It means that when you create a
variable, you reserve some space in the memory.
print (count)
print (miles)
print (name)
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables,
respectively. This produces the following result −
100
1000.0
Anshu Pandey
www.bootup.ai
Data Types in Python
• Numbers
• String
• List
• Tuple
• Dictionary
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
www.bootup.ai
Python
Python Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation marks.
Python allows either pair of single or double quotes.
Hello World!
H
llo
llo World!
Hello World!Hello World!
Hello World!TEST
www.bootup.ai
Python
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 of the
differences between them is that all the items belonging to a list can be of different data type.
www.bootup.ai
Python
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 parenthesis.
The main difference 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 –
www.bootup.ai
Python
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 = {}
This is one
This is two
{'name': 'john', 'dept': 'sales', 'code': 6734}
dict_keys(['name', 'dept', 'code'])
dict_values(['john', 'sales', 6734])
9
www.bootup.ai
Python
Data Type Conversion
Sometimes, you may need to perform conversions between the built-in types. To convert between types,
you simply use the type-names 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.
10
www.bootup.ai
Python
Python Arithmetic Operators
Assume variable a holds the value 10 and variable b holds the value 21, then
- Subtraction Subtracts right hand operand from left hand operand. a – b = -11
a**b =10 to
** Exponent Performs exponential (power) calculation on operators
the power 20
11
www.bootup.ai
Operators in Python
Python Comparison Operators
These operators compare the values on either side of them and decide the relation among them. They
are also called Relational operators.
Assume variable a holds the value 10 and variable b holds the value 20, then
12
www.bootup.ai
Operators in Python
Python Assignment Operators
Assume variable a holds the value 10 and variable b holds the value 20, then
c = a + b assigns
= Assigns values from right side operands to left side operand value of a + b into
c
c += a is
It adds right operand to the left operand and assign the
+= Add AND equivalent to c = c
result to left operand
+a
c -= a is
It subtracts right operand from the left operand and assign
-= Subtract AND equivalent to c = c
the result to left operand
–a
c *= a is
*= Multiply It multiplies right operand with the left operand and assign
equivalent to c = c
AND the result to left operand
*a
c /= a is
equivalent to c = c
It divides left operand with the right operand and assign the
/= Divide AND / ac /= a is
result to left operand
equivalent to c = c
/a
c %= a is
%= Modulus It takes modulus using two operands and assign the result
equivalent to c = c
AND to left operand
%a
c **= a is
**= Exponent Performs exponential (power) calculation on operators and
equivalent to c = c
AND assign value to the left operand
** a
c //= a is
//= Floor It performs floor division on operators and assign value to
equivalent to c = c
Division the left operand
// a
13
www.bootup.ai
Reserved Words
The following list shows the Python keywords. These are reserved words and you cannot use them as
constants or variables or any other identifier names. All the Python keywords contain lowercase letters
only.
as finally Or
continue if Return
del in While
elif is With
except
14
www.bootup.ai
Python – Reading Input from Keyboard
Python 2 has two versions of input functions, input() and raw_input(). The input() function treats the
received data as string if it is included in quotes '' or "", otherwise the data is treated as number.
In Python 3, raw_input() function is deprecated. Further, the received data is always treated as string.
>>> x = input("something:")
something:10
>>> x
'10'
>>> x = input("something:")
something:'10' #entered data treated as string with or without ''
>>> x
"'10'"
15
www.bootup.ai
Python – Control Flow
Decision Making – IF Condition
The IF statement is similar to that of other languages. The if statement contains a logical expression using
which the data is compared and a decision is made based on the result of the comparison.
var1 = 100
if var1:
print (var1)
var2 = 0
if var2:
print (var2)
16
www.bootup.ai
Python – Control Flow
Decision Making – IF condition
There may be a situation when you want to check for another condition after a condition resolves to true.
In such a situation, you can use the nested ifconstruct.
In a nested if construct, you can have an if...elif...else construct inside another if...elif...else construct.
enter number8
divisible by 2 not divisible by 3
enter number15
divisible by 3 not divisible by 2
enter number12
Divisible by 3 and 2
17
www.bootup.ai
Python – Control Flow
For Loop
Executes a sequence of statements multiple times and abbreviates the code that manages the loop
variable.
Example
range() generates an iterator to progress integers starting with 0 up to n-1. To obtain a list object of the
sequence, it is type casted to list(). Now this list can be iterated using thefor statement.
0
1
2
3
4
18
www.bootup.ai
Python – Control Flow
While Loop
Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before
executing the loop body.
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
19
www.bootup.ai
Python – Functions
While Loop
A function is a block of organized, reusable code that is used to perform a single, related action. Functions
provide better modularity for your application and a high degree of code reusing.
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define a function
in Python.
• Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
• Any input parameters or arguments should be placed within these parentheses. You can also define
parameters inside these parentheses.
• The code block within every function starts with a colon (:) and is indented.
• The statement return [expression] exits a function, optionally passing back an expression to the caller.
A return statement with no arguments is the same as return None.
20
www.bootup.ai
Python – File I/O Handling
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10)
print ("Read String is : ", str)
The above method would create foo.txt file and would write given content in that file and finally it
would close that file. If you would open this file, it would have the following content −
21
www.bootup.ai
Python – File I/O Handling
# Open a file
fo = open("foo.txt", "w")
fo.write( "Python is a great language.\nYeah its great!!\n")
22
www.bootup.ai
Python – Object Oriented Programming
Python has been an object-oriented language since the time it existed. Due to this, creating and using
classes and objects are downright easy.
Example
class Employee:
'Common base class for all employees'
empCount = 0
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
• The variable empCount is a class variable whose value is shared among all the instances of a in this
class. This can be accessed as Employee.empCount from inside the class or outside the class.
• The first method __init__() is a special method, which is called class constructor or initialization
method that Python calls when you create a new instance of this class.
• You declare other class methods like normal functions with the exception that the first argument to
each method is self. Python adds the self argument to the list for you; you do not need to include it
when you call the methods.
23
www.bootup.ai
Python – Object Oriented Programming
Inheritance
>>> class A:
def hello(self):
print(‘I am Super Class’)
>>> class B(A):
def bye(self):
print(‘I am Sub Class’)
>>> p=B()
>>> p.hello()
I am Super Class
>>> p.bye()
I am Sub Class
24
www.bootup.ai
Summary
This Module covered following topics
▪ Start writing basic codes in Python
▪ Work with Numbers, variables & basic operations in python
▪ Work with Data Types – Lists, tuples & dictionary in python
▪ Create Rule based systems using if else, for and while loop
▪ Write user defined functions
▪ Writing codes using OOPs
25
www.bootup.ai
© Copyright BootUP 2019
BootUP
Noble House, 30th Floor
Jl. Dr.Ide Anak Agung Gde Agung
Mega Kuningan, Jakarta 12950
Jakarta, Indonesia
2019
www.bootup.ai
INDONESIA UNITED STATES
Noble House, 30th Floor 68 Willow Rd
Jl. Dr.Ide Anak Agung Gde Agung Menlo Park, CA 94025
Mega Kuningan, Jakarta 12950 Silicon Valley, USA
+62 811 992 1500 +1 800 493 1945
info@bootup.ai info@bootupventures.com
www.bootup.ai