You are on page 1of 36

Introduction to Python Programming

1
Objectives
After completing this module, you should be able to:
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

2
What is Python?

A dynamic, open source programming language with a focus on


simplicity and productivity. It has an
elegant syntax that is natural to read and easy to write.

3 3
Who uses Python?

4 4
Why Python ?

5 5
Why Python?
Python is Simple & Beautiful

Python is Object-Oriented

supports concepts as Polymorphism, Operation overloading & Multiple

Inheritance

Python is Free (Open Source Language )

Downloading & Installing Python is Free & Easy

Source Code is easily Accessible

Python is Portable & Powerful

Runs virtually on every major Platforms used today

Dynamic Typing, Built-in types & tools, Library Utilities, Automatic Memory
6 6
Python VS Java

7 7
Version of Python
There are two versions of Python currently available:

Python 2.x
Python 3.x

Now the question is which version should we use?

8 8
Lets see the basic differences
Python 2.x is legacy, Python 3.x is the present and future
of the language
The most visible difference is probably the way the “print”
statement works.

In Python2 it’s a statement print “Hello World!”

In Python3 it’s a function print(“Hello World!”)

9 9
Python Strings
Strings in Python are identified as a contiguous set of characters in between quotation marks

str = 'Hello World!’


print(str) # Prints complete string
print(str[0]) # Prints first character of the string
print(str[2:5]) # Prints characters starting from 3rd to 6th
print(str[2:]) # Prints string starting from 3rd character
print(str * 2) # Prints string two times
print(str + "TEST“) # Prints concatenated string

10 10
Arithmetic Operators
Operator Meaning Example

+ Add two operands or unary plus x+y

- Subtract right operand from left x-y

* Multiply two operands x*y

/ Divide left operand by the right one (always results into float) x/y

x%y
% Modulus - remainder of the division of left operand by the right
(remainder of x/y)

Floor division - division that results into whole number adjusted


// x // y
to the left in the number line

x**y
** Exponent - left operand raised to the power of right
(x to the power y)

11 11
Comparison Operators
Operator Meaning Example

> Greater that - True if left operand is greater than the right x>y

< Less that - True if left operand is less than the right x<y

== Equal to - True if both operands are equal x == y

!= Not equal to - True if operands are not equal x != y

Greater than or equal to - True if left operand is greater than or equal to the
>= x >= y
right

<= Less than or equal to - True if left operand is less than or equal to the right x <= y

12 12
Logical Operators
Operator Meaning Example

and True if both the operands are true x and y

or True if either of the operands is true x or y

not True if operand is false (complements the operand) not x

13 13
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 ([]).

list1 = [ ‘hello', 786 , 4.1, ‘Ram', 702 ]


list2 = [123, ‘Victor’]
print(list1) # Prints complete list
print(list1[0]) # Prints first element of the list
print(list1[1:3]) # Prints elements starting from 2nd to 4th
print(list1[2:]) # Prints elements starting from 3rd element
print(list2 * 2) # Prints list two times
print(list1 + list2) # Prints concatenated lists

14 14
Positive and Negative Indices
t = [23, ‘abc’, 4.56, [2,3], ‘def’]

Positive index: count from the left, starting with 0


>>> t[1]
‘abc’

Negative index: count from right, starting with –1


>>> t[-3]
4.56

15 15
Lists are Mutable
We can change lists in place
Name li still points to the same memory reference when we’re done

>>> li = [‘abc’, 23, 4.34, 23]


>>> li[1] = 45
>>> li
[‘abc’, 45, 4.34, 23]

16 16
Operations on Lists Only
>>> li = [1, 11, 3, 4, 5]
>>> li.append(‘a’) # Note the method syntax
>>> li
[1, 11, 3, 4, 5, ‘a’]

>>> li.insert(2, ‘i’)


>>>li
[1, 11, ‘i’, 3, 4, 5, ‘a’]

17 17
Operations on Lists Only
Lists have many methods, including index, count, remove, reverse, sort

>>> li = [‘a’, ‘b’, ‘c’, ‘b’]


>>> li.index(‘b’) # index of 1st occurrence
1
>>> li.count(‘b’) # number of occurrences
2
>>> li.remove(‘b’) # remove 1st occurrence
>>> li
[‘a’, ‘c’, ‘b’]

18 18
Python Tuples
A tuple is another sequence data type that is similar to the list. Unlike lists, however, tuples are
enclosed within parentheses

tuple1 = ( ‘hello', 786 , 2.23, ‘victor', 70.2 )


tuple2 = (123, ‘jay’)
print(tuple1) # Prints complete list
print(tuple1[0]) # Prints first element of the list
print(tuple1[1:3]) # Prints elements starting from 2nd to 4th
print(tuple1[2:]) # Prints elements starting from 3rd element
print(tuple2 * 2) # Prints list two times
print(tuple1 + tuple2) # Prints concatenated lists

19 19
Tuples are Immutable
You can’t change a tuple.
You can make a fresh tuple and assign its reference to a previously used name

>>> t = (23, ‘abc’, 4.56, (2,3), ‘def’)


>>> t[2] = 3.14
Traceback (most recent call last):
File "<pyshell#75>", line 1, in -toplevel-
tu[2] = 3.14
TypeError: object doesn't support item assignment

>>> t = (23, ‘abc’, 3.14, (2,3), ‘def’)

20 20
The ‘in’ Operator
Boolean test whether a value is inside a For strings, tests for substrings
container

>>> t = [1, 2, 4, 5] >>> a = 'abcde'


>>> 3 in t >>> 'c' in a
False True
>>> 4 in t >>> 'cd' in a
True True
>>> 4 not in t >>> 'ac' in a
False False

Be careful: the in keyword is also used in the syntax of for loops and list
comprehensions

21 21
Python Set
A set contains an unordered collection of unique and immutable objects. The set data type is, as
the name implies, a Python implementation of the sets as they are known from mathematics. This
explains, why sets unlike lists or tuples can't have multiple occurrences of the same element.

>>> adjectives = {"cheap","expensive","inexpensive","economical"}


>>> adjectives
set(['inexpensive', 'cheap', 'expensive', 'economical’])

>>> x = set("A Python Tutorial")


>>> x
set(['A', ' ', 'i', 'h', 'l', 'o', 'n', 'P', 'r', 'u', 't', 'a', 'y’, 'T'])

>>> cities = set(("Paris", "Lyon", "London","Berlin","Paris","Birmingham"))


>>> cities
set(['Paris', 'Birmingham', 'Lyon', 'London', 'Berlin']) >>>

22 22
Python Dictionary
Python 's dictionaries consist of key-value pairs

dict1 = {'name': 'john','code':6734, 'dept': 'sales'}


print(dict1['name’]) # Prints value for 'one' key
print(dict['code’]) # Prints value for 2 key
print(dict1) # Prints complete dictionary
print(dict1.keys()) # Prints all the keys
print(dict1.values()) # Prints all the values

23 23
If else structure
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)

24 24
For loop
for iterating_var in sequence:
statements(s)
#example
fruits = ['apple', 'banana', 'cherry’]
for fruit in fruits:
print(fruit.upper())
#output
APPLE
BANANA
CHERRY

25 25
List Comprehension
>>> # for loop to create a list of cubes
>>> nums = [1, 2, 3, 4, 5]
>>> cubes = []
>>> for num in nums:
>>> cubes.append(num**3)
>>> # equivalent list comprehension
>>> cubes = [num**3 for num in nums] # [1, 8, 27, 64, 125]

>>> # for loop to create a list of cubes of even numbers


>>> cubes_of_even = []
>>> for num in nums:
>>> if num % 2 == 0:
>>> cubes_of_even.append(num**3)
>>> # equivalent list comprehension
>>> # syntax: [expression for variable in iterable if condition]
>>> cubes_of_even = [num**3 for num in nums if num % 2 == 0] # [8, 64]

26 26
While loop
while expression:
statements(s)
# while loop Example
count = 0
while count < 5:
print("This will print 5 times")
count += 1 # equivalent to 'count = count + 1’
#output
This will print 5 times
This will print 5 times
This will print 5 times
This will print 5 times
This will print 5 times

27 27
Defining Functions
Argument

28 28
Defining Functions
def functionname( parameters ):

"function_docstring"

function_suite

return [expression]

Example:

def printme( str ):

"This prints a passed string into this function"

print(str)

return

29 29
Object Oriented Programming - Class

>>> class person:


def sayhi(self):
print(‘Hello, How are you?’)
>>> p=person()
>>> p.sayhi()
Hello, How are you?

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

31 31
Object Oriented Programming - Class
The 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.

class Person:
def __init__(self, name):
self.name = name

def say_hi(self):
print('Hello, my name is', self.name)

p = Person('Swaroop')
p.say_hi()

32 32
Learning Check Question
Choose the right answer -
What is the output of [1, 2, 3] + [4, 5, 6]?
A. [1, 2, 3, 4, 5, 6]
B. [1, 2, 3],[4, 5, 6]
C. [5, 7,9]
D. 21

33
Learning Check Answer
Choose the right answer -
What is the output of [1, 2, 3] + [4, 5, 6]?
A. [1, 2, 3, 4, 5, 6]
B. [1, 2, 3],[4, 5, 6]
C. [5, 7,9]
D. 21

34
Summary
This module covered the following topics:
Atomic Data Types – Integers, Strings, Float, Boolean and
Complex
Operators in Python – Arithmetic, Comparison and Logical
Main Data Types – List, Tuple, Set and Dictionary
Control Structure – IF else, For loop and While Loop
Defining Functions in Python
Object Oriented Programming using Python

35
Thank you

36

You might also like