Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Python Lab (1)

The document provides an introduction to Python programming, covering key concepts such as variables, data types, operators, control structures, and built-in data structures. It highlights Python's simplicity, readability, and widespread use by major organizations. Additionally, it includes examples of syntax and functionality for various programming constructs in Python.

Uploaded by

sravanipakala205
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)
4 views

Python Lab (1)

The document provides an introduction to Python programming, covering key concepts such as variables, data types, operators, control structures, and built-in data structures. It highlights Python's simplicity, readability, and widespread use by major organizations. Additionally, it includes examples of syntax and functionality for various programming constructs in Python.

Uploaded by

sravanipakala205
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/ 71

Python

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

Variables are containers for storing data values. Python variable is


also known as an identifier and used to hold value.

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.

# Python program to declare


variables

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

Function - Id() returns integer value


Assigning Values to Variables
>>> a,b,c=1,2,3
>>>a
1
>>>b
2
>>>c
3
Addition & Assignment (+=): x+=y is equivalent to x=x+y

Subtraction & Assignment (-=): x-=y is equivalent to x=x-


y
Power & Assignment (**=): x**=y is equivalent
to x=x**y
DATA TYPES

Variables can store data of different types, such as:


•Numeric Types : int, float, complex
•Sequence Types : string, list, tuple
•Boolean Type : bool
•Mapping Type : dict
•Set Types : set, frozenset
Size of different data types in Python
The size of each data type in Python 3 is as follows:
Size of int is: 12
Size of float is: 16
Size of str is: 25
Size of list is: 20
Size of tuple is: 12
Size of dict is: 120
Size of set is: 100
Size of frozenset is: 100
Size of None is: 8
Size of Ellipsis is: 8
Size of Object is: 8
Size of Lambda is: 60
Size of Function-ref is: 60
Size of Exception is: 32
Input and Output Statements
OPERATORS
Python Logical
Operators
Logical operators are used to combine conditional statements:

Operator Description Example


and Returns True if both statements x < 5 and x < 10
are true

or Returns True if one of the x < 5 or x < 4


statements is true

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:

Operat Name Description


or

& AND Sets each bit to 1 if both bits are 1


| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left Shift left by pushing zeros in from the right and let the leftmost bits fall
shift off

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

& (AND) | (OR) ~ (NOT)


a=5= 0101 a=5= 0101 a=5=0101
b=3= 0011 b=3= 0011 ----------------
---------------------- ----------------- ~a 1010 -> 10 –>converted to 2’s complement
0001 1 0111-> 7 ---------------- (formula) ~a= - (a+1) = - 6
----------------------- -----------------

^ (XOR) << left shift >> right shift


a=5= 0101 a=5 -> 0101 a=5 ->0101
b=3= 0011 a<<2 a>>2 loosing
--------------------- Octal representation
0110 -> 6 0000 0101 adding 0000 0101
----------------------- 00010100 ->20 0000 0001 -> 1
shifting left -------> <------- shifting right
bits gaining bits loosing
00010100 00000001
Membership operators : in , not in (like search )

Identity operators: is , is not

--- > is

--- > is not


In ,not in (Like search operation) Is ,is not (like == operator)
Comparison is done based on id value but not value
Python Assignment
Operators
Assignment operators are used to assign values to variables:
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
Python Comparison Operators
Comparison operators are used to compare two values:

Operator Name Example


== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
CONTROL STRUCTURES

• 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

Syntax of While Loop:


while conditional_expression:
Block of statements
import os
clear=lambda:os.system("cls")
clear()
# printing natural numbers 1-10

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.

For Loops Syntax:


for var in iterable/sequence:
Example: # statements
#Python program to illustrate
# Iterating over a list
l = [" apple", " banana ", " orange"]
for i in l:
print(i)
alist=[1,2,3,4,5]
for i in alist:
print(i)
Break statement:
The break is a keyword in python which is used to bring the program
control out of the loop. The break statement breaks the loops one by one, i.e., in
the case of nested loops, it breaks the inner loop first and then proceeds to
outer loops.
In other words, we can say that break is used to abort the current
execution of the program and the control goes to the next line after the loop.
The break is commonly used in the cases where we need to break the loop for a
given condition.

Break statement Syntax:


Loop (
Condition:
break
)

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:

In Python programming, the pass statement is a null statement.


The difference between a comment and a pass statement in Python is that
while the interpreter ignores a comment entirely, pass is not ignored.
Pass may be used when we don't wish any code to be executed.
We can simply insert a pass in places where empty code is prohibited, such
as loops, functions, class definitions, or if-else statements.

# Python program to show how to use a pass statement in a for loop


pass acts as a placeholder. We can fill this place later on.

sequence = {“apple", “banana", “orange”}


for value in sequence:
if value == “banana":
pass # leaving an empty if block using the pass keyword
else:
print("Not reached pass keyword: ", value)
fruit =['mango', 'apple', 'cherry', 'orange']

for i in fruit:

if(i =='apple'):
pass
else:

print(i)

Output:
mango
cherry
orange
Strings in Python:

A string is a sequence of characters that can be a combination of letters,


numbers, and special characters. It can be declared in python by using single quotes,
double quotes, or even triple quotes. These quotes are not a part of a string, they
define only starting and ending of the string. Strings are immutable, i.e., they cannot
be changed. Each element of the string can be accessed using indexing or slicing
operations.

In Python, Strings are arrays of bytes representing Unicode characters.


Example:
“srinivas" or ‘hello world‘

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.

>>> Print(“hello world”)


output : hello world
Accessing characters in String:

In Python, individual characters of a String can be accessed by using the


method of Indexing ie index value ‘0’ on words.

Indexing allows negative address references to access characters


from the back of the String, e.g. -1 refers to the last character, -2 refers to the second
last character, and so on.

While accessing an index out of the range will cause an IndexError.


Only Integers are allowed to be passed as an index, float or other types that will cause
a TypeError.
S R I N I V A S
String -> 0 1 2 3 4 5 6 7
Index values -> -8 -7 -6 -5 -4 -3 -2 -1

Pre defined methods


Built-in Data Structures
Python have 4 types of built-in Data Structures namely List, Dictionary, Tuple, and Set.

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)

# creating list of numbers


l=[1,2,3,4]
print(l)

#creating list of strings


l=["apple","banana","orange"]
print(l)

l=[1,"one",2,"two",3,"three",4,"four"]
Print(l)

Python len() is used to get the length of the list.


# creating empty list
l=[] l1=[1,2,3,4]
print(l) l2=["abc","xyz","pqr"]
print(len(l1))
# creating list of numbers print(len(l2))
l=[1,2,3,4]
print(l) #Accessing elements from a multi-dimensional
list
#creating list of strings l=[[1,2,3,4],[5,6,7,8,9]]
l=["apple","banana","orange"] print(l)
print(l) print(l[0][0])
print(l[1][1])
l=[1,"one",2,"two",3,"three",4,"four"] print(l[1][0])
print(l) print(l[0][2])
print(l[0:2])
print(l[5:6]) # IndexError: list index out of range
print(l[2][0])
Python offers the following list functions:

sort(): Sorts the list in ascending order.

type(list): It returns the class type of an object.

append(): Adds a single element to a list.

extend(): Adds multiple elements to a list.

index(): Returns the first appearance of the specified value.

max(list): It returns an item from the list with max value.

min(list): It returns an item from the list with min value.

len(list): It gives the total length of the list.

cmp(list1, list2): It compares elements of both lists list1 and list2.


# Python program to illustrate a list

# creates a empty list


nums = []
# appending data in list
nums.append(21)
nums.append(40.5)
nums.append("String") Output:
print(nums)
Tuple :
A tuple in Python is similar to a list . The difference between the two
is that we cannot change the elements of a tuple once it is assigned where as
we can change the elements of a list.

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.

A set is a collection which is unordered, unchangeable*, and unindexed.

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

Duplicates Not Allowed :


Sets cannot have two items with the same value.
1. Using the set() method:
When a set is created using the set() method, only the unique elements are added
to the set, even though the same element is defined twice inside the set() function.
This is because the basic rule of defining a set says that elements have to be unique.

s1 = set([1,2,3,2, 'a', 'b', 'a', ‘x', ‘y', ‘x',])


print(s1)

output: {1, 2, 3, 'a', ’x,’ ’y’, 'b', }

2. Using curly braces and comma-separated values


A set can have multiple types of data in it. Below is an example that shows set with a
single data type. It is followed by an example that shows a set being defined with elements
of different data types.

s2={ 1,2,3,4,1, 'a', ' ab', 'ac', 'bc ‘}

Output:
{1, 2, 3, 4, 'bc', 'ac', 'a', ' ab'}
Method Description
clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not exist:
insert the key, with the specified value

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary


Note: As of Python version 3.7, dictionaries are ordered. In Python 3.6 and
earlier, dictionaries are unordered.

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.

Duplicates Not Allowed:


Dictionaries cannot have two items with the same key:
Ex:
car = { "brand": "Ford", "model": “xyz", “color": ”red”, "year": 2020}

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.

 def keyword is used to define function followed by the function name.

 Arguments should be written inside the opening and closing parentheses of the
function, and end the declaration with a colon.

 Write the program statements to be executed within the function body.

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

# A simple Python function


def fun():
print("Welcome to python ")

Calling a Python Function:


After creating a function we can call it by using the name of the function
followed by parenthesis containing parameters of that particular function.

# A simple Python function defining


def fun():
print(" Welcome to python ")
# code to call a function
fun()
The argument list can contain none or more arguments. The arguments are
also called parameters. The function body contains indented statements. The function
body gets executed whenever the function is called. The arguments can be optional or
mandatory.

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

Example 2: def sum(a,b): # define a function sum with two argument


c=a+b
return c #returning the value to calling function
z=sum(10,20)
print("The sum is:",z)
def disp(n):
if n == 0: # Base condition to stop recursion
return
print("hello world")
disp(n - 1)

disp(5) # Prints "hello world" 5 times


Parameter Passing
There are two most common strategies of passing an argument to a function.
Call by Value
This strategy is used in C, C++ or Java but not used in Python. In call by
value, the values of actual parameters are copied to function’s formal parameters, and
both types of parameters are stored in separate memory locations. So if we made any
changes in formal parameters, that changes will not be reflected in actual parameters of
the caller function.
Call by Reference
The functions are called by reference in Python, which means all the changes
performed to the inside the function reflected in an actual parameter.
Types of arguments
There may be several types of arguments, which are listed below
1. Required arguments
2. Default arguments
3. Keyword arguments
4. Variable-length arguments
1. Required Arguments:
The required arguments are those arguments which are mandatory to pass
at the time of function calling with exact match their positions in the function call and
function definition. If the argument is not provided in the function call or made any
changes in arguments position, then Python interpreter will show an error.
def add(a,b): def add(a,b):
c=a+b c=a+b
return c return c
sum=add(10,20) sum=add(10)
Print(sum); Print(sum);
Output: 30 Output: TypeError: add() missing 1 required
positional argument: 'b'

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

print('Employee Id:',id,'\nEmployee',name,'\nEmployee Age:',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:

 *args (Non-Keyword argument)


 **kwargs (Keyword argument)

*args (Non-Keyword argument)


Python provides *args which allows to pass the variable number of 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)

You might also like