Python_UNIT 1
Python_UNIT 1
CS1001-2
Course Outcomes:
At the end of the course student will be able to
1. Understand and experiment with the basics of python programming like data types and looping.
3. Apply the Python operations for manipulating strings, lists, tuples and dictionaries.
• Python is simple and so easy to learn Python is versatile and can be used
to create many different things.
• High Level Language: Python don‟t let you worry about low-level details, like
memory management, hardware-level operations etc.
• You can make the changes in code without restarting the program.
a) Demonstrate about Basics of Python Programming.
• It has a Python shell window, which gives you access to the Python
interactive mode.
• Goto File menu click on New File (CTRL+N) and write
the code and save add.py
iii. Running Python scripts in Command Prompt:
• Open your text editor, type the following text and save it as hello.py.
print "hello"
• Make sure you change to the directory where you saved the file
before doing it.
Python Identifier
• Python Identifier is the name we give to identify a
variable, function, class, module or other object.
• That means you can‟t use them as name of any entities like variables, classes and
functions.
• In fact a variable is a memory location where a value can be stored. Later we can retrieve the value to use.
• During the execution, the type of a variable is inferred from the context in which it is being used. Hence
Python is called dynamically-typed language.
• Simple variable assignment
x=4 # x is of type int
x = “nitte" # x is now of type str
print(x)
1. Identifiers can be combination of uppercase and lowercase letters, digits or an underscore (_).
So myVariable, variable_1, variable_for_print all are valid python identifiers.
2. An Identifier can not start with digit. So, while variable1 is valid, 1variable is not valid.
print(x)
print(y)
print(z)
Python Data Types
• Variables can store data of different types, and different types can do different things.
• Python has the following data types built-in by default, in these categories:
Numeric Types Text Type Boolean Type Binary Types Mapping Type Sequence Type class
float tuple
complex range
• int can be expressed in binary, decimal, octal, hexadecimal.
Integer type Starts with Example
decimal 0-9 156
binary 0b/0B 0b101
octal 0o/0O 0o432
hexadecimal 0x/0X 0x443
• input() built-in function can be used to retrieve input values from keyboard.
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
1.Arithmetic operators
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponent x ** y
// Floor division x // y
Operation Nuances
• On performing floor division, a//b, result is largest integer which is less than or equal to the
quotient.
2. Comparison Operators
• These are used to compare two operands. For example, compare the ages of two persons, compare
the prices of two or more items, etc.
== Equal x == y
!= Not equal x != y
Identity operators are used to compare the objects, not if they are equal, but if they are actually the
same object, with the same memory location:
• print(x == y) # to demonstrate the difference between "is" and "==": this comparison
returns True because x is equal to y
5.Membership operators
<< left shift Shift left by pushing zeros in from the right and let the
leftmost bits fall off
>> right shift Shift right by pushing copies of the leftmost bit in from the
left, and let the rightmost bits fall off
• Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 .
Take Bitwise and of both X & y
• Note: Here, (111)2 represent binary number.
Take two bit values X and Y, where X = 5= (101)2 . Take Bitwise NOT of
X.
• Example 1:
a = 5 = 0000 0101 (Binary)
a << 1 = 0000 1010 = 10
a << 2 = 0001 0100 = 20
Example 2:
b = -10 = 1111 0110 (Binary)
b << 1 = 1110 1100 = -20
b << 2 = 1101 1000 = -40
Example 1:
a = 10 = 0000 1010 (Binary)
a >> 1 = 0000 0101 = 5
Example 2:
a = -10 = 1111 0110 (Binary)
a >> 1 = 1111 1011 = -5
7.Assignment operators
• Assignment operators are used to assign values to variables
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
Precedence and Associativity
• Precedence(priority)-multiple operators in an expression
• c=a*b/c
• Same precedence
• * is done before / (arithmetic operators have Left to right
associativity )
Type Conversions
• Mixed mode operations:
• Operation between int and float will yield float.
• Operation between int and complex will yield complex.
• Operation between float and complex will yield complex.
• float() - constructs a float number from an integer literal, a float literal or a string
literal (providing #the string
x will represents a float or an integer)
be 1.0
# y will be 2.8
• x = float(1)
# z will be 3.0
y = float(2.8)
# w will be 4.2
z = float("3")
w = float("4.2")
• str() - constructs a string from a wide variety of data types, including strings,
integer literals and float literals
a = 30
b = 100
if b > a:
print("b is greater than a")
print(“program ends here..”)
The if-else statement
The if-else statement is similar to if statement except the fact that, it also
provides the block of the code for the false case of the condition to be
checked. If the condition provided in the if statement is false, then the else
statement will be executed.
Syntax:
if condition:
statement1
statement2
else:
statement3
statement4
Example:
a = 30
b = 100
if b > a:
print("b is greater than a")
else:
print("b is greater than a")
• During each iteration var is assigned the next value from the list.
• In place of a list, a string, a tuple, set or dictionary can also be used.
• else block is optional.
• If present,it is executed if loop is not terminated abruptly using break.
x = ‘nmamit’
for i in x:
print(i)
output: ??
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Output:
apple
banana
cherry
Usage of for loop
• A for loop can be used in the following two situations:
• Repeat a set of statements a finite number of times.
• Iterate through a string, list, tuple, set or dictionary.
• Output:
• for can be used to iterate through a string, list, tuple, set or
dictionary as shown below:
break statement
The break Statement
The break statement in Python is used to exit or “break” out of a loop (either a
for or while loop) prematurely before the loop has iterated through all its items or
reached its condition.
Example:
x = ‘nmamit’
for i in x:
if i==‘i’:
break
print(i)
Output:
Working of break statement
The continue Statement
With the continue statement we can stop the current iteration of the loop, and
continue with the next.
Python continue statement is used to skip the execution of the program block
and returns the control to the beginning of the current loop to start the next
iteration.
x = ‘nmamit’
for i in x:
if i==‘i’:
continue
print(i)
Output:
Working of continue statement:
Using else Statement with for Loop
• A loop expression and an else expression can be connected in Python.
• After the circuit has finished iterating over the list, the else clause is
combined with a for Loop.
Example:
for x in range(6):
if x == 3:
break
print(x)
else:
print("finished!")
while loop
A while loop in Python is a control flow statement used
to repeat a block of code as long as a specified
condition is True. It's especially useful when the
number of iterations isn't known beforehand but
depends on some dynamic condition.
Syntax:
while expression:
statement(s)
Output:
The string “This will run forever!” will be printed infinite times.
Syntax:
• Usage of break with for loop
i=0 i=0
while i < 4: while i < 4:
i += 1 i += 1
print(i) print(i)
else: # Executed because break
no break in for else: # Not executed as
print("No Break\n") there is a break
print("No Break")
pass statement
Syntax:
pass
What is pass statement in Python?
When the user does not know what code to write, So user
simply places a pass at that line. Sometimes, the pass is used
when the user doesn‟t want any code to execute. So users can
simply place a pass where empty code is not allowed, like in
loops, function definitions, class definitions, or in if statements.
So using a pass statement user avoids this error.
Using pass With Conditional Statement
Using pass With Conditional Statement
Using pass With Looping Statement
Using pass With Looping Statement (while)
FUNCTIONS:
❖ Functions are used to avoid rewriting same code again and again in a
program.
i) Built in function
❖ Built in functions are the functions that are already created and
stored in python.
These built in functions are always available for usage and accessed
by a programmer. It cannot be modified.
ii)User Defined Functions:
❖ User defined functions are the functions that programmers
create for their requirement and use.
❖ These functions can then be combined to form module which
can be used in other programs by importing them.
• Example:
def my_add(a,b):
c=a+b
return c
Function Calling:
⮚ Once we have defined a function, we can call it from
another
function, program or even the Python prompt.
⮚ To call a function we simply type the function name
with
appropriate arguments.
• Example:
x=5
y=4
my_add(x,y)
Flow of Execution:
❖ The order in which statements are executed is called the flow of
execution
❖ Execution always begins at the first statement of the program
❖ Statements are executed one at a time, in order, from top to
bottom.
❖ Function definitions do not alter the flow of execution of the
program, but remember that statements inside the function are not
executed until the function is called.
❖ Function calls are like a bypass in the flow of execution. Instead
of going to the next statement, the flow jumps to the first line of
the called function, executes all the statements there, and then
comes back to pick up where it left off.
Note: When you read a program, don’t read from top to
bottom. Instead, follow the flow of execution. This means
that you will read the def statements as you are scanning
from top to bottom, but you should skip the statements of
the function definition until you reach a point where that
function is called.
Parameters And Arguments:
Parameters(Formal Parameters):
∙ If there is more than one value required, all of them will be listed in
parameter list separated by comma.
∙ Example: my_add(x,y)
RETURN STATEMENT:
• The return statement is used to exit a function and go back to
the place from where it was called.
• If the return statement has no arguments, then it will not return
any values. But exits from function.
• Syntax:
return[expression]
• Example:
def my_add(a,b):
c=a+b
return c
x=5
y=4
print(my_add(x,y))
• Output:
9
The pass Statement
The pass statement serves as a placeholder for future
code, preventing errors from empty code blocks.
def function():
pass # this will execute without any action
or error
function()
ARGUMENTS TYPES:
1. Required Arguments
2. Keyword(named) Arguments
3. Default Arguments
• Output:
Name: george
Age 56
3. Default Arguments:
• Assumes a default value if a value is not provided in the function
call for that argument.
def my_details( name, age=40 ):
print("Name: ", name)
print("Age ", age)
return
my_details(name="george")
• Output:
Name: george
Age 40
4. Variable length Arguments
• If we want to specify more arguments than specified while
defining the function, variable length arguments are used.
• It is denoted by * symbol before parameter.
def my_details(*name ):
print(*name)
my_details("rajan","rahul","micheal",ärjun")
• Output:
rajan rahul micheal ärjun
Positional-Only Arguments
• You can specify that a function can have ONLY positional arguments,
or ONLY keyword arguments.
Example
//error
def my_function(x, /):
print(x)
my_function(x = 3)
Recursive Function
A Python function can be called from within its body. When we do so it is
called a recursive function.
• Variables created in a function die when control returns from a function.
• Recursive functions are inherently slow since passing value(s) and control to
a function and returning value(s) and control will slow down the execution of
the function.
•x= lambda a : a + 10
print(x(5))
• def myfun(n):
return lambda a : a * n
• def myfun(n):
return lambda a : a * n
mydoubler = myfun(2)
print(mydoubler(11))
• MODULES:
⮚ A module is a file containing Python definitions, functions, statements
and instructions.
⮚ Standard library of Python is extended as modules.
⮚ To use these modules in a program, programmer needs to import
the module.
⮚ Once we import a module, we can reference or use to any of its functions or
variables in our code.
o There is large number of standard modules also available in python.
o Standard modules can be imported the same way as we import our user-
defined modules.
o Every module contains many function.
o To access one of the function , you have to specify the name of the module and
the name of the function separated by dot . This format is called dot notation.
• Syntax:
import module_name
module_name.function_name(variable)