0% found this document useful (0 votes)
11 views

UNIT-01 PYTHON BASICS

Python is a high-level, interpreted programming language created by Guido van Rossum in 1991, used for web development, software development, and data handling. It features various data types including numeric, string, list, tuple, dictionary, and set, and allows for variable assignment and manipulation without explicit declaration. Additionally, Python supports comments for code readability and includes built-in functions for data type conversion and sequence generation.

Uploaded by

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

UNIT-01 PYTHON BASICS

Python is a high-level, interpreted programming language created by Guido van Rossum in 1991, used for web development, software development, and data handling. It features various data types including numeric, string, list, tuple, dictionary, and set, and allows for variable assignment and manipulation without explicit declaration. Additionally, Python supports comments for code readability and includes built-in functions for data type conversion and sequence generation.

Uploaded by

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

PYTHON BASICS

UNIT-01
What is Python?
 Python is a very popular general-
purpose interpreted, interactive,
object-oriented, and high-level
programming language.
Python  It was created by Guido van Rossum,
Introduction and released in 1991.
 It is used for:
1. web development (server-side),
2. software development,
3. mathematics,
4. system scripting.
 Python can be used on a server to
create web applications.
 Python can be used alongside
software to create workflows.
What can  Python can connect to database
Python do? systems. It can also read and modify
files.
 Python can be used to handle big data
and perform complex mathematics.
 Python can be used for production-
ready software development.
 Comments can be used to explain Python
code.
 Comments can be used to make the code
more readable.
 Comments can be used to prevent execution
Python when testing code.
Comments Creating a Comment
 Comments starts with a #, and Python will ignore
them:
Example #This is a comment
print("Hello,
World!")

print("Hello, World!") #This is a


comment
 To add a multiline comment you could insert a # for
each line:

Example
#This is a comment
#written in
#more than just one
Multiline line
print("Hello, World!")
Comments Or, not quite as intended, you can use a multiline string.
Since Python will ignore string literals that are not assigned to
a variable, you can add a multiline string (triple quotes) in
your code, and place your comment inside it:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
 Variables are containers for storing data
values.

Creating Variables
Variables  Python has no command for declaring a
variable.
OR  A variable is created the moment you first
Names assign a value to it.
Examplex = 5
y = "John"
print(x)
print(y) OUTPUT :
5
John
Casting Get the Type
Variables do not
need to be  You can get the
 If you want to
declared with any data type of a
particular type, specify the data
variable with
and can even type of a variable,
the type() function.
change type after this can be done
with casting.  EXAMPLE
they have been x=5
set.
x=4 # x is of type int
EXAMPLE y = "John"
x = "Sally" # x is now of x = str(3) print(type(x
type str y = int(3) OUTPU )) OUTPUT
print(x) z = float(3) T print(type(y <class
print(x) 3 )) 'int'>
print(y) 3 <class
print(z) 3.0 'str'>
Single or Double Case-Sensitive
Quotes?
 String variables can
 Variable names are
be declared either
by using single or case-sensitive.
double quotes: Example

VARIABLES x = "John"
print(x)
 This will create two
variables:
#double quotes are a=4
the same as single A = "Sally"
quotes: #A will not overwrite
x = 'John' a
print(x) print(a)
print(A)
OUTPU
OUTPU
T John
T:
John
4
Sally
 A variable can have a short name (like x and y)
or a more descriptive name (age, carname,
total_volume).
Rules for Python variables:
 A variable name must start with a letter or the
Variable underscore character
Names  A variable name cannot start with a number
 A variable name can only contain alpha-numeric
characters and underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive (age, Age and
AGE are three different variables)
 A variable name cannot be any of the
Python keywords.
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John" OUTPUT
John
EXAMPLE myvar2 = "John"
John
print(myvar) John
print(my_var) John
print(_my_var) John
print(myVar) John
print(MYVAR)
print(myvar2)
 Python allows you to assign values to multiple
variables in one line:
Python x, y, z = "Orange", "Banana",
Variables "Cherry" OUTPUT:
Orange
- Assign print(x)
print(y)
Banana

Multiple print(z)
Cherry

Values
 And you can assign the same value to
multiple variables in one line:
x=y=z=
"Orange"
One Value OUTPUT:
Orange
to Multiple print(x)
print(y) Orange
Variables print(z) Orange
 If you have a collection of values in a list,
tuple etc. Python allows you to extract the
values into variables. This is
called unpacking
Unpack a fruits = ["apple", "banana",
Collection "cherry"]
OUTPUT:
x, y, z = fruits
apple
print(x) banana
print(y) cherry
print(z)
 The Python print() function is often
used to output variables.

x = "Python"
y = "is"
Output z = "awesome"
print(x, y, z)
Variables O/P: Python is awesome
Global Variables
 Variables that are created outside of a
function are known as global variables.
 Global variables can be used by everyone,
both inside of functions and outside.
Global
Variables x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()

O/P : Python is awesome


 A data type represents a kind of value and
determines what operations can be done on it.
Numeric, non-numeric and Boolean (true/false) data
are the most obvious data types. Python has various
built-in data types
Data Type Examples
Numeric int, float, complex

Data Type String str


Sequence list, tuple, range
bytes, bytearray,
Binary
memoryview
Mapping dict
Boolean bool
Set set, frozenset
None NoneType
 Python numeric data types store numeric values.
Number objects are created when you assign a value
var1 = 1 # int
to them. For example −
data type
var2 = True # bool data
type
Python var3 = 10.023 # float data
type
Numeric var4 = 10+3j # complex
Data Type data type
 Python supports four different numerical types and
each of them have built-in classes in Python library,
called int, bool, float and complex respectively −
• int (signed integers)
• bool (subtype of integers.)
• float (floating point real
values)
• complex (complex numbers)
Examples

int bool float complex


10 True 0.0 3.14j
0O777 False 15.20 45.j
-786 -21.9 9.322e-36j
080 32.3+e18 .876j
0x17 -90. -.6545+0J
-0x260 -32.54e100 3e+26J
0x69 70.2-E12 4.53e-7j
Python  Sequence is a collection data type.

Sequence  It is an ordered collection of items. Items in the


sequence have a positional index starting with 0.
Data Type  It is conceptually similar to an array in C or C++.
There are following three sequence data types
defined in Python.

1. String Data Type


2. List Data Type
3. Tuple Data Type
• Python string is a sequence of one or more Unicode
Python characters, enclosed in single, double or triple quotation
marks (also called inverted commas).
String Data • Python strings are immutable which means when you
perform an operation on strings, you always produce a
Type new string object of the same type, rather than
mutating an existing string.
• As long as the same sequence of characters is enclosed,
str = 'Hello World!‘
single or double or triple quotes don't matter.
OUTPUT:
print (str) # Prints complete string
Hello World! print (str[0]) # Prints first character of
H the string
llo print (str[2:5]) # Prints characters starting
llo World! from 3rd to 5th
Hello World!Hello print (str[2:]) # Prints string starting
World! from 3rd character
Hello World!TEST print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string
Python  Python string is a sequence of one or more Unicode characters,
enclosed in single, double or triple quotation marks (also called
String inverted commas).
 Python strings are immutable which means when you perform an
Data operation on strings, you always produce a new string object of
the same type, rather than mutating an existing string.
Type  As long as the same sequence of characters is enclosed, single
tr or doubleWorld!'
= 'Hello or triple quotes don't matter.
print (str) # Prints complete string
print (str[0]) # Prints first character of the
string
print (str[2:5]) # Prints characters starting from
3rd to 5th
print (str[2:]) # Prints string starting from 3rd
character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string
 Python Lists are the most versatile compound data types.
 A Python list contains items separated by commas and enclosed
within square brackets ([]).
 To some extent, Python lists are similar to arrays in C.
 One difference between them is that all the items belonging to a
Python list can be of different data type where as C array can store
Python List elements related to a particular data type.

Data Type [2023, "Python", 3.11, 5+6j, 1.23E-4]

 As mentioned, an item in the list may be of any data


type. It means that a list object can also be an item in
another list. In that case, it becomes a nested list.
[['One', 'Two', 'Three'], [1,2,3], [1.0, 2.0,
3.0]]

A list can have items which are simple numbers,


strings, tuple, dictionary, set or object of user
defined class also.
 Python tuple is another sequence data type that is
similar to a list. A Python tuple consists of a number
of values separated by commas.
 Unlike lists, however, tuples are enclosed within
parentheses (...).

Python  A tuple is also a sequence, hence each item in the


tuple has an index referring to its position in the
Tuple Data collection.
 The index starts from 0.
Type (2023, "Python", 3.11, 5+6j, 1.23E-4)

 In Python, a tuple is an object of tuple class. We can


check it with the type() function.
type((2023, "Python", 3.11, 5+6j, 1.23E-4))
<class 'tuple'>
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')

print (tuple) # Prints the complete tuple


print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements of the tuple starting
from 2nd till 3rd
print (tuple[2:]) # Prints elements of the tuple starting from
Example 3rd element
print (tinytuple * 2) # Prints the contents of the tuple twice
(tuple) print (tuple + tinytuple) # Prints concatenated tuples

Output:
('abcd', 786, 2.23, 'john', 70.2)
abcd
(786, 2.23)
(2.23, 'john', 70.2)
(123, 'john', 123, 'john')
('abcd', 786, 2.23, 'john', 70.2,
123, 'john')
 Python range() is an in-built function in Python which returns a
sequence of numbers starting from 0 and increments to 1 until it
reaches a specified number.

Python  We use range() function with for and while loop to generate a
sequence of numbers.
range(start, Following
stop, step) is the syntax of the function:
Ranges
Function
 Here is the description of the parameters used:
1. start: Integer number to specify starting position, (Its optional,
Default: 0)
2. stop: An integer number specifying at which position to stop(Its
mandatory)
3. step: Integer number to specify increment, (Its optional, Default: 1)
for i in range(5): for i in range(1, 5):
print(i) print(i)

0 1
1 2
2 3
4
Examples 3
4
 Python dictionaries are kind of hash table type.A dictionary
key can be almost any Python type, but are usually numbers
or strings.
 Python dictionary is like associative arrays or hashes found in
Python Perl and consist of key:value pairs.
 The pairs are separated by comma and put inside curly
Dictionary brackets {}. To establish mapping between key and value,
Data Type the semicolon':' symbol is put between the two.
 Dictionaries are enclosed by curly braces ({ }) and values
dict = {}
can be assigned and accessed using square braces ([]). For
dict['one'] = "This is one"
example −
dict[2] = "This is two"

tinydict = {'name': 'john','code':6734, Output:


'dept': 'sales'} This is one
This is two
print (dict['one']) # Prints value for {'dept': 'sales', 'code': 6734, 'name':
'one' key 'john'}
print (dict[2]) # Prints value for 2 key ['name‘, 'code', 'dept']
print (tinydict) # Prints complete ['sales', 6734, 'john']
dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the
 Set is a Python implementation of set as defined in
Mathematics. A set in Python is a collection, but is not an
indexed or ordered collection as string, list or tuple.
 An object cannot appear more than once in a set, whereas in
List and Tuple, same object can appear more than once.
 Comma separated items in a set are put inside curly
brackets or braces {}. Items in the set collection can be of
different data types.
{2023, "Python", 3.11, 5+6j,
1.23E-4}
Python Set Data {(5+6j), 3.11, 0.000123,
Type 'Python', 2023}

 A set can store only immutable objects such as number


(int, float, complex or bool), string or tuple. If you try to put
a list or a dictionary in the set collection, Python raises
a TypeError.
 Hashing is a mechanism in computer science which enables
quicker searching of objects in computer's memory. Only
immutable objects are hashable.
# Returns false as a is not equal
 Python boolean type
to b
is one of built-in data a=2
types which b=4
represents one of the print(bool(a==b))
two values # Following also prints the same
either True or False. print(a==b)
Python bool() functio
n allows you to # Returns False as a is None
Python evaluate the value of
any expression and
a = None
print(bool(a))
Boolean returns either True or
False based on the
Data Types expression.
# Returns false as a is an empty
sequence
Output : a = ()
False print(bool(a))
False
False # Returns false as a is 0
False a = 0.0
False print(bool(a))
True
# Returns false as a is 10
a = 10
print(bool(a))
 Python and other programming languages provide
different type of operators which are symbols
(sometimes called keywords) and used to perform a
certain most commonly required operations on one or
more operands.
What are  Operators allow different operations like addition,
subtraction, multiplication, division etc.
Operators in Types of Operators in Python
Python? 1) Arithmetic Operators
2) Comparison (Relational) Operators
3) Assignment Operators
4) Logical Operators
5) Bitwise Operators
6) Membership Operators
7) Identity Operators
 Arithmetic operators are used to perform basic
mathematical operations. Assume variable a holds 10
and variable b holds 20, then

Python
Arithmetic
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
Python
Comparison
Operators
 Assignment operators are used to assign values to
variables. Following is a table which shows all Python
assignment operators.

Python
Assignment
Operators
 Bitwise operator works on bits and performs bit by bit
operation. These operators are used to compare
binary numbers.

Python
Bitwise
Operators
 Python logical operators are used to combile two or
more conditions and check the final result.

Python
Logical
Operators
 Python's membership operators test for membership
in a sequence, such as strings, lists, or tuples. −

Python
Membership
Operators
 Identity operators compare the memory locations of
two objects.

Python
Identity
Operators
Sr.N Operator & Description
o.
1 **
Exponentiation (raise to the power)
2 ~+-
Complement, unary plus and minus (method names for the last two
are +@ and -@)
3 * / % //

Python 4
Multiply, divide, modulo and floor division
+-
Addition and subtraction
Operators 5 >> <<
Right and left bitwise shift
Precedence 6 &
Bitwise 'AND'
7 ^|
Bitwise exclusive `OR' and regular `OR'
8 <= < > >=
Comparison operators
9 <> == !=
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
11 is is not
Identity operators
12 in not in
Membership operators
13 not or and
Logical operators
# Program for Fahrenheit to Celsius Conversion
in Python

def fahrenheit_to_celsius(fahrenheit):
celsius = (fahrenheit - 32) * 5/9
Program for return celsius

Fahrenheit # Example usage


to Celsius fahrenheit = 100

Conversion # Convert Fahrenheit to Celsius using the


function
celsius = fahrenheit_to_celsius(fahrenheit)

# Print the converted temperature in Celsius


print(f"{fahrenheit} degrees Fahrenheit is equal to
{celsius} degrees Celsius.")
OUTPUT : 100 degrees Fahrenheit is
equal to 37.77777777777778
degrees Celsius.
 Input functions (input()) allow users of a program
to place values into programming code.
 The parameter for an input function is called a
prompt. This is a string (this can be indicated by
“” or ‘’) such as “Enter a number: “
 The user’s response to the prompt will be
returned to the input statement call as a string. To
Input/ use this value as any other data type, it must be
converted with another function (int()).
Output  Print functions (print()) allow programs to output
strings to users on a given interface.
 The parameter of this function is of any type. All
types will automatically be converted to strings.
xString = input(“Enter a number:
“)
x = int(xString)
y=x+2
print(y)
 A Python 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
Python - reusing.

Functions  A top-to-down approach towards


building the processing logic
involves defining blocks of
independent reusable functions.
 A Python function may be
invoked from any other function
by passing required data
(called parameters or argumen
ts). The called function returns
its result back to the calling
environment.
Types of
Python
Functions
 Python provides the following types of
functions −
1. Built-in functions
2. Functions defined in built-in modules
3. User-defined functions
• Function blocks begin with the
keyword def followed by the function name and
parentheses ( ( ) ).
• Any input parameters or arguments should be

Defining a placed within these parentheses. You can also


define parameters inside these parentheses.
Function in • The first statement of a function can be an optional
statement; the documentation string of the function
Python or docstring.
• 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.
Syntax: Example:

def def greetings():


functionname( parame "This is docstring of greetings
ters ): function"
"function_docstring" print ("Hello World")
function_suite return
return [expression]
greetings()
 Defining a function only gives it a name, specifies the
parameters that are to be included in the function
and structures the blocks of code.
 Once the basic structure of a function is finalized, you
can execute it by calling it from another function or
directly from the Python prompt.
Calling a
# Function definition is here
Function in def printme( str ):

Python "This prints a passed string into this


function"
print (str)
return;

# Now you can call printme function


printme("I'm first call to user defined
function!")
printme("Again second call to the same
function")
 The function calling
mechanism of Python
differs from that of C and
C++.
 There are two main
function calling
mechanisms: Call by
Value and Call by
Pass by Reference.
Reference  When a variable is
vs Value passed to a function,
what does the function do
to it? If any changes to its
variable does not get
reflected in the actual
argument, then it uses
call by value mechanism.
 On the other hand, if the
change is reflected, then
it becomes call by
 Python uses pass by reference mechanism. As
variable in Python is a label or reference to the object
in the memory, the both the variables used as actual
argument as well as formal arguments really refer to
Python the same object in the memory.
 We can verify this fact by checking the id() of the
uses pass passed variable before and after passing.
def testfunction(arg):
by print ("ID inside the function:",
id(arg))
reference
mechanis var="Hello"
print ("ID before passing:",
m id(var))
testfunction(var)

ID before passing: 1996838294128


ID inside the function: 1996838294128
• The process of a function often depends
on certain data provided to it while calling
it. While defining a function, you must
give a list of variables in which the data
passed to it is collected.
• The variables in the parentheses are
called formal arguments.
Function • When the function is called, value to each
Arguments of the formal arguments must be
provided. Those are called actual
arguments.
 Let's modify greetings function and have name an
argument.
 A string passed to the function as actual argument
becomes name variable inside the function.
def greetings(name):
"This is docstring of greetings
function"
Function print ("Hello {}".format(name))
return
Arguments
Example greetings("Samay")
greetings("Pratima")
greetings("Steven")

Hello Samay
Hello
Pratima
Hello Steven
 Python also accepts function recursion, which means
a defined function can call itself.
 Recursion is a common mathematical and
programming concept. It means that a function calls
itself. This has the benefit of meaning that you can
loop through data to reach a result.

Python  The developer should be very careful with recursion


as it can be quite easy to slip into writing a function
Function which never terminates, or one that uses excess
amounts of memory or processor power. However,
Recursion when written correctly recursion can be a very
efficient and mathematically-elegant approach to
programming.
 In this example, tri_recursion() is a function that we
have defined to call itself ("recurse"). We use
the k variable as the data, which decrements (-1)
every time we recurse. The recursion ends when the
condition is not greater than 0 (i.e. when it is 0).
# Program to print the fibonacci series upto
n_terms

# Recursive function
def recursive_fibonacci(n):
if n <= 1: Fibonacci
return n series:
else: 0
Example for return(recursive_fibonacci(n-1) +
recursive_fibonacci(n-2))
1
1
Recursion 2
3
n_terms = 10
5
# check if the number of terms is valid 8
if n_terms <= 0: 13
print("Invalid input ! Please input a positive value") 21
else: 34
print("Fibonacci series:")
for i in range(n_terms):
print(recursive_fibonacci(i))
 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.
 The concept of module in Python further enhances the
modularity. You can define more than one related functions
Python - together and load required functions.
Modules  A module is a file containing definition of functions,
classes, variables, constants or any other Python object.
 Contents of this file can be made available to any other
program. Python has the import keyword for this purpose.
import math
print ("Square root of 100:",
math.sqrt(100))
Sr.N Name & Brief Description
o.
1 os
This module provides a unified interface to a number of operating system
functions.
2 string
This module contains a number of functions for string processing
3 re
This module provides a set of powerful regular expression facilities. Regular
expression (RegEx), allows powerful string search and matching for a pattern in a

Built in 4
string
math

Modules This module implements a number of mathematical operations for floating point
numbers. These functions are generally thin wrappers around the platform C
library functions.
5 cmath
This module contains a number of mathematical operations for complex numbers.
6 datetime
This module provides functions to deal with dates and the time within a day. It
wraps the C runtime library.
7 gc
This module provides an interface to the built-in garbage collector.
8 asyncio
This module defines functionality required for asynchronous processing
9 Collections
This module provides advanced Container datatypes.
10 Functools
11 operator
Functions corresponding to the standard operators.
12 pickle
Convert Python objects to streams of bytes and back.
13 socket
Low-level networking interface.
14 sqlite3
A DB-API 2.0 implementation using SQLite 3.x.
15 statistics
Mathematical statistics functions
16 typing
Support for type hints
17 venv
Creation of virtual environments.
18 json
Encode and decode the JSON format.
19 wsgiref
WSGI Utilities and Reference Implementation.
20 unittest
Unit testing framework for Python.
21 random
Generate pseudo-random numbers
 Any text file with .py extension and containing Python
code is basically a module.
 It can contain definitions of one or more functions,
variables, constants as well as classes.
User  Any Python object from a module can be made
available to interpreter session or another Python
Defined script by import statement. A module can also include
runnable code.
Modules
 Creating a module is nothing but saving a Python
code with the help of any editor. Let us save the
following code as mymodule.py

def SayHello(name):
print ("Hi {}! How are
you?".format(name))
Create a return

Module  You can now import mymodule in the current Python


terminal.
>>> import mymodule
>>> mymodule.SayHello("Harish")
Hi Harish! How are you?
 In Python, the import keyword has been provided to
load a Python object from one module.
 The object may be a function, class, a variable etc. If
a module contains multiple definitions, all of them will
be loaded in the namespace.

The import  Let us save the following code having three functions
as mymodule.py.
Statement def sum(x,y):
return x+y The import
mymodule statement loads
def all the functions in this
average(x,y): module in the current
return namespace. Each function in
(x+y)/2 the imported module is an
attribute of this module
def object.
power(x,y):
return x**y
 Dot notation is a syntax used in programming
languages like Python to access an object’s attributes
and methods, making it easier to search complex
data structures.
 When we use dot notation in Python, we usually write
[object we want to access][dot][attribute or method].

Dot  We replace the items in the square brackets with


what object, attribute and method we actually want
Notation access to.
 Python has certain built-in string methods
like .upper(), which turns a string into its upper-case
version, and .replace(), which replaces letters and
words in a string.
 We can use dot notation to access the built-in string
DOT methods.
NOTATION my_string = "Hello, World!"
IN print(my_string.upper()) # this prints "HELLO, WORLD!"
print(my_string.replace("Hello", "Goodbye")) # this prints prints
STRINGS "Goodbye, World!"
 Python also has built-in list methods like .append(),
which adds to the list, and .sort(), which sorts a list in
ascending order. We can use dot notation to access
built-in list methods.
DOT
NOTATION my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
my_list.append(7) # this appends the number 7 to
IN LISTS my_list
my_list.sort() # this sorts my list
print(my_list) # this line prints [1, 1, 2, 3, 3, 4, 5, 5, 6,
7, 9]
 We can use dot notation to access the properties of
datetime objects. Suppose I want to know the current
year and month. Here’s a piece of code I could write:
DOT
NOTATION
IN import datetime

DATETIME now = datetime.datetime.now() # apply


now() to get current datetime
OBJECTS print(now.year) # this prints the current
year
print(now.month) # this prints the current
month
CONDITIONAL CONSTRUCT – if else
STATEMENT

Conditional constructs (also


known as if statements) provide a
way to execute a chosen block of
code based on the run-time
evaluation of one or more Boolean
expressions. In Python, the most
general form of a conditional is
written as follows:
CONDITIONAL CONSTRUCT – if else
STATEMENT

: Colon
Must
if first condition:
first body
elif second condition:
second body
elif third condition:
third body
else:
fourth body
CONDITIONAL CONSTRUCT – if else
STATEMENT

FLOW CHART

False
Condition ? Statement 1 Statement 2

Main True
Body
Statement 1

else
Statement 2 body
CONDITIONAL CONSTRUCT – if else
STATEMENT

Each condition is a Boolean


expression, and each body contains
one or more commands that are to
be executed conditionally.

If the first condition succeeds, the


first body will be executed; no other
conditions or bodies are evaluated
in that case.
CONDITIONAL CONSTRUCT – if else
STATEMENT

If the first condition fails, then the


process continues in similar manner
with the evaluation of the second
condition. The execution of this
overall construct will cause
precisely one of the bodies to be
executed.

There may be any number of elif


clauses (including zero), and
 The final else clause is optional.
EXAMPLES – if STATEMENT

else is
missing, it
is an
optional
statement

OUT
PUT
CONDITIONAL CONSTRUCT

EXAMPLE – if else STATEMENT


EXAMPLE – if else STATEMENT

: Colon
Must

else is
used

OUT
PUT
EXAMPLES – if elif STATEMENT

READ AS
18 is less
than age
and
18 is less
than 60

OUTPU
T
3. ITERATION OR LOOPING

What is loop or iteration?


Loops can execute a block of code
number of times until a certain
condition is met.
OR
The iteration statement allows
instructions to be executed until a
certain condition is to be fulfilled.
The iteration statements are also
called as loops or Looping statements.
3. ITERATION OR LOOPING

Python provides two


kinds of loops & they are,

while loop

for loop
while loop

A while loop allows general


repetition based upon the repeated
testing of a Boolean condition
The syntax for a while loop in
Python is as follows:
: Colon
while condition:
Must
body
Where, loop body contain the
single statement or set of
statements (compound statement)
or an empty statement.
while loop

The loop iterates while the


expression evaluates to true, when
expression becomes false the loop
terminates.

FLOW
CHART

while
loop
while loop - programs
# Natural Numbers generation

OUTPUT
while loop - programs
# Calculating Sum of Natural
Numbers

OUTPUT
for LOOP

Python’s for-loop syntax is a


more convenient alternative to a
while loop when iterating through
a series of elements. The for-loop
syntax can be used on any type of
iterable structure, such as a list,
tuple str, set, dict, or file
Syntax or general format of for
loop is,

for element in iterable:


for LOOP

Till the list


exhaust for
loop will
continue to
execute.

OUTPU
T
for LOOP

range KEYWORD
for LOOP - range
KEYWORD
The range() function returns
a sequence of numbers, starting
from 0 by default, and
increments by 1 (by default),
and ends at a specified number.

range(start, stop, step)


x
for n in range(3 O
= range(3,
,6):
print(n)
R 6)
for n in x:
print(n)
for LOOP - range KEYWORD
#Generating series of
numbers

OUTPU
T
for LOOP - range KEYWORD

#Generating even numbers

OUTPU
T
for LOOP - range KEYWORD
# print string character by
character

OUTP
UT
else statement in loop

else can be used in for and


while loops the else body will be
executed as and when the loop’s
conditional expression evaluates to
false OUTPUT
4. BRANCHING OR JUMPING
STATEMENTS

Python has an unconditional


branching statements and they
are,
1. break STATEMENT

2. continue STATEMENT
4. BRANCHING OR JUMPING
STATEMENTS

1. break STATEMENT

Break can be used to


unconditionally jump out of the
loop. It terminates the execution
of the loop. Break can be used in
while loop and for loop. Break is
mostly required, when because of
some external condition, we need
to exit from a loop.
1. break STATEMENT

Loop
Condition ? break
causes
jump
True

Statement 1

break
1. break STATEMENT

OUT
PUT
2. continue STATEMENT

The continue statement in


Python returns the control to
the beginning of the while
loop. The continue
statement rejects all the
remaining statements in the
current iteration of the loop
and moves the control back to
the top of the loop.
The continue statement can be
2. continue STATEMENT

Loop False
Condition ?

True
Statement 1

Statements
ignored or continue
skipped
continue
Statement n
causes
jump
2. continue STATEMENT

when i value becomes 2 the print


statement gets skipped, continue
statement goes for next iteration, hence
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.
The pass statement is
a null operation; nothing happens
when it executes.
The pass is also useful in places
where your code will eventually go,
but has not been written yet (e.g.,
in stubs for example):
pass STATEMENT

pass in loop
pass in has no
loop output
BREAK CONTINUE
It terminates the It terminates only the
execution of current iteration of
remaining iteration the loop.
Differen of the loop.
ce 'break' resumes the 'continue' resumes
control of the the control of the
Between program to the end program to the next
break of loop enclosing iteration of that loop
and that 'break'. enclosing 'continue'.
It causes early It causes early
continue termination of loop. execution of the next
iteration.
'break' stops the 'continue' do not
continuation of stops the continuation
What is namespace:
 A namespace is a system that has a unique name for each
and every object in Python.
 An object might be a variable or a method. Python itself
Namespac maintains a namespace in the form of a Python dictionary.
 Let’s go through an example, a directory-file system
es and structure in computers. Needless to say, that one can
have multiple directories having a file with the same
Scope in name inside every directory.
Python  But one can get directed to the file, one wishes, just by
specifying the absolute path to the file.
 Real-time example, the role of a namespace is like a
surname. One might not find a single “Alice” in the class
there might be multiple “Alice” but when you particularly
ask for “Alice Lee” or “Alice Clark” (with a surname), there
will be only one (time being don’t think of both first name
and surname are same for multiple students).
 When Python interpreter runs solely without any user-
defined modules, methods, classes, etc. Some functions
like print(), id() are always present, these are built-in
namespaces.
 When a user creates a module, a global namespace gets
created, later the creation of local functions creates the
local namespace.
 The built-innamespace encompasses the global
namespace and the global namespace encompasses
the local namespace.
Types of
# var1 is in the global
namespaces : namespace
var1 = 5

def some_func():
# var2 is in the local namespace
 var2 = 6
def some_inner_func():
# var3 is in the nested local
# namespace
var3 = 7
 Raise an exception
 As a Python developer you can choose to throw an
exception if a condition occurs.

Python Rais  To throw (or raise) an exception, use the raise


keyword.
e an x = -1
Exception if x < 0:
raise Exception("Sorry, no numbers
below zero")

 The raise keyword is used to raise an exception.

You might also like