Python Unit 1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 84

Programming with Python

A.Y. 2022-23 (Odd) Semester: 5


(Information Technology)
(Course Code: 102044504)

Vinita Shah
Asst. Professor, IT Dept., GCET
Motivation
Python is a popular programming language.

It was created in 1991 by Guido van Rossum.


Why is it called Python?
When Guido van Rossum began implementing Python,
He was also reading the published scripts from
“Monty Python’s Flying Circus”, a BBC comedy series in
1970s.

Van Rossum thought he needed a name that was short,


unique, and slightly mysterious, so he decided to call the
language Python.
Features
The syntax in Python helps the programmers to do coding in
fewer steps as compared to Java or C++.

Large standard library that has automatic memory


management and dynamic features.

Python works on different platforms (Windows, Mac,


Linux, Raspberry Pi, etc).

Python has a simple syntax similar to the English language.

Python runs on an interpreter system, meaning that code


can be executed as soon as it is written. This means that
prototyping can be very quick.
Applications of Python
Python is used in many application domains.

Web and Internet Development -


• Frameworks such as Django and Pyramid.
• Micro-frameworks such as Flask and Bottle.

Scientific and Numeric


• NumPy is a general-purpose array-processing package. It
provides a high-performance multidimensional array object,
and tools for working with these arrays.
• SciPy is a collection of packages for mathematics, science, and
engineering.
• Pandas is a data analysis and modeling library.
• IPython is a powerful interactive shell that features easy
editing and recording of a work session, and supports
visualizations and parallel computing.
Applications of Python
Desktop GUIs -
Tkinter GUI library and Turtle
Some toolkits that are usable on several platforms are available
separately:
• wxWidgets
• Kivy, for writing multitouch applications.
• Qt via pyqt or pyside

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.

These definitions are evaluated and the commands are executed


By the Python interpreter in something called the shell.

Typically, a new shell is created whenever execution of a program


begins. In most cases, a window is associated with the shell.

A command, often called a statement, instructs the interpreter to


do something.
For example,
print (‘Hello’)
Basic understanding of python code

• Indentation matters to code meaning


• First assignment to a variable creates it
• Variable types don’t need to be declared.
• Python figures out the variable types on its own from
the value given to a variable.
• The basic printing command is print
• # is used for comments
Variables
• Type of a variable can be retrieved like
Example types.py:

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

j = input("Enter input: ")


print(j)
print(type(j))

i = eval(input("Enter input: "))


print(i)
print(type(i)) Output:

Enter input : 3+2


3+2
<class 'str'>

Enter input : 3+2


5
<class ‘int'>
Python Comments

In Python, there are two ways to annotate your code.

Single-line comments are created simply by beginning a line with the


hash (#) character, and they are automatically terminated by the end
of line.

For example:
#This would be a comment in Python
Python Comments

Comments that span multiple lines –


Used to explain things in more detail – are created by adding a triple
quotes (""") on each end of the comment.

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

• Numbers – int, float, complex


• String
• Boolean
• List
• Tuple
• Dictionary
• Set
Data Types
Type Keyword Example
Text Type: str x = "Hello World"
Numeric Types: int, float, complex X=20
X=20.5
X=2j
Sequence list, tuple, range x = ["apple", "banana", "cherry"]
Types: x = ("apple", "banana", "cherry")
x = range(6)
Mapping Type: dict x = {"name" : "John", "age" : 36}

Set Types: set, frozenset x = {"apple", "banana", "cherry"}


x = frozenset({"apple", "banana",
"cherry"})
Boolean Type: bool x = True
None Type: NoneType x = None
Strings
Strings start and end with single or double quotes.
Python strings are immutable.

Strings are arrays of characters and elements of an array can be


accessed using indexing.
Indices start with 0 from left side and -1 when starting from right
side.
string1 ="PYTHON TUTORIAL"
Character P Y T H O N T U T O R I A L

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

The backslash (\) character is used to introduce a special


character.

Escape sequence Meaning


\n Newline
\t Horizontal Tab
\\ Backslash
\' Single Quote
\" Double Quote
Python Keywords
Keywords are the reserved words in Python. We cannot use a
keyword as a variable name, function name or any other identifier.

The above keywords may get altered in different versions of


Python. Some extra might get added or some might be removed.
Python Keywords

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.

>>> 1 == 1 >>> 10 <= 1


True False
>>> 5 > 3 >>> 3 > 7
True False
>>> True or False >>> True and False
True False
Description of Keywords

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.

It is an object of its own datatype, the NoneType. We cannot create


multiple None objects but can assign it to variables.

We must take special care that None does not imply False, 0 or any
empty list, dictionary, string etc.

>>> None == 0 >>> x = None


False >>> y = None
>>> None == [] >>> x == y
False True
>>> None == False
False
None

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.

If we give the function an odd number, None is returned implicitly.


Operators

• Arithmetic operators: +,-,*,/,%,//,**


• Comparison operators: ==,!=,<,>,<=,>=
• Assignment operators: =,+=,-=,*=,/=,//=
• Bitwise operators: &,|,^,~,<<,>>
• Logical operators: and, or , not
• Identity Operators: is, is not
• Membership operators: in, not in
Arithmetic Operators

Operator Name Example Result


+ Addition x+y Sum of x and y.
- Subtraction x-y Difference of x and y.

* Multiplication x*y Product of x and y.

/ Division x/y Quotient of x and y.

% Modulus x%y Remainder of x divided by y.

** Exponent x**y x**y will give x to the power y

The division of operands where


the result is the quotient in which
// Floor Division x// y
the digits after the decimal point
are removed
Arithmetic Operators
# Addition of numbers
add = a + b
# Subtraction of numbers
sub = a - b
# Multiplication of number
mul = a * b
# Division(float) of number
div1 = a / b
# Division(floor) of number
div2 = a // b
# Modulo of both number
mod = a % b

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

Operator Name Example Result


== Equal x==y True if x is exactly equal to y.
!= Not equal x!=y True if x is exactly not equal to y.
True if x (left-hand argument) is
Greater
> x>y greater than y (right-hand
than
argument).
True if x (left-hand argument) is
< Less than x<y less than y (right-hand
argument).
Greater True if x (left-hand argument) is
>= than or x>=y greater than or equal to y (left-
equal to hand argument).
True if x (left-hand argument) is
Less than
<= x<=y less than or equal to y (right-hand
or equal to
argument).
Logical Operators

Operator Example Result


and (x and y) is True if both x and y are true.
or (x or y) is True if either x or y is true.
If a condition is true then Logical not
not (x not y) operator will make false.
Assignment Operators
Operator Shorthand Expression Description
Adds 2 numbers and assigns the
+= x+=y x=x+y
result to left operand.
Subtracts 2 numbers and assigns the
-= x-= y x = x -y
result to left operand.
Multiplies 2 numbers and assigns
*= x*= y x = x*y
the result to left operand.
Divides 2 numbers and assigns the
/= x/= y x = x/y
result to left operand.
Computes the modulus of 2
%= x%= y x = x%y numbers and assigns the result to
left operand.
Performs exponential (power)
calculation on operators and assign
**= x**=y x = x**y
value to the equivalent to left
operand.
Performs floor division on operators
//= x//=y x = x//y
and assign value to the left operand.
Bitwise Operators

Operator Shorthand Expression Description

& And x&y Bits that are set in both x and y are set.

| Or x|y Bits that are set in either x or y are set.

^ Xor x^y Bits that are set in x or y but not both are set.

Bits that are set in x are not set, and vice


~ Not ~x
versa.

<< 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 bitwise AND operation


print(a & b)

# Print bitwise OR operation


print(a | b)
Output:
0
# Print bitwise NOT operation 14
print(~a)
-11
# print bitwise XOR operation 14
print(a ^ b) 2
# print bitwise right shift operation
40
print(a >> 2)

# print bitwise left shift operation


print(a << 2)
Identity Operators

is and is not are the identity operators both are used to


check if two values are located on the same part of the
memory.

is - True if the operands are identical


is not - True if the operands are not identical
Identity Operators

# Examples of Identity operators


a1 = 3
b1 = 3
Output:
a2 = ‘Hello’ False
b2 = ‘Hello’ True

print(a1 is not b1)

print(a2 is b2)
Membership Operators

• in and not in are the membership operators.

• Used to test whether a value or variable is in a sequence.

in - True if value is found in the sequence


not in - True if value is not found in the sequence
Membership Operators

# Examples of Membership
operator
x = 'Python Programming'

Output:
print('P' in x) True

print('programming' not in x) True

print(‘Python' not in x) False


Membership Operators

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

There comes situations in real life when we need to make some


decisions and based on these decisions, we decide what should
we do next.

Similar situations arises in programming also where we need to


make some decisions and based on these decision we will execute
the next block of code.

• if statement
• if..else statements
• nested if statements
• if-elif ladder
Decision Making in Python

if statement

if condition:
statement1

statement2

# Here if the condition is true, if block


# will consider only statement1 to be
inside its block.
Decision Making in Python

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 (i < 15): Output:


print ("i is smaller than 15") i is smaller than 15
i is smaller than 12 too
if (i < 12):
print ("i is smaller than 12 too")
else:
print ("i is greater than 15")
Decision Making in Python

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 == 15): Output:


print ("i is 15") i is 20

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

Using else statement with while loops:


Syntax:
while condition:
# execute these statements
else:
# execute these statements

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:

for iterator_var in sequence:


statements(s)

fruits = ["apple", "banana", “cherry"] Output:


Apple
for x in fruits: Banana
print(x) cherry
Looping in Python

for in loop: - # Iterating over a String

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

It returns a sequence of numbers from start to (end -1)


with inc or dec as specified.

By default start = 0 and inc = 1

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

for in loop: - Range Function


Output:
0
for x in range(4):
1
print(x) 2
3

Output:
for x in range(2, 6): 2
print(x) 3
4
5
Looping in Python

for in loop: - Else in for loop

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 in loop: - Nested loops


Example –
1
22
333
4444

for i in range(1, 5):


for j in range(i):
print(i,end=“ “)
print(“\n”)
Looping in Python

for in loop: - Prime number program

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

Program to swap the values of two variables without using


temporary variable.

x = 10
y=5

x=x+y
y=x-y
x=x-y

print("After Swapping: x =", x, " y =", y)


Program

Python program to calculate the sum of the digits in an integer.

n = int(input("Enter input: "))

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

With the continue statement we can stop the current iteration,


and continue with the next.

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

Python function to find average of 2 numbers

def avg_number(x, y):


print("Average of ",x," and ",y, " is ",(x+y)/2)

avg_number(3, 4)
Program

Python function to check whether x is even or odd

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

# check if the number is negative, positive or zero


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Recursion
In Python, a function can call other functions. It is even
possible for the function to call itself.

These type of construct are termed as recursive function.

Advantages of Recursion:

• Recursive functions make the code look clean and


elegant.
• A complex task can be broken down into simpler sub-
problems using recursion.
• Sequence generation is easier with recursion than using
some nested iteration.
Program
Write a program for find factorial of a given number using recursion.
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)

num = int(input("Enter a number: "))


if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of",num,"is",recur_factorial(num))
Program
def greet(name):
print("Hello, " + name + ". Good morning!")

greet(‘IT 5th sem’)

Note: In python, the function definition should always be present before


the function call. Otherwise, we will get an error.
greet('Paul’)

def greet(name):
print("Hello, " + name + ". Good morning!")

# Error: name 'greet' is not defined


Return statement
The return statement is used to exit a function and go back to the place
from where it was called.

Syntax of return -
return [expression_list]

This statement can contain an expression that gets evaluated and the
value is returned.

If there is no expression in the statement or the return statement itself is


not present inside a function, then the function will return the None
object.
Program
def absolute_value(num):

if num >= 0:
return num
else:
return -num

print(absolute_value(2))

print(absolute_value(-4))
Scope and Lifetime of Variables

Scope of a variable is the portion of a program where the


variable is recognized.

Parameters and variables defined inside a function are not


visible from outside the function. Hence, they have a local
scope.

The lifetime of a variable is the period throughout which the


variable exists in the memory. The lifetime of variables inside
a function is as long as the function executes.
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.

Global variables are available from within any scope, global


and local.

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.

The global keyword makes the variable global.

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

You might also like