Python Lab (1)
Python Lab (1)
Programming
Lab
CONTENTS
Input and
Introduction to Libraries in
Operators Output Files
Python Python
Statements
Assigning
Applications of Control
values to Functions
Python Structures
Variables
Math &
IDEs Built-in Types Random Dictionary
Modules
Introduction to
Python Variables List Set
Interpreter
Indentation
Keywords Tuple Strings
and Comments
Python – Why?
• Simple syntax
• Programs are clear and easy to read
• Has powerful programming features
• Companies and organizations that use Python include
YouTube, Google, Yahoo, and NASA.
• Python is well supported and freely available at
www.python.org.
Python – Why?
• Guido van Rossum –
Creator
• Released in the early
1990s.
• Its name comes from a
1970s British comedy
sketch television show
called Monty Python’s
Flying Circus.
INDENTATION
COMMENTS
KEYWORDS
VARIABLES
keywords
In programming languages like C, C++, and Java, you will need to declare the
type of variables but in Python you don’t need to do that. Just type in the
variable and when values will be given to it, then it will automatically know
whether the value given would be an int, float, or char or even a String.
num= 3
print(num)
num2 = 4.5
print(num2)
name="helloworld"
print(name)
Example:
a = 50
b=a
print(id(a))
print(id(b))
# Reassigned variable a
a = 500
print(id(a))
not Reverse the result, returns False not(x < 5 and x < 10)
if the result is true
Python Bitwise Operators
# Bitwise operators are used to compare (binary) numbers:
>> Signed right Shift right by pushing copies of the leftmost bit in from the left, and let
shift the rightmost bits fall off
BITWISE OPERATORS:
Decimal to Binary (0,1)
--- > is
• if-elif-else ladder
Control structures : Flow of control
Sequential Line by line Execution
Conditional Set of statements based on condition (True/False)
Loops/ Iterative Block of statements executed repeatedly base on condition (True/False)
Jumping Control jumps from the loop i.e BLOCK with keywords break ,continue ,pass
Conditional :
1. Simple if:
if (cond):
block of statements executed if condition is TRUE
2. if-else block:
if (cond):
block of statements executed if condition is TRUE
else :
block of statements executed if condition is FALSE
3. Nested if :
if (condition1):
# Executes when condition1 is true
If (condition2):
# Executes when condition2 is true
#if Block is end here
# if Block is end here
4. Nested if-else :
if (cond):
block of statements executed if condition is TRUE
elif (cond):
block of statements executed if condition is TRUE
else:
block of statements executed if condition is FALSE
EXAMPLE: # python program to illustrate nested If statement
i = 10
# python program to illustrate If if (i == 10):
statement if (i < 15):
i = 200
if (i > 100): print("i is smaller than 15")
print("100 is less than 200") if (i < 12):
print("I am OUT OF if")
print("i is smaller than 12 too")
else:
print("i is greater than 15")
EXAMPLE:
# python program to illustrate If-else # python program to illustrate if-elif-else ladder
statement # max of 3 numbers
a=10 a,b,c=1,2,3
b=20 if(a >= b) and (a >= c):
if (a < b): big = a
print("a is smaller than b") elif b >= a and b >= c:
else: big = b
print(“b greater than a") else:
big = c
print("I AM OUT OF IF - ELSE BLOCK")
print("largest is " ,big)
LOOPS:
While Loop:
Python While Loop:
While Loop is used to execute a block of statements
repeatedly until a given condition is satisfied.
i.e,conditional_expression, is true.
And when the condition becomes false, control comes out the
loop . i.e out of the block
print("***********************************")
i=1
while (i<=10):
print(i)
i=i+1
print("***********************************")
j=1
while (j<=10):
print("apple")
j=j+1
print("***********************************")
For loop:
Python For loop is used for sequential traversal i.e. it is used
for iterating over an iterable like [String, Tuple, List, Set or Dictionary]
In Python, there is no C style for loop, i.e., for (i=0; i<n; i++).
There is “for” loop which is similar to each loop in other languages.
In Python, for loops only implements the collection-based iteration.
Ex:
for i in range(5):
print(i)
if i == 2:
break
# The break keyword is used to break out a for loop, or a while loop .
Continue Statement:
Python continue keyword is used to skip the remaining statements of the
current loop and go to the next iteration.
The continue keyword return control of the iteration to the beginning of the
Python for loop or Python while loop.
Continue Statement Syntax:
while True:
... if x == 10:
Continue
print(x)
Ex:
for i in range(9):
if i == 3:
continue
print(i)
# Skip the iteration if the variable i is 3 and continue with next iteration
Note:
use break and continue statements to alter the flow of a loop.
Pass Statement:
for i in fruit:
if(i =='apple'):
pass
else:
print(i)
Output:
mango
cherry
orange
Strings in Python:
Python does not have a character data type, a single character is simply a string
with a length of 1. Square brackets can be used to access elements of the string.
LISTS:
Lists are one of the most powerful data structures in python. Lists are
sequenced data types. In Python, an empty list is created using list() function.
They are just like the arrays declared in other languages.
A single list can contain strings, integers, as well as other objects.
Lists can also be used for implementing stacks and queues.
Lists are mutable, i.e., they can be altered once declared. The elements
of list can be accessed using indexing and slicing operations.
In Python Lists are just like dynamically sized arrays, declared in other
languages (vector in C++ and ArrayList in Java).
In simple language, a list is a collection of things, enclosed in [ ] and
separated by commas.
The list is a sequence data type which is used to store the collection of
data.
Tuples and String are other types of sequence data types.
# creating empty list
l=[]
print(l)
l=[1,"one",2,"two",3,"three",4,"four"]
Print(l)
Ex:
t1=("apple","banana","orange")
print(t1[1:])
print(t1[0:1])
print(t1) output:
print(t1+t1)
print(t1*2)
print(type(t1))
Set:
Sets are used to store multiple items in a single variable. Set is one of 4 built-in
data types in Python used to store collections of data, the other 3 are List, Tuple, and
Dictionary, all with different qualities and usage.
•Note: Set items are unchangeable, but you can remove items and add new items.
Set Items:
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered:
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be
referred to by index or key.
Unchangeable:
Set items are unchangeable, meaning that we cannot change the items after the set
has been created.Once a set is created, you cannot change its items, but you can
remove items and add new items.
Output:
{1, 2, 3, 4, 'bc', 'ac', 'a', ' ab'}
Method Description
clear() Removes all the elements from the dictionary
items() Returns a list containing a tuple for each key value pair
setdefault() Returns the value of the specified key. If the key does not exist:
insert the key, with the specified value
Dictionaries are written with curly brackets, and have keys and values:
Ex:
>>> digits={1:"one",2:"two",3:"three"}
>>> digits
Output: {1: 'one', 2: 'two', 3: 'three'}
Dictionary Items:
Dictionary items are ordered, changeable, and does not allow
duplicates.
Dictionary items are presented in key:value pairs, and can be referred to
by using the key name.
Ordered or Unordered:
Note:As of Python version 3.7, dictionaries are ordered. In Python 3.6 and
earlier, dictionaries are unordered.
When we say that dictionaries are ordered, it means that the items
have a defined order, and that order will not change.
Unordered means that the items does not have a defined order, you
cannot refer to an item by using an index.
Changeable:
Dictionaries are changeable, meaning that we can change, add or
remove items after the dictionary has been created.
print(car)
Python Functions:
A Python function is a reusable, organized block of code that is used to
perform the specific task. The functions are the appropriate way to divide an extensive
program into a useful block. It also provides reusability to our program. A code block
can be reused by calling the function.
All functions are treated as an object in Python, so it is more flexible than other
programming languages.
In Python, there are two types of functions:
Built-in functions – These functions are the part of the Python libraries and packages.
These are also called as pre-defined functions.
User-defined functions – These functions are defined by the user as per their
requirement.
Syntax:
C syntax:
return_type function_name ( paramete
{
body of the function
}
Creating a function:
Below are the basic steps to create a user-defined function.
Arguments should be written inside the opening and closing parentheses of the
function, and end the declaration with a colon.
The return statement is optional. It should be written at the end of the function.
Creating a Python Function:
We can create a Python function using the def keyword.
Calling a Function
After declaring a function, it must be called using function name followed
by parentheses with appropriate argument.
Note: It is necessary to define a function before calling; otherwise, it will give an error.
Example 1:
def disp():
print(“hello world”)
disp()
2. Default argument:
The default arguments are those arguments that assign a value with the
argument at the time of function definition. If the argument is not specified at the
time of function call, then it will be initialized with the value which was given in the
definition. For example
def add(a,b=30): #default value def disp(name,age=45):
c=a+b print('My name is:',name)
return c print('My age is',age)
sum=add(10) disp("raju")
Print(sum); disp("srinivas",35)
3.Keyword arguments:
The benefit of keyword arguments is that we can pass the argument in the
random order, which means the order of passing arguments doesn’t matter. Each
argument treated as the keyword. It will match argument names in the function
definition and function call.
def employee(id,name,age):
employee(age=30,id=1,name= 'Srinivas‘)
employee(id=1,age=30,name='RAJU')
employee(name='RAVI',age=30,id=1)
4. Variable-length arguments:
Some times we are not sure about numbers of argument that can be passed
to a function, for such scenario, we use variable-length arguments.
There are two types of variable-length argument in a function:
We should use an asterisk ( * ) before the argument name to pass variable length
arguments. The arguments are passed as a tuple, and these passed arguments make
tuple inside the function with the same name as the argument excluding asterisk *.
def variable(*names):
for I in names:
print(I )
variable(‘ raju ', ‘ ravi', ‘ kishan', ' devid', 'mohan')
**kwarg arguments
We cannot pass the keyword argument using *args. Python provides
**kwargs; It allows us to pass variable-length of keyword argument to the function.
We must use the double-asterisk ** before the argument name to denote
this type of argument. The arguments are passed as a dictionary, and these
arguments make a dictionary inside the function with name same as the parameter
without double asterisk **.
For example:
def variable(**names):
for key, value in names . items():
print(key , value)
variable( first_ name = “raju ", last _ name=' ravi ', Age=25,Salary=34000)