0% found this document useful (0 votes)
3 views31 pages

Python 1st

Python is a high-level, interpreted programming language known for its simplicity and versatility, supporting object-oriented programming and a wide range of libraries. It was created by Guido van Rossum in 1991, evolving from the ABC programming language, and has since become popular in various fields such as data science, web development, and artificial intelligence. Key features include easy syntax, cross-platform compatibility, and a large standard library, making it accessible for beginners and powerful for experienced developers.

Uploaded by

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

Python 1st

Python is a high-level, interpreted programming language known for its simplicity and versatility, supporting object-oriented programming and a wide range of libraries. It was created by Guido van Rossum in 1991, evolving from the ABC programming language, and has since become popular in various fields such as data science, web development, and artificial intelligence. Key features include easy syntax, cross-platform compatibility, and a large standard library, making it accessible for beginners and powerful for experienced developers.

Uploaded by

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

Q.1 What is Python?

Explain History of python

Python is a general purpose, dynamic, high-level, and interpreted programming language. It


supports Object Oriented programming approach to develop applications. It is simple and easy to
learn and provides lots of high-level data structures.Python is easy to learn yet powerful and
versatile scripting language, which makes it attractive for Application Development. Python
provides many useful features to the programmer. These features make it most popular and
widely used language. We have listed below few-essential feature of Python.

Key features of python


1. It has easier to read syntax
2. It uses white space for indentation
3. Can be integrated with other languages(my sql)
4. Provides for efficient memory management(garbage collection)
5. Supports exception handling
6. Easy to use and Learn
7. Expressive Language
8. Interpreted Language
9. Object-Oriented Language
10. Open Source Language
11. Extensible
12. Learn Standard Library
13. GUI Programming Support
14. Integrated
15. Embeddable
16. Dynamic Memory Allocation
17. Wide Range of Libraries and Frameworks

Explore Features
1) Easy to Learn and Use
Python is easy to learn as compared to other programming languages. Its syntax is
straightforward and much the same as the English language. There is no use of the semicolon or
curly-bracket, the indentation defines the code block. It is the recommended programming
language for beginners.

2) Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello world
program you simply type print("Hello World"). It will take only one line to execute, while Java
or C takes multiple lines.

3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a time.
The advantage of being interpreted language, it makes debugging easy and portable.

4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh,
etc. So, we can say that Python is a portable language. It enables programmers to develop the
software for several competing platforms by writing a program only once.

5) Free and Open Source


Python is freely available for everyone. It is freely available on its official
website www.python.org. It has a large community across the world that is dedicatedly working
towards make new python modules and functions. Anyone can contribute to the Python
community. The open-source means, "Anyone can download its source code without paying any
penny."
6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come into
existence. It supports inheritance, polymorphism, and encapsulation, etc. The object-oriented
procedure helps to programmer to write reusable code and develop applications in less code.

7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can be
used further in our Python code. It converts the program into byte code, and any platform can use
that byte code.

8) Large Standard Library


It provides a vast range of libraries for the various fields such as machine learning, web
developer, and also for the scripting. There are various machine learning libraries, such as
Tensor flow, Pandas, Numpy, Keras, and Pytorch, etc. Django, flask, pyramids are the popular
framework for Python web development.

9) GUI Programming Support


Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy
are the libraries which are used for developing the web application.
10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by
line like C,C++ Java. It makes easy to debug the code.
11. Embeddable
The code of the other programming language can use in the Python source code. We can use
Python source code in another programming language as well. It can embed other language into
our code.
12. Dynamic Memory Allocation
In Python, we don't need to specify the data-type of the variable. When we assign some value to
the variable, it automatically allocates the memory to the variable at run time. Suppose we are
assigned integer value 15 to x, then we don't need to write int x = 15. Just write x = 15.
Python History
Python was invented by Guido van Rossum in 1991 at CWI in Netherland. The idea of Python
programming language has taken from the ABC programming language or we can say that ABC
is a predecessor of Python language.
There is also a fact behind the choosing name Python. Guido van Rossum was a fan of the
popular BBC comedy show of that time, "Monty Python's Flying Circus". So he decided to
pick the name Python for his newly created programming language.

Where is Python used?


Python is a general-purpose, popular programming language and it is used in almost every
technical field. The various areas of Python use are given below.
o Data Science
o Date Mining
o Desktop Applications
o Console-based Applications
o Mobile Applications
o Software Development
o Artificial Intelligence
o Web Applications
o Enterprise Applications
o 3D CAD Applications
o Machine Learning
o Computer Vision or Image Processing Applications.
o Speech Recognitions
History of Python
 Python laid its foundation in the late 1980s.
 The implementation of Python was started in December 1989 by Guido Van
Rossum at CWI in Netherland.
 In February 1991, Guido Van Rossum published the code (labeled version 0.9.0)
to alt.sources.
 In 1994, Python 1.0 was released with new features like lambda, map, filter, and
reduce.
 Python 2.0 added new features such as list comprehensions, garbage collection
systems.
 On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was
designed to rectify the fundamental flaw of the language.
 ABC programming language is said to be the predecessor of Python language,
which was capable of Exception Handling and interfacing with the Amoeba
Operating System.
 The following programming languages influence Python:
o ABC language.
o Modula-3

Python Popular Frameworks and Libraries


Python has wide range of libraries and frameworks widely used in various fields such as machine
learning, artificial intelligence, web applications, etc. We define some popular frameworks and
libraries of Python as follows.
o Web development (Server-side) - Django Flask, Pyramid, CherryPy
o GUIs based applications - Tk, PyGTK, PyQt, PyJs, etc.
o Machine Learning - TensorFlow, PyTorch, Scikit-learn, Matplotlib, Scipy, etc.
o Mathematics - Numpy, Pandas, etc.
Q. 2 Evaluate Python Variables ?
Variables are nothing but reserved memory locations to store values. This means that when you create
a variable you reserve some space in memory. Based on the data type of a variable, the interpreter
allocates memory and decides what can be stored in the reserved memory.

Variable Naming Rules in Python


1. Variable name should start with letter(a-zA-Z) or underscore (_).
Valid : age , _age , Age
Invalid : 1age
2. In variable name, no special characters allowed other than underscore (_).
Valid : age_ , _age
Invalid : age_*
3. Variables are case sensitive. age and Age are different, since variable names are case sensitive.
4. Variable name can have numbers but not at the beginning.
Example: Age1
5. Variable name should not be a Python keyword. Keywords are also called as reserved words.
How to Declare and use a Variable
Example: a=100
print (a)
Re-declare a Variable: You can re-declare the variable even after you have declared it once.
Example: a=100
print(a)
a=’BIST’
print(a)
Concatenate Variables
a='BIST'
b=1 print(a+b)
Note:will throw error , as we cannot concatenate two different datatypes. But a='BIST' b=1
print(a+str(b))
will display BIST1
Assigning multiple values to multiple variables
a, b, c,d = 8, 3.3, "BIST",5.2
print (a)
print (b)
print (c)
print (d)
output:
8
3.3
BIST
5.2
If we want to assign the same value to multiple variables at once, we can do this as
x = y = z = "bansal institute of science and technology"
print (x)
print (y)
print (z)

Ouput:
bansal institute of science and technology
bansal institute of science and technology
bansal institute of science and technology
Delete a variable :You can also delete variable using the command del "variable name"
Example:
S=34
Print(s)
del s
print(f)

Global and Local Variables in Python


1. Local variables :are those which are initialized inside a function and belong only to that particular
function. It cannot be accessed anywhere outside the function.

Example:

def localvariable():
y = "Bist"
print(y)
localvariable()

Output:
Bist

2. Global Variables: variable declared outside of the function or in global scope is known as a
global variable. This means that a global variable can be accessed inside or outside of the
function.
Example:
x = "global variable"
def glovariable():
print("x inside:", x)
glovariable()
print("x outside:", x)

Output:
x inside: global variable
x outside: global variable

Global variable and Local variable with same name


Example:
Semester =3
department="mca"
subject="python"

def Bist():
Semester = 1
department="mca"
subject="c with data structure"
print("local :",Semester,department,subject)
Bist()
print("global :",Semester,department,subject)

output:
local : 1 mca c with data structure
global : 3 mca python
Q. 3 Evaluate Data Types In python?
Data types are the classification or categorization of data items. It represents the kind of value that
tells what operations can be performed on a particular data. Since everything is an object in Python
programming, data types are actually classes and variables are instance (object) of these classes.

Numeric: numeric data type represent the data which has numeric value. Numeric value can be integer,
floating number or even complex numbers.
1.Integer: – This value is represented by int class
Example:
a=34
print(a)
print(a,type(a))
output:
34
34 <class 'int'>
3. float: This value is represented by float class.

b=34.4
print(b)
print(b,type(b))
3.Complex Number: omplex number is represented by complex class. It is specified as (real part) +
(imaginary part)j. For example – 2+3j
c = 2 + 4j
print("\nType of c: ", type(c))
Type of c: <class 'complex'>

Sequence Type
sequence is the ordered collection of similar or different data types. Sequences allows to store multiple
values in an organized and efficient fashion. There are several sequence types in Python.
 String
 List
 Tuple

1.String: String is sequence of Unicode characters. We can use single quotes or double quotes to
represent strings. Multi-line strings can be denoted using triple quotes, ''' or """.
Example:
s = "This is a string"
print(s)
s = '''A multiline
string'''
print(s)

Output:
This is a string
A multiline
string

2. List: List is an ordered sequence of items. It is one of the most used datatype in Python and is very
flexible. All the items in a list do not need to be of the same type.
Example:
a = [3,10,"mca"]
print("a[2] = ", a[2])
print(a)

Output:
a[2] = mca
[3, 10, 'mca']

3. Tuple:Tuple is an ordered sequence of items same as a list. The only difference is that tuples are
immutable. Tuples once created cannot be modified.Tuples are used to write-protect data and are usually
faster than lists as they cannot change dynamically.It is defined within parentheses () where items are
separated by commas.
Example:
t = (5,'program', 25.5)
print(t)

Output:
(5, 'program', 25.5)

Set
Set is an unordered collection of unique items. Set is defined by values separated by comma inside
braces { }. Items in a set are not ordered.
Example:
a = {5,45,1,47}
# printing set variable
print("a = ", a)
# data type of variable a
print(type(a))

Output:
a = {1, 45, 5, 47}
<class 'set'>
Dictionary is an unordered collection of key-value pairs. It is generally used when we have a huge
amount of data. Dictionaries are optimized for retrieving data. We must know the key to retrieve the
value. dictionaries are defined within braces {} with each item being a pair in the form key:value. Key
and value can be of any type.
Example:
d = {'dept':'mca','sub_code':303}
print(type(d))
print(d['dept'])
print(d)

Output:
<class 'dict'>
mca
{'dept': 'mca', 'sub_code': 303

Q. 4 Difference between interactive mode and script mode ?


Interactive Mode:

Python is a programming language that lets you work quickly and integrate systems more efficiently. It
is a widely-used general-purpose, high-level programming language. It was designed with an emphasis
on code readability, and its syntax allows programmers to express their concepts in fewer lines of code.
In the Python programming language, there are two ways in which we can run our code:
1. Interactive mode
2. Script mode

1. Interactive mode : Interactive mode is where you type your code into the Python interpreter
directly. This is useful for trying out small snippets of code, or for testing things out as you’re
writing them.
Advantage:
 The interactive mode is great for testing out commands and getting immediate feedback.
 It can also be used to quickly execute commands on a remote server.
Disadvantage:
 Disadvantages of interactive mode
 The interactive mode is not suitable for large programs.
 The interactive mode doesn’t save the statements. Once we make a program it is for that time
itself, we cannot use it in the future. In order to use it in the future, we need to retype all the
statements.
 Editing the code written in interactive mode is a tedious task. We need to revisit all our previous
commands and if still, we could not edit we need to type everything again.

# Python program to add two numbers


a=2
b=3

# Adding a and b and storing result in c


c=a+b

# Printing value of c
print(c)

output:
We can see the desired output on the screen. This kind of program is a very short program and can be
easily executed in interactive mode.

Script mode
Script mode is where you write your code in a .py file and then run it with the python command. This is
the most common way that people use Python because it lets you write and save your code so that you
can use it again later.

How to run python code in script mode?


In order to run a code in script mode follow the following steps.
Step 1: Make a file using a text editor. You can use any text editor of your choice(Here I use notepad).
Step 2: After writing the code save the file using “.py” extension.
Step 3: Now open the command prompt and command directory to the one where your file is stored.
Step 4: Type python “filename.py” and press enter.
Step 5: You will see the output on your command prompt.
Let us understand these steps with the help of the examples:
Example 1:
In order to execute “Hello gfg” using script mode we first make a file and save it.

Now we use the command prompt to execute this file.


Output:
Q.5 What is Expressions in python ?
A combination of operands and operators is called an expression. The expression in Python produces
some value or result after being interpreted by the Python interpreter. An expression in Python is a
combination of operators and operands.An example of expression can be : x = x + 10x=x+10. In this
expression, the first 1010 is added to the variable x. After the addition is performed, the result is
assigned to the variable x.

Example :
x = 25 # a statement
x = x + 10 # an expression
print(x)

Output :
35

An expression in Python is very different from statements in Python. A statement is not evaluated for
some results. A statement is used for creating variables or for displaying values.

Example :

a = 25 # a statement

print(a) # a statement

Output :

25

An expression in Python can contain identifiers, operators, and operands. Let us briefly discuss them.
An identifier is a name that is used to define and identify a class, variable, or function in Python.

An operand is an object that is operated on. On the other hand, an operator is a special symbol that
performs the arithmetic or logical computations on the operands. There are many types of operators in
Python, some of them are :

 + : add (plus).
 - : subtract (minus).
 x : multiply.
 / : divide.
 ** : power.
 % : modulo.
 << : left shift.
 >> : right shift.
 & : bit-wise AND.
 | : bit-wise OR.
 ^ : bit-wise XOR.
 ~ : bit-wise invert.
 < : less than.
 > : greater than.
 <= : less than or equal to.
 >= : greater than or equal to.
 == : equal to.
 != : not equal to.
 and : boolean AND.
 or : boolean OR.
 not : boolean NOT.
Types of Expression in Python
We have various types of expression in Python, let us discuss them along with their respective examples.
1. Constant Expressions
A constant expression in Python that contains only constant values is known as a constant expression. In
a constant expression in Python, the operator(s) is a constant. A constant is a value that cannot be
changed after its initialization.

Example :

x = 10 + 15

# Here both 10 and 15 are constants but x is a variable.


print("The value of x is: ", x)

Output :

The value of x is: 22. Arithmetic Expressions

An expression in Python that contains a combination of operators, operands, and sometimes parenthesis
is known as an arithmetic expression. The result of an arithmetic expression is also a numeric value
just like the constant expression discussed above. Before getting into the example of an arithmetic
expression in Python, let us first know about the various operators used in the arithmetic expressions.

Operator Syntax Working


+ x+y Addition or summation of x and y.
- x-y Subtraction of y from x.
x xxy Multiplication or product of x and y.
/ x/y Division of x and y.
// x // y Quotient when x is divided by y.
% x%y Remainder when x is divided by y.
** x ** y Exponent (x to the power of y).

Example :

x = 10
y = 5

addition = x + y
subtraction = x - y
product = x * y
division = x / y
power = x**y

print("The sum of x and y is: ", addition)


print("The difference between x and y is: ", subtraction)
print("The product of x and y is: ", product)
print("The division of x and y is: ", division)
print("x to the power y is: ", power)

Output :

The sum of x and y is: 15


The difference between x and y is: 5
The product of x and y is: 50
The division of x and y is: 2.0
x to the power y is: 100000
3. Integral Expressions

An integral expression in Python is used for computations and type conversion (integer to float,
a string to integer, etc.). An integral expression always produces an integer value as a resultant.

Example :

x = 10 # an integer number
y = 5.0 # a floating point number

# we need to convert the floating-point number into an integer or vice versa for
summation.
result = x + int(y)

print("The sum of x and y is: ", result)

Output :

The sum of x and y is: 15

4. Floating Expressions

A floating expression in Python is used for computations and type conversion (integer to float,
a string to integer, etc.). A floating expression always produces a floating-point number as a resultant.

Example :

x = 10 # an integer number
y = 5.0 # a floating point number

# we need to convert the integer number into a floating-point number or vice versa
for summation.
result = float(x) + y

print("The sum of x and y is: ", result)

Output :

The sum of x and y is: 15.0

5. Relational Expressions

A relational expression in Python can be considered as a combination of two or more arithmetic


expressions joined using relational operators. The overall expression results in
either True or False (boolean result). We have four types of relational operators in Python (i.e. > ,
< , >= , <=)(i.e.>,<,>=,<=).
A relational operator produces a boolean result so they are also known as Boolean Expressions.

For example :
10 + 15 > 2010+15>20

In this example, first, the arithmetic expressions (i.e. 10 + 1510+15 and 2020) are evaluated, and
then the results are used for further comparison.

Example :
a = 25
b = 14
c = 48
d = 45

# The expression checks if the sum of (a and b) is the same as the difference of (c
and d).
result = (a + b) == (c - d)
print("Type:", type(result))
print("The result of the expression is: ", result)

Output :

Type: <class 'bool'>


The result of the expression is: False

6. Logical Expressions

As the name suggests, a logical expression performs the logical computation, and the overall expression
results in either True or False (boolean result). We have three types of logical expressions in Python, let
us discuss them briefly.

Operator Syntax Working


and xx and yy The expression return True if both xx and yy are true, else it returns False.
or xx or yy The expression return True if at least one of xx or yy is True.
not not xx The expression returns True if the condition of xx is False.

Note :
In the table specified above, xx and yy can be values or another expression as well.

Example :

from operator import and_

x = (10 == 9)
y = (7 > 5)

and_result = x and y
or_result = x or y
not_x = not x

print("The result of x and y is: ", and_result)


print("The result of x or y is: ", or_result)
print("The not of x is: ", not_x)

Output :

The result of x and y is: False


The result of x or y is: True
The not of x is: True
7. Bitwise Expressions

The expression in which the operation or computation is performed at the bit level is known as a bitwise
expression in Python. The bitwise expression contains the bitwise operators.

Example :

x = 25
left_shift = x << 1
right_shift = x >> 1

print("One right shift of x results: ", right_shift)


print("One left shift of x results: ", left_shift)

Output :

One right shift of x results: 12


One left shift of x results: 50

8. Combinational Expressions

As the name suggests, a combination expression can contain a single or multiple expressions which
result in an integer or boolean value depending upon the expressions involved.

Example :

x = 25
y = 35

result = x + (y << 1)

print("Result obtained : ", result)

Output :

Result obtained: 95

Whenever there are multiple expressions involved then the expressions are resolved based on their
precedence or priority. Let us learn about the precedence of various operators in the following section.

Multiple Operators in Expression (Operator Precedence) ?

The operator precedence is used to define the operator's priority i.e. which operator will be executed first.
The operator precedence is similar to the BODMAS rule that we learned in mathematics. Refer to the
list specified below for operator precedence.

Precedence Operator Name


1. ()[]{} Parenthesis
2. ** Exponentiation
3. -value , +value , ~value Unary plus or minus, complement
4. / * // % Multiply, Divide, Modulo
5. +– Addition & Subtraction
6. >> << Shift Operators
7. & Bitwise AND
8. ^ Bitwise XOR
9. pipe symbol Bitwise OR
Let us take an example to understand the precedence better :

x = 12
y = 14
z = 16

result_1 = x + y * z
print("Result of 'x + y + z' is: ", result_1)

result_2 = (x + y) * z
print("Result of '(x + y) * z' is: ", result_2)

result_3 = x + (y * z)
print("Result of 'x + (y * z)' is: ", result_3)

Output :

Result of 'x + y + z' is: 236


Result of '(x + y) * z' is: 416
Result of 'z + (y * z)' is: 236

Difference between Statements and Expressions in Python

We have earlier discussed statement expression in Python, let us learn the differences between them.

Statement in Python Expression in Python

A statement in Python is used for creating The expression in Python produces some value or result after
variables or for displaying values. being interpreted by the Python interpreter.

A statement in Python is not evaluated for An expression in Python is evaluated for some results.
some results.

The execution of a statement changes the state The expression evaluation does not result in any state change.
of the variable.

A statement can be an expression. An expression is not a statement.

Example : x = 3x=3. Example: x = 3 + 6x=3+6.


Output : 33 Output : 99
Q.6 What is Statement ?

A statement is an instruction that the Python interpreter can execute. We have seen two kinds
of statements: print and assignment.When you type a statement on the command line, Python
executes it and displays the result, if there is one. The result of a print statement is a value.
Assignment statements don't produce a result.A script usually contains a sequence of
statements. If there is more than one statement, the results appear one at a time as the
statements execute.

Python statement ends with the token NEWLINE character. It means each line in a Python script is a
statement.For example, a = 10 is an assignment statement. where a is a variable name and 10 is its value.
There are other kinds of statements such as if statement, for statement, while statement, etc.,

Types of Statements:
1. Multi-Line Statements
2. Python Compound Statements
3. Simple Statements
4. Expression statements
5. The pass statement
6. The del statement

1. Multi-Line Statements
Python statement ends with the token NEWLINE character. But we can extend the statement over
multiple lines using line continuation character (\). This is known as an explicit continuation.

Example
addition = 10 + 20 + \
30 + 40 + \
50 + 60 + 70
print(addition)

Output: 280
2. Python Compound Statements
 Compound statements contain (groups of) other statements; they affect or control the execution
of those other statements in some way.
 The compound statement includes the conditional and loop statement.
 if statement: It is a control flow statement that will execute statements under it if the condition is
true. Also kown as a conditional statement.
 while statements: The while loop statement repeatedly executes a code block while a particular
condition is true. Also known as a looping statement.
 for statement: Using for loop statement, we can iterate any sequence or iterable variable. The
sequence can be string, list, dictionary, set, or tuple. Also known as a looping statement.
 try statement: specifies exception handlers.
 with statement: Used to cleanup code for a group of statements, while the with statement allows
the execution of initialization and finalization code around a block of code.

Simple Statements:
Apart from the declaration and calculation statements, Python has various simple statements for a
specific purpose.
a.Expression statements
Expression statements are used to compute and write a value. An expression statement evaluates the
expression list and calculates the value.An expression is a combination of values, variables,
and operators.
Example:
x=5
# right hand side of = is a expression statement

# x = x + 10 is a complete statement
x = x + 10

b. The pass statement


pass is a null operation. Nothing happens when it executes. It is useful as a placeholder when a statement
is required syntactically, but no code needs to be executed.
For example, you created a function for future releases, so you don’t want to write a code now. In such
cases, we can use a pass statement.
Example:
# create a function
def fun1(arg):
pass # a function that does nothing (yet)

c. The del statement


The Python del statement is used to delete objects/variables.
Syntax:
del target_list

Example:
x = 10
y = 30
print(x, y)

# delete x and y
del x, y

# try to access it
print(x, y)

Output:

10 30
NameError: name 'x' is not defined

d.The import statement

The import statement is used to import modules. We can also import individual classes from a module.
Example:
import datetime
# get current datetime
now = datetime.datetime.now()
print(now)
E.The continue and break statement

 break Statement: The break statement is used inside the loop to exit out of the loop.
 continue Statement: The continue statement skip the current iteration and move to the next
iteration.

Q.7 Evaluate tuple assignment ?


we can perform tuple assignment which is a quite useful feature. We can initialise or create a tuple in
various ways. Besides tuple assignment is a special feature in python. We also call this
feature unpacking of tuple.The process of assigning values to a tuple is known as packing. While on the
other hand, the unpacking or tuple assignment is the process that assigns the values on the right-hand
side to the left-hand side variables. In unpacking, we basically extract the values of the tuple into a
single variable.Moreover, while performing tuple assignments we should keep in mind that the number
of variables on the left-hand side and the number of values on the right-hand side should be equal. Or in
other words, the number of variables on the left-hand side and the number of elements in the tuple
should be equal. Let us look at a few examples of packing and unpacking.

Tuple Packing (Creating Tuples)


We can create a tuple in various ways by using different types of elements. Since a tuple can contain all
elements of the same data type as well as of mixed data types as well. Therefore, we have multiple ways
of creating tuples. Let us look at few examples of creating tuples in python which we consider as
packing.

Example 1: Tuple with integers as elements


>>>tup = (22, 33, 5, 23)
>>>tup
(22, 33, 5, 23)

Tuple Assignment (Unpacking)


Unpacking or tuple assignment is the process that assigns the values on the right-hand side to the left-
hand side variables. In unpacking, we basically extract the values of the tuple into a single variable.
Example
>>>(n1, n2) = (99, 7)

>>>print(n1)

99

>>>print(n2)

7
TUPLE ASSIGNMENT

 An assignment to all of the elements in a tuple using a single assignment statement.


 Python has a very powerful tuple assignment feature that allows a tuple of variables on the left of
an assignment to be assigned values from a tuple on the right of the assignment.
 The left side is a tuple of variables; the right side is a tuple of values.
 Each value is assigned to its respective variable.

Example:Swap two numbers


a=2
b=3
print(a,b)
temp = a
a=b
b = temp
print(a,b)
Output:
(2, 3)
(3, 2)

Q.8 Demonstrate Precedence Of Operators?

Operator Precedence: This is used in an expression with more than one operator with different precedence to
determine which operation to perform first.
Example: Solve
10 + 20 * 30

The following table lists all operators from highest precedence to lowest.

Operator Description

** Exponentiation (raise to the power)

~+- Complement, unary plus and minus (method names


for the last two are +@ and -@)
* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

>> << Right and left bitwise shift

& Bitwise 'AND'td>

^| Bitwise exclusive `OR' and regular `OR'

<= < > >= Comparison operators


<> == != Equality operators
= %= /= //= -= += Assignment operators
*= **=
is is not Identity operators

in not in Membership operators


not or and Logical operators
Operator precedence affects how an expression is evaluated.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than
+, so it first multiplies 3*2 and then adds into 7.

Example

#!/usr/bin/python

a = 20
b = 10
c = 15
d=5
e=0

e = (a + b) * c / d #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ", e

e = ((a + b) * c) / d # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ", e

e = (a + b) * (c / d); # (30) * (15/5)


print "Value of (a + b) * (c / d) is ", e

e = a + (b * c) / d; # 20 + (150/5)
print "Value of a + (b * c) / d is ", e

Output:
Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
Value of (a + b) * (c / d) is 90
Value of a + (b * c) / d is 50

Q.9 Demonstrate comments in python ?

Comments in Python is the inclusion of short descriptions along with the code to increase its readability.
A developer uses them to write his or her thought process while writing the code. It explains the basic
logic behind why a particular line of code was written. They are just meant for the coders themselves or
other developers to understand a piece of code, especially since the Python interpreter completely
ignores comments in Python.

What Are Comments in Python Used For?


Comments in Python are identified with a hash symbol, #, and extend to the end of the line. Hash
characters in a string are not considered comments, however. There are three ways to write a comment -
as a separate line, beside the corresponding statement of code, or as a multi-line comment block.
 There are multiple uses of writing comments in Python. Some significant uses include:
 Increasing readability
 Explaining the code to others
 Understanding the code easily after a long-term
 Including resources
 Re-using the existing code
What Are the Advantages of Using Comments in Python?

 Comments in Python provide numerous advantages. Their primary benefits include:


 Makes the code easily understandable by other programmers
 The code becomes self-explanatory
 Helps remember why we used a specific command, method, or function in the code
 Enables the interpreter to ignore some part of the code while testing

There are three types of comments:


 single-line
 multi-line
 docstring comments.

1. Single-Line: Single-line comments begin with the “#” character. Anything that is written in a
single line after ‘#’ is considered as a comment.

Syntax:
# comments here

Example:
print("Hello, World!") #This is a sinle- line comment

2. Multi-Line Comments
Python does not support multi-line comments. However, there are multiple ways to overcome this
issue. None of these ways are technically multi-line comments, but you can use them as one. The first
way is by using # at the beginning of each line of the comment.

Syntax:
# comments here

Example:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

3. Python Docstrings
Python provides an in-built feature called docstrings for commenting on modules, methods, functions,
objects, and classes. They are written in the first line after defining a module, function, method, etc.,
using three quotation marks (‘’ or “”). If you do not use it in the first line, the interpreter will not take it
as a docstring. You can also access docstrings using the __doc__ attribute.

Example:
def square(n):
'''Takes in a number n, returns the square of n'''
return n**2
Q.10 Evaluate python module?

A Python module is a file containing Python definitions and statements. A module can define functions, classes,
and variables. A module can also include runnable code. Grouping related code into a module makes the code
easier to understand and use. It also makes the code logically organized.
Let’s create a simple calc.py in which we define two functions, one add and another subtract.
Create a simple Python module
# A simple module, calc.py
def add(x, y):
return (x+y)

def subtract(x, y):


return (x-y)
Import Module in Python
We can import the functions, and classes defined in a module to another module using the import
statement in some other Python source file. When the interpreter encounters an import statement, it
imports the module if the module is present in the search path. A search path is a list of directories that
the interpreter searches for importing a module.
For example, to import the module calc.py, we need to put the following command at the top of the
script.

Syntax
import module

Note: This does not import the functions or classes directly instead imports the module only. To access
the functions inside the module the dot(.) operator is used.

Importing modules in Python


Now, we are importing the calc that we created earlier to perform add operation.

Example:
# importing module calc.py
import calc
print(calc.add(10, 2))

Output:
12
The from-import Statement in Python
Python’s from statement lets you import specific attributes from a module without importing the module
as a whole.

Importing specific attributes from the module


Here, we are importing specific sqrt and factorial attributes from the math module.
# importing sqrt() and factorial from the
# module math
from math import sqrt, factorial

# if we simply do "import math", then


# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))
Output:
4.0
720

Import all Names


The * symbol used with the from import statement is used to import all the names from a module to a
current namespace.

Syntax:
from module_name import *

from import * Statement

The use of * has its advantages and disadvantages. If you know exactly what you will be needing from the module,
it is not recommended to use *, else do so.

# importing sqrt() and factorial from the


# module math
from math import *

# if we simply do "import math", then


# math.sqrt(16) and math.factorial()
# are required.
print(sqrt(16))
print(factorial(6))
Output
4.0

Q.11 Evaluate python Functions?

Function: 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.
As you already know, Python gives you many built-in functions like print(), etc. but you can also create
your own functions. These functions are called user-defined functions.

Defining a Function

Rules to define a function in Python.

 Function blocks begin with the keyword def followed by the function name and parentheses
( ( ) ).
 Any input parameters or arguments should be placed within these parentheses. You can also
define parameters inside these parentheses.
 The first statement of a function can be an optional statement - the documentation string of the
function 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.
Advantages of Python:

 By including functions, we can prevent repeating the same code block repeatedly in a
program.

 Python functions, once defined, can be called many times and from anywhere in a program.

 If our Python program is large, it can be separated into numerous functions which is simple
to track.

 The key accomplishment of Python functions is we can return as many outputs as we want
with different arguments.

Syntax
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
Example

def printme( str ):


"This prints a passed string into this function"
print str
return

1. Calling a Function
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.

# Function definition is here


def printme( str ):
"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")

output:
I'm first call to user defined function!
Again second call to the same function

2. Pass by reference vs value


All parameters (arguments) in the Python language are passed by reference. It means if you change what
a parameter refers to within a function, the change also reflects back in the calling function
Example:
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4]; # This would assig new reference in mylist
print "Values inside the function: ", mylist
return

# Now you can call changeme function


mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist

Output:

Values inside the function: [1, 2, 3, 4]


Values outside the function: [10, 20, 30]

Q.12 Evaluate Flow of Execution

The flow of execution basically refers to the order in which statements are executed. That is to say,
execution always starts at the first statement of the program. Moreover, statements execute one at a time.
1. Flow of execution without function

Generally, in a simple and basic python program, you sea that every python program is executed in a sequential
manner that means line by line, the first line executed first, second line executed secondly and so on to the last
line in a Python program but after creating our programs through functions, the functions completely changed its
flow of execution.

Example:

num1= float(inpit"Entrr first number"))


num2= float(inpit"Entrr second number"))
sum=num1+num2
print (sum)

Execution starts from here

2.Program with functions


When a python program is written through function, then the control is not going to follow the rule of
sequential programming, that means, now the program is not going to be executed line by
line (sequentially) and provides the flexibility to execute any statement at any time required to fulfil the
logic of the program.
Now, instead of going to the next statement, and starting from the first, a python program begins with
the top level statements according to the logic of program and the flow of control may jumps to the
statements required for given logic. It may also jumps to body of the function and executes all the
statements there, and then comes back to pick up where it left off.

Example:

def sum( x,y):


s=x+y
return sum
num1= float(inpit"Entrr first number"))
num2= float(inpit"Entrr second number"))
sum(num1,num2)
print (sum)

Table Of Comparison For Execution


without
S.no with function
function
Line
1 Line 1
4 to Line 5
Line
2 Line 2
6 to Line 1
Line
3 Line 3
2 to Line 3
Line
4 Line 4
6 to Line 7
Q.13 Explain parameters and arguments in python?

Parameters:
A parameter is the variable defined within the parentheses during function definition. Simply they are written
when we declare a function.
Example:
# Here a,b are the parameters
def sum(a,b):
print(a+b)
3

Arguments:
An argument is a value that is passed to a function when it is called. It might be a variable, value or object passed
to a function or method as input. They are written when we are calling the function.
Example:
def sum(a,b):
print(a+b)
# Here the values 1,2 are arguments
sum(1,2)
Output:
3
Types of arguments in python:
Python functions can contain two types of arguments:
1. Positional Arguments
2. Keyword Arguments

1. Positional Arguments:
Positional Arguments are needed to be included in proper order i.e the first argument is always listed first when
the function is called, second argument needs to be called second and so on.
Example:
Python3
def person_name(first_name,second_name):
print(first_name+second_name)

# First name is Ram placed first


# Second name is Babu place second
person_name("Ram","Babu")
Output:
RamBabu
2. Keyword Arguments:
Keyword Arguments is an argument passed to a function or method which is preceded by a keyword and an equal
to sign. The order of keyword argument with respect to another keyword argument does not matter because the
values are being explicitly assigned.
Python3
def person_name(first_name,second_name):
print(first_name+second_name)

# Here we are explicitly assigning the values


person_name(second_name="Babu",first_name="Ram")
Output:
RamBabu
Practical Questions:

1. Write a python program to swap the given two numbers using function

def swap(x,y):

t=x

x=y

y=t

print("after swap value",x,y)

return(x,y)

x,y=20,10

d=swap(x,y)

print("before swap value",x,y)

Output:

after swap value 10 20

before swap value 20 10


2. Writ a program to calculate Distance between two points

import math

def distance(x1,x2,y1,y2):

dx=x2-x1

dy=y2-y1

print("The value of dx is", dx)

print("The value of dy is", dy)

dist=math.sqrt(dx**2 + dy**2)

return dist

x1 = float(input("Enter the x1: "))

x2 = float(input("Enter the x2: "))

y1 = float(input("Enter the y1: "))

y2 = float(input("Enter the y2 "))

d=distance(x1,x2,y1,y2)

print("The distance between two points are", round(d,2))

Output:

Enter the x1: 4

Enter the x2: 8

Enter the y1: 6

Enter the y2 12

The value of dx is 4.0

The value of dy is 6.0

The distance between two points are 7.21


3 Write a python program to circulate the values of n variables.​
def circulate(list,n):

cir=list[n:]+list[:n]

return cir

list=[23,45,89,67,89,90]

n=int(input(“enter element index number”))

result=circulate(list,n)

print(result)

Output:

Enter element index number 2

[89, 67, 89, 90, 23, 45]

You might also like