Python 1st
Python 1st
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.
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.
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)
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
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
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.
# 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.
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
Output :
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.
Example :
x = 10
y = 5
addition = x + y
subtraction = x - y
product = x * y
division = x / y
power = x**y
Output :
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)
Output :
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
Output :
5. Relational 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 :
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.
Note :
In the table specified above, xx and yy can be values or another expression as well.
Example :
x = (10 == 9)
y = (7 > 5)
and_result = x and y
or_result = x or y
not_x = not x
Output :
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
Output :
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)
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.
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.
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 :
We have earlier discussed statement expression in Python, let us learn the differences between them.
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 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
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
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.
>>>print(n1)
99
>>>print(n2)
7
TUPLE ASSIGNMENT
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
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; # 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
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.
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)
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.
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.
Syntax:
from module_name import *
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.
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
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
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.
output:
I'm first call to user defined function!
Again second call to the same function
Output:
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:
Example:
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)
1. Write a python program to swap the given two numbers using function
def swap(x,y):
t=x
x=y
y=t
return(x,y)
x,y=20,10
d=swap(x,y)
Output:
import math
def distance(x1,x2,y1,y2):
dx=x2-x1
dy=y2-y1
dist=math.sqrt(dx**2 + dy**2)
return dist
d=distance(x1,x2,y1,y2)
Output:
Enter the y2 12
cir=list[n:]+list[:n]
return cir
list=[23,45,89,67,89,90]
result=circulate(list,n)
print(result)
Output: