Python Unit 1
Python Unit 1
Python Unit 1
Vinita Shah
Asst. Professor, IT Dept., GCET
Motivation
Python is a popular programming language.
Software Development –
• SCons for build control.
• Buildbot and Apache Gump for automated continuous
compilation and testing.
• Roundup or Trac for bug tracking and project management.
How to run your code!
• Python uses interpreter to run the code.
• Two ways to code:
▫ Script mode: write python code in a file.py and
execute it from interpreter.
▫ Command line mode: interactive shell is used to give
command which will be executed immediately by the
interpreter
Famous Python Interpreters
• PyCharm
• PyDev
• IDLE
• Spyder
• Google Colab
• Visual Studio Code
• Sublime
• Atom
• Vim
IDLE
(Integrated Development and Learning Environment)
Anaconda – Spyder
Google Colab
Hello world !
• Script mode:
file.py
print (“Hello world !”)
• Command line:
>>> print(“Hello world !”)
Basic Elements
Python program, sometimes called a script, is a sequence of
definitions and commands.
pi = 3.1415926
message = "Hello, world" Output:
i=2 <type 'float'>
<type 'str'>
print(type(pi)) <type 'int'>
print(type(message))
print(type(i))
Variable naming conventions
Can contain letters, numbers, and underscores
Must begin with a letter
Cannot be one of the reserved Python keywords:
and, as, assert, break, class, continue, def, del, elif,
else, except, exec, finally, for, from, global, if,
import, in, is, lambda, not, or, pass, print, raise,
return, try, while, with, yield
User Input
For example:
#This would be a comment in Python
Python Comments
Example 1 –
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Example 2–
"""
This would be a multiline comment
in Python that spans several lines and
describes your code, your day, or anything you want it to
"""
Data Types
Index (from
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
left)
Index (from
-15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
right)
Special Characters in String
import keyword
print(keyword.kwlist)
Output -
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break',
'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for',
'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not',
'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Description of Keywords
True, False
True and False are truth values in Python. They are the results of
comparison operations or logical (Boolean) operations in Python.
True and False in python is same as 1 and 0. This can be justified with
the following example
>>> True == 1
True
>>> False == 0
True
>>> True + True
2
Description of Keywords
None -
None is a special constant in Python that represents the absence of a
value or a null value.
We must take special care that None does not imply False, 0 or any
empty list, dictionary, string etc.
Void functions that do not return anything will return a None object
automatically.
def a_void_function():
a=1
b=2
c=a+b
x = a_void_function()
print(x)
Output -
None
None
program has a function that does not return a value, although it does
some operations inside. So when we print x, we get None which is
returned automatically (implicitly).
def improper_return_function(a):
if (a % 2) == 0:
return True
x = improper_return_function(3)
print(x)
The function will return True only when the input is even.
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
Comparison Operators
Comparison operators compares the values. It either
returns True or False according to the condition.
& And x&y Bits that are set in both x and y are set.
^ Xor x^y Bits that are set in x or y but not both are set.
<< Shift left x <<y Shift the bits of x, y steps to the left
>> Shift right x >>y Shift the bits of x, y steps to the right.
Bitwise Operators
# Examples of Bitwise operators
a = 10
b=4
print(a2 is b2)
Membership Operators
# Examples of Membership
operator
x = 'Python Programming'
Output:
print('P' in x) True
a = 10
b = 20
list = [1, 2, 3, 4, 5 ];
if ( a in list ):
print "Line 1 - a is available in the given list"
else:
print "Line 1 - a is not available in the given list"
Output:
if ( b not in list ): Line 1 - a is not available in
print "Line 2 - b is not available in the given list" the given list
else:
print "Line 2 - b is available in the given list"
Line 2 - b is not available in
a=2 the given list
if ( a in list ):
print "Line 3 - a is available in the given list"
Line 3 - a is available in the
else:
print "Line 3 - a is not available in the given list" given list
Decision Making in Python
• if statement
• if..else statements
• nested if statements
• if-elif ladder
Decision Making in Python
if statement
if condition:
statement1
statement2
if-else statement
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Decision Making in Python
if-else statement
i = 20
if (i < 15):
print ("i is smaller than 15") Output:
print ("i'm in if Block") i is greater than 15
i'm in else Block
else:
print ("i is greater than 15")
print ("i'm in else Block")
Decision Making in Python
Nested if statement
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Decision Making in Python
Nested if statement
i = 10
if (i == 10):
if-elif-else ladder
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Decision Making in Python
if-elif-else ladder
i = 20
if (i == 10):
print ("i is 10")
elif (i == 20):
print ("i is 20")
else:
print ("i is not present")
Looping in Python
While Loop:
Syntax:
while expression:
statement(s)
count = 0 Output:
while (count < 3): Hello
count = count + 1 Hello
print("Hello") Hello
Looping in Python
count = 0
while (count < 3): Output:
Hello
count = count + 1
Hello
print("Hello") Hello
else: In Else Block
print("In Else Block")
Looping in Python
for in loop:
Syntax:
print("String Iteration")
Output:
s = “hello” h
e
for i in s : l
print(i) l
o
Looping in Python
for in loop: - Range Function
range(start, end, inc/dec) –
range(5) = [0,1,2,3,4]
range(2,6) = [2,3,4,5]
range(1,8,2) = ???
[1,3,5,7]
range(10,2,-2) = ???
[10,8,6,4]
Looping in Python
Output:
for x in range(2, 6): 2
print(x) 3
4
5
Looping in Python
Example –
Print all numbers from 0 to 5, and print a message when the
loop has ended.
Output:
for x in range(6): 0
print(x) 1
else: 2
print("Finally finished!") 3
4
5
Finally finished!
Looping in Python
for n in range(10,20):
for i in range(2,n):
if n%i==0:
j=n/i
break
else:
print(n,“is a prime number”)
Program
x = 10
y=5
x=x+y
y=x-y
x=x-y
sum = 0
while (n != 0):
sum = sum + int(n % 10)
n = int(n/10)
print(sum)
break statement
With the break statement we can stop the loop even if the
while condition is true
i=1
while i < 6:
Output –
print(i)
1
if i == 3: 2
break 3
i += 1
continue statement
i=0
while i < 6:
Output –
i += 1
1
if i == 3: 2
continue 4
print(i) 5
6
Functions
• Define and Call function
Syntax of Function –
def function_name(parameters):
"""docstring"""
statement(s)
Functions
• Significance of Indentation (Space) in Python
Functions
• Define and Call function
Program
avg_number(3, 4)
Program
def evenOdd( x ):
if (x % 2 == 0):
print "even"
else:
print "odd"
evenOdd(2)
evenOdd(3)
Program
Write a program for find factorial of a given number using iterative
function.
Num = int(input("Enter a number: "))
factorial = 1
Advantages of Recursion:
def greet(name):
print("Hello, " + name + ". Good morning!")
Syntax of return -
return [expression_list]
This statement can contain an expression that gets evaluated and the
value is returned.
if num >= 0:
return num
else:
return -num
print(absolute_value(2))
print(absolute_value(-4))
Scope and Lifetime of Variables
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:", x)
Output –
Value inside function: 10
Value outside function: 20
Local Scope
A variable created inside a function belongs to the local scope
of that function, and can only be used inside that function.
def myfunc():
x = 300
print(x)
myfunc()
Output –
300
Function inside function
A variable created inside a function belongs to the local scope
of that function, and can only be used inside that function.
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
Output –
300
Global Scope
A variable created in the main body of the Python code is a
global variable and belongs to the global scope.
x = 300
def myfunc():
print(x)
Output –
myfunc() 300
300
print(x)
Same variable name
If you operate with the same variable name inside and outside of a
function, Python will treat them as two separate variables, one
available in the global scope (outside the function) and one available
in the local scope (inside the function)
x = 300
def myfunc():
x = 200 Output –
print(x) 200
300
myfunc()
print(x)
Global Keyword
If you need to create a global variable, but are stuck in the local
scope, you can use the global keyword.
def myfunc():
global x
x = 300
Output –
myfunc() 300
print(x)
Global Keyword
Use the global keyword if you want to make a change to a global
variable inside a function.
x = 300
def myfunc():
global x
x = 200
Output –
myfunc() 200
print(x)
Th a n k
Yo u