Unit 1 Python
Unit 1 Python
Developers often have a need to interact with users, either to get data or to provide some sort of result.
Most programs today use a dialog box as a way of asking the user to provide some type of input. While
Python provides us with two inbuilt functions to read the input from the keyboard.
input ( prompt )
raw_input ( prompt )
input()
input (): This function first takes the input from the user and converts it into a string. The type of the
returned object always will be <class ‘str’>. It does not evaluate the expression it just returns the complete
statement as String. For example, Python provides a built-in function called input which takes the input from
the user. When the input function is called it stops the program and waits for the user’s input. When the
user presses enter, the program resumes and returns what the user typed.
EXAMPLE
val = input("Enter your value: ")
print(val)
Output
Enter your name xyz
xyz
Input()
When input() function executes program flow will be stopped until the user has given input.
The text or message displayed on the output screen to ask a user to enter an input value is optional i.e.
the prompt, which will be printed on the screen is optional.
Whatever you enter as input, the input function converts it into a string. if you enter an integer value still
input() function converts it into a string. You need to explicitly convert it into an integer in your code
using typecasting
Input()
Output
enter the number: 123
123
Input()
output
enter the number
123
123
enter the name
Rani
Rani
type of number <class ‘str’>
Type of name<class ‘str’>
Input()
output
enter the number
123
123
enter the name
Rani
Rani
type of number <class ‘int’>
Type of name<class ‘str’>
Input()
This function works in older version (like Python 2.x). This function takes exactly what is typed from the
keyboard, converts it to string, and then returns it to the variable in which we want to store it.
number=raw_input("enter the number in decimal")
print(number)
Output
raw_input is not defined
Write a program to take number from user and add these number
Link in Description
PYTHON PROGRAMMING
Basic Program
Area and perimeter of rectangle ,
square By PRAGYA RAJVANSHI
Area and circumference of circle B.Tech, M.Tech( C.S.E)
output
enter the length of rectangle
6
the length of rectangle 6
enter the width of rectangle
7
the width of rectangle 7
the area of rectangle 42
write a program to find out the area of rectangle
output
Enter the length of rectangle
6.8
Traceback (most recent call last):
File "/home/main.py", line 1, in <module>
x=int(input("enter the length of rectangle\n"))
ValueError: invalid literal for int() with base 10: '6.8'
write a program to find out the area of rectangle
output
enter the length of rectangle
6.7
the length of rectangle 6.7
enter the width of rectangle
5.5
the width of rectangle 5.5
the area of rectangle 36.85
write a program to find out the area of rectangle
output
enter the length of rectangle
6
the length of rectangle 6.0
enter the width of rectangle
7
the width of rectangle 7.0
the area of rectangle 42.0
write a program to find out the perimeter of rectangle
output
enter the length of rectangle
4
the length of rectangle 4
enter the width of rectangle
5
the width of rectangle 5
the perimeter of rectangle 18
write a program to find out the perimeter of rectangle
output
enter the length of rectangle
8.9
the length of rectangle 8.9
enter the width of rectangle
9.8
the width of rectangle 9.8
the perimeter of rectangle 37.400000000000006
write a program to find out the area and perimeter of square
output
enter the side of the square
9.8
the side of the square 9.8
the area of the square 96.04000000000002
the perimeter of square 39.2)
write a program to find out the area and circumference of circle
output
enter the radius of circle
6.7
the radius of circle 6.7
the area of circle 140.9546
the perimeter of circle 42.076
write a program to swap two number with using third variable
Link in Description
PYTHON PROGRAMMING
Data type
By PRAGYA RAJVANSHI
B.Tech, M.Tech( C.S.E)
Data type
Every value has a data type, and variables can hold values. Python is a powerfully composed language
A=5 We did not specify the type of the variable a, which has the value five from an integer. The Python
interpreter will automatically interpret the variable as an integer.
We can verify the type of the program-used variable thanks to Python. The type() function in Python
returns the type of the passed variable.
a=5
print("the type of a ", type(a))
Output
the type of a <class 'int'>
Data type
a=20.5
b=6
c="hello“
print("thetype of a",type(a))
print("the type of b",type(b))
print("the type of c",type(c))
Data type
num1=5
print(num1,"is type",type(num1))
num2=2.0
print(num2,"is of type",type(num2))
num3=1+2j
print(num3,'is of type',type(num3))
Output
5 is type <class 'int'>
2.0 is of type <class 'float'>
(1+2j) is of type <class 'complex'>
sequencing type
String
The sequence of characters in the quotation marks can be used to describe the string. A string can be
defined in Python using single, double, or triple quotes.
str1="hi"
str2='bye'
str3='''hello'''
print(str1,"is of type",type(str1))
print(str2,"is of type ",type(str2))
print(str3,"is of type",type(str3))
sequencing type
String
output
hi is of type <class 'str'>
bye is of type <class 'str'>
hello is of type <class 'str'>
sequencing type
String handling
str1="hello gatewayclasses"
str2="welcome"
print(str1[0:2])#printing first two character using slice operator
print(str2[1:3])#printing second and third character
print(str1[4])#printing the element present at four index
print(str2[5])#printing the element present at fifth index
print(str1*2)#printing the string twice
print(str2*4)#printing the string four time
print(str1+str2)#concatenation
print(str2+str1)
sequencing type
String handling
output
he
el
o
m
hello gatewayclasseshello gatewayclasses
welcomewelcomewelcomewelcome
hello gatewayclasseswelcome
welcomehello gatewayclasses
sequencing type
list
List is an ordered collection of similar or different types of items separated by commas and enclosed within
brackets [ ]. For example,
language=["python","c","java"]
print("the type of language",type(language)
Output
the type of language <class 'list'>
,
sequencing type
list
language=["python","c","java"]
print(language[3]),
Output
ERROR!Traceback (most recent call last):
File "<string>", line 2, in <module>IndexError: list index out of range
sequencing type
list
language=["python",1,"c","java",3.5]
print(language)
Output
['python', 1, 'c', 'java', 3.5]
sequencing type
list
list1 = [1, "hi", "Python", 2]
print(type(list1))
print (list1)
print(list1[2:])#list slicingprint
(list1[3:]) #list slicing print(list1[:2]) #list slicingprint
(list1[0:2]) #list slicing print
(list1 + list1) #concatenation using+operatorprint
(list1 * 3) #list repetition using*operator
sequencing type
list
output
[2]
[1, 'hi']
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
Link in Description
PYTHON PROGRAMMING
Data type
By PRAGYA RAJVANSHI
B.Tech, M.Tech( C.S.E)
sequencing type
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.
In Python, we use the parentheses () to store items of a tuple. For example,
sequencing type
product=('microsoft','xbox',499.99)
product2=("samsung","vivo",2,4.555)
print(product)
print(product2)
print("type of product",type(product))
print("type of product",type(product2))
print(product[0])
print(product[1])
print(product2[2])
sequencing type
output
('microsoft', 'xbox', 499.99)
('samsung', 'vivo', 2, 4.555)
type of product <class 'tuple'>
type of product <class 'tuple'>
microsoft
xbox
2
sequencing type
d={1:'gatewayclasses',2:'python',3:'datatype',4:'module'}
print(d)
print(d.keys())
print(d.values())
print("1name is "+d[1])
print("3name "+d[3])
Output
dict_keys([1, 2, 3, 4])
dict_values(['gatewayclasses', 'python', 'datatype', 'module'])
1name is gatewayclasses
3name datatype
Boolean
The Boolean value can be of two types only i.e. either True or False. The output <class ‘bool’> indicates the variable is a
Boolean data type.
a = True
type(a)
output
<class 'bool'>
b = False
type(b)
Output
<class 'bool'>
sets
Set items are unordered, unchangeable, and do not allow duplicate values.
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.
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.
sets
output
{'apple', 'banana', 'cherry'}
{1, 3, 5, 7, 9}
{False, True}
{True, 34, 40, 'male', 'abc'}
thisset = {"apple", "banana", "cherry",1,1}
print(len(thisset))
Output
4
AKTU Full Courses (Paid)
Download Gateway Classes Application
From Google Play store
All Subjects
Link in Description
PYTHON PROGRAMMING
operator
By PRAGYA RAJVANSHI
B.Tech, M.Tech( C.S.E)
operator
These are the special symbols in Python and are used to execute an Arithmetic or Logical computation. An
operator alone cannot perform an activity, it needs an Operand. What is an operand? An Operand is a value
that the operator needs to complete a task.
Types of Operators in Python
We have multiple operators in Python, and each operator is subdivided into other operators. Let’s list
them down and know about each operator in detail.
Arithmetic operators
Comparison operators
Assignment operators
operator
Logical operators
Bitwise operators
Membership operators
Special operators
Identity operators
Membership operators
Arithmetic operators
Arithmetic operators are used for executing the mathematical functions in Python which include, addition,
subtraction, multiplication, division, etc
Right-hand Operand is
-Minus subtracted from the left- 20-10=10
hand operand.
Arithmetic operators
Multiplication It Multiplies the values on either side of the operands. 10*10 = 100
It divides the left-hand operand by the right-hand one and also returns a
% modlus 7%2 = 1
reminder.
5.0 / 2
Division that results in the whole number being adjusted to the left in 2.5
// Floor division
the number line. 5.0 //2
2.0
10 to the
** Exponent The left operand is raised to the power of the right power of 3
10**3=1000
FLOOR DIVISION
Floor division is a normal division operation, except it returns the largest possible integer. This integer can either be
less than the normal division output or equal to it.
The floor function is signified by the ⌊ ⌋ symbol in mathematical terms
Let us now understand the working of the Floor division operation. For example,
⌊36/5⌋
Step 1: Performing the division first. We will divide 36 by 5.
36 ÷ 5 = 7.2
Step 2: Now, we will perform the floor function on the value we get after division, i.e., 7.2.
⌊7.2⌋=7
.
FLOOR DIVISION
Floor division is an operation in Python that allows us to divide two numbers and rounds the resultant
value down to the nearest integer. The floor division occurs through the (//) operator.
a=543
b=32
print(a//b)
print(a/b)
output
16.
16.97
Arithmetic operators
x=10
y=20
print("x+y=",x+y)
print("x-y=",x-y)
print("x*y",x*y)
Output
x+y= 30
x-y= -10
x*y 200
Arithmetic operators
x=20
y=10
Output
print("x/y",x/y) x/y 2.0
x=-20 x/y -2.0
x/y -2.0
y=10 x/y 2.0
print("x/y",x/y)
x=20
y=-10
print("x/y",x/y)
x=-20
y=-10
print("x/y",x/y)
Arithmetic operators
x=9
y=2
Output
print("x%y=",x%y) x%y= 1
print("x//y=",x//y)) x//y= 4
x**y= 1000
x=10
y=3
print("x**y=",x**y)
Python Comparison(Relational) Operators
The name itself explains that this operator is used to compare different things or values with one
another. In Python, the Comparison operator is used to analyze either side of the values and decide the
relation between them. The comparison operator is also termed a relational operator because it explains
the connection between.
the
Python Comparison(Relational) Operators
We have different Comparison (Relational) operators. Let’s list them down and get to know each operator in
detail.
== Equal
!= Not Equal
> Greater Than
< Less Than
>= Greater Than or Equal to
<= Less Than or Equal
Python Comparison(Relational) Operators
5) Python(>=) greater than equal to (<=) less than equal to Comparison Operator
This Operator compares the right-hand operator with the left-hand one and if the right-hand one is greater
than the left-hand one, it returns True statement
x=10
y=3
Output
print("x<=y",x<=y) x<=y False
x>=y True
print("x>=y",x>=y))
Python Assignment Operators
The assignment operator is used to assign value to the event, property, or variable. We use this operator in
Python to assign values to variables. We have multiple Assignment operators. Let’s list them down and know
things better.
= Assign Value
+= Add AND
-= Subtract AND
*= Multiply AND
/= Divide AND
%= Modulus AND
**= Exponent AND
//= Floor Division
Python Assignment Operators
a=10
print(a)
a+=10
print("a=",a)
a*=10
print("a=",a)
b=5
b/=2
print("b=",b)
b//=2
print("b=",b)
Python Assignment Operators
b%=2
print("b=",b)
b**=2
print("b=",b)
c=15
c//=2
print("c=",c)
Python Assignment Operators
output
a= 20
a= 200
b= 2.5
b= 1.0
b= 1.0
b= 1.0
c= 7
AKTU Full Courses (Paid)
Download Gateway Classes Application
From Google Play store
All Subjects
Link in Description
PYTHON PROGRAMMING
operator
By PRAGYA RAJVANSHI
B.Tech, M.Tech( C.S.E)
Python logical Operators
Logical operators are used in any programming language to make decisions based on multiple conditions. In
Python, we use Logical operators to determine whether a condition is True or False by taking Operand values
as a base
0(false) 0 0 0 1 1
0 1 0 1 1 0
1(true) 0 0 1 0 1
1 1 1 1 0 0
Python logical Operators
x = 10>2
y = 20>4
print('x and y is',x and y)
print('x or y is',x or y)
print('not(x and y) is',not(x and y))
Output
x and y is True
x or y is True
not(x and y) is False
Python Bitwise operators
Bitwise operators are used in Python to perform the operations on binary numerals or bit patterns. It
operates bit by bit.
& Binary AND
| Binary OR
^ Binary XOR
~ Binary Ones Complement
<< Binary Left Shift
>> Binary Right Shift
Python logical Operators
0(false) 0 0 0 0 1 1
0 1 0 1 1 1 0
1(true) 0 0 1 1 0 1
1 1 1 1 0 0 0
Bitwise AND OPERATOR
4 0 0 0 0 0 1 0 0
10&4 0 0 0 0 0 0 0 0
Bitwise AND OPERATOR
a = 10
b=4
print(a & b)
Output
0
Bitwise OR OPERATOR
4 0 0 0 0 0 1 0 0
10I4 0 0 0 0 1 1 1 0
Bitwise OR OPERATOR
a = 10
b=4
print(a | b)
Output
14
Bitwise XOR OPERATOR
6 0 0 0 0 0 1 1 0
10^6 0 0 0 0 1 1 0 0
Bitwise XOR OPERATOR
a = 10
b=6
print(a ^ b)
Output
12
Bitwise ONES’ COMPLEMENT OPERATOR
~10 1 1 1 1 0 1 0 1
Bitwise XOR OPERATOR
a = 10
print(~a)
Output
-11
Bitwise left shift OPERATOR
a = 10
print(a <<1)
Print(a<<2)
Output
20
40
Bitwise right shift OPERATOR
a = 10
print(a >>1)
Print(a>>2)
Output
5
2
Python membership Operators
Identity operators are used to compare the objects if both the objects are actually of the same data type and
share the same memory location.
There are different identity operators such as
‘is’ operator – Evaluates to True if the variables on either side of the operator point to the same object and
false otherwise.
x=5
y=5
print(x is y)
Output
true
Identity Operators
string1 = "Hello"
string2 = "Hello“
Z=string1
print(string1 is string2)
print(id(string1))
print(id(string2))
Print(id)
Output
True
140025108758000
140025108758000
140025108758000
Identity Operators
list1 =[10,20,30]
list2 =[10,20,30]
print(list1 is list2)
print(id(list1))
print(id(list2))#is operator work only on integer and string
Output
False
140013677373632
140013677480128
Identity Operators
In Python, operators have different levels of precedence, which determine the order in which they are
evaluated. When multiple operators are present in an expression, the ones with higher precedence are
evaluated first. In the case of operators with the same precedence, their associativity comes into play,
determining the order of evaluation.
Operator precedence and associativity
Operator precedence and associativity
Operators Description Associativity
This is used in an expression with more than one operator with different precedence to determine which operation
to perform first..
Precedence of Python Operators
name="Alex"
age=0
if name=="Alex" or name=="john" and age>=2:
print("hello")
else:
print("bye")
Output
hello
Precedence of Logical Operators in Python
name="Alex"
age=0
if (name=="Alex" or name=="john“) and age>=2:
print("hello")
else:
print("bye")
Output
bye
Associativity of Python Operators
If an expression contains two or more operators with the same precedence then Operator Associativity is
used to determine. It can either be Left to Right or from Right to Left.
100/10*10
10*10
100
Associativity of Python Operators
print(100 / 10 * 10)
#left associative
print(5 - 2 + 3)#left associative
print(5 - (2 + 3))#()is higher precedence -,+
print(2 ** 3 ** 2)# ** is right associativity
Output
100.0
6
0
512
100 + 200 / 10 - 3 * 10
Operators Precedence and Associativity in Python
Operators Precedence and Associativity are two main characteristics of operators that determine the
evaluation order of sub-expressions in the absence of brackets.
100+200/10-3*10
100+20-3*10
100+20-30
120-30
90
expression = 100 + 200 / 10 - 3 * 10
print(expression)
Output 90.0
Non Associative Operators
In Python, most operators have associativity, which means they are evaluated from left to right or right
to left when they have the same precedence. However, there are a few operators that are non-
associative, meaning they cannot be chained together.
a=5
b = 10
c = 15
a = b = (a < b) += (b < c)
Output
throw an error
Non Associative Operators
#If the operator += follows associativity answer will shown otherwise error will be raised
a = b = c += 2
note
Link in Description
PYTHON PROGRAMMING
Type conversion
By PRAGYA RAJVANSHI
B.Tech, M.Tech( C.S.E)
AKTU QUESTION
The act of changing an object’s data type is known as type conversion. The Python interpreter
automatically performs Implicit Type Conversion.
Python prevents Implicit Type Conversion from losing data. The user converts the data types of objects
using specified functions in explicit type conversion, sometimes referred to as type casting. When type
casting, data loss could happen if the object is forced to conform to a particular data type.
Two type of type conversion is there –
Implicit type
Explicit type(type casting)
Implicit Type Conversion in Python
In Implicit type conversion of data types in Python, the Python interpreter automatically converts one data
type to another without any user involvement
x =10
print("x is type of",type(x)) Output
x is type of <class 'int'>
y =10.6
y is type of <class 'float'>
print("y is type of",type(y)) 20.6
z is of type <class 'float'>
z=x + y
print(z)
print("z is of type",type(z))
Explicit Type Conversion in Python
In Explicit Type Conversion in Python, the data type is manually changed by the user as per their
requirement. With explicit type conversion, there is a risk of data loss since we are forcing an expression to
be changed in some specific data type.
Explicit Type Conversion in Python
f=float(s)
print("after converting to float from string",f)
Explicit Type Conversion in Python
s="4“
c=ord(s)
print("after converting string to integer",c)#Ascii value of 4 IS 52
c=hex(56)
print("after converting integer to hexadecimal",c)
c=oct(56)
print("after converting integer to octadecimal",c)
Output
after converting string to integer 52
after converting integer to hexadecimal 0x38
after converting integer to octadecimal 0o70
python type conversion using tuple(), set(), list()
s = 'python'
c=tuple(s)
print("after converting string to tuple",c)
print(type(c))
c= set(s)
print("after converting string to set",c)
print(type(c))
c=list(s)
print("after converting string to set",c)
print(type(c))
python type conversion using tuple(), set(), list()
OUTPUT
after converting string to tuple ('p', 'y', 't', 'h', 'o', 'n')
<class 'tuple'>
after converting string to set {'h', 'p', 'y', 'n', 't', 'o'}
<class 'set'>
after converting string to set ['p', 'y', 't', 'h', 'o', 'n']
<class 'list'>
Convert ASCII value to characters
a = chr(76)
b = chr(77)
print(a)
print(b)
OUTPUT
L
M
Python code to demonstrate Type conversion using dict(), complex(), str()
dict(): This function is used to convert a tuple of order (key, value) into a dictionary.
str(): Used to convert an integer into a string.
complex(real,imag) : This function converts real numbers to complex(real,imag) number.
Python3
Python code to demonstrate Type conversion using dict(), complex(), str()
a=1
b=2
tup = (('a', 1) ,('f', 2), ('g', 3))
c = complex(1,2)
print ("After converting integer to complex number : ",c)
c = str(a)
print ("After converting integer to string : ",c)
c = dict(tup)
print ("After converting tuple to dictionary :”,c)
Python code to demonstrate Type conversion using dict(), complex(), str()
Output
After converting integer to complex number : (1+2j)
After converting integer to string : 1
After converting tuple to dictionary : {'a': 1, 'f': 2, 'g': 3}
AKTU Full Courses (Paid)
Download Gateway Classes Application
From Google Play store
All Subjects
Link in Description
PYTHON PROGRAMMING
Python’s programming cycle is dramatically shorter than that of traditional programming cycle.
In Python, there are no compile or link steps.
Python programs simply import modules at runtime and use the objects they contain. Because of this,
Python programs run immediately after changes are made.
In cases where dynamic module reloading can be used, it is even possible to change and reload parts of a
running program without stopping it at all.
Python’s impact on the programming cycle is as follows:
p Programming cycle for python
p Programming cycle for python
Since Python is interpreted, there is a rapid turnaround after program changes. And because Python’s
parser is embedded in Python-based systems, it is easy to modify programs at runtime.
p What is IDE
An integrated development environment (IDE) is a software application that helps programmers develop
software code efficiently. It increases developer productivity by combining capabilities such as software
editing, building, testing, and packaging in an easy-to-use application. Just as writers use text editors and
accountants use spreadsheets, software developers use IDEs to make their job easier.
p Why IDE is important ?
PyCharm
Spyder
Pydev
IDLE
VISUAL STUDIO
p pyCharm
PyCharm is a hybrid platform developed by JetBrains as an IDE for Python. It is commonly used for Python
application development. Some of the unicorn organizations such as Twitter, Facebook, Amazon, and
Pinterest use PyCharm their Python IDE as
Features
1. Intelligent Code Editor:
Code Navigation:
It helps developers in editing and enhancing the code with less effort and time.
With code navigation, a developer can easily navigate to a function, class, or file.
A programmer can locate an element, a symbol, or a variable in the source code within no time.
Using the lens mode, further, a developer can thoroughly inspect and debug the entire source code.
Refactoring
It has the advantage of making efficient and quick changes to both local and global variables.
Refactoring in PyCharm enables developers to improve the internal structure without changing the
external performance of the code.
.
p pyCharm
Spyder is widely used for data science works. It is mostly used to create a secure and scientific environment
for Python. Spyder Python uses PyQt (Python plug-in) which a developer can add as an extension.
•Features of Spyder :
It has good syntax highlighting and auto code completion
Spyder Python explores and edits variables directly from GUI.
It performs very well in multi-language editor.
p SPYDER
Features of Spyder :
Availability of breakpoints (debugging and conditional breakpoints)
Automatic colon insertion after if, while, etc
p PYDEV
PyDev :
PyDev is an open-source integrated development environment (IDE) for Python.
It is designed to provide a complete development environment for Python programmers.
Also, it is built on top of the Eclipse platform and supports various features like debugging, code analysis,
code completion, and much more.
PyDev is compatible with all the major operating systems like Windows, Linux, and Mac OS X, making it a
popular choice among developers..
p PYDEV
Code completion: PyDev provides intelligent code completion. With the help of this, we can write code
faster and with fewer errors. It suggests the available methods and variables for a particular object or
module.
Debugging: PyDev has a built-in debugger. It allows us to step through our code and identify and fix errors
quickly.
Code analysis: PyDev performs static code analysis. It is used to identify potential errors and provide
suggestions for improvement, which can help us write better code.
p PYDEV
Multi-platform support: PyDev is compatible with all major operating systems, including Windows, Linux,
and Mac OS X, making it a popular choice among developers.
Integration with Eclipse: PyDev is built on top of the Eclipse platform, which provides a rich set of features
for development, including support for other programming languages and version control systems.
Plugins: PyDev supports plugins, which can extend its functionality to support additional features, such as
Django and Flask web frameworks.
p IDLE
IDLE :
IDLE is a basic IDE mainly used by beginner level developer.
IDLE Python is a cross-platform IDE, hence it increases the flexibility for users.
It is developed only in Python in collaboration with Tkinter GUI toolkit.
The feature of multi-window text editor in IDLE has some great functions like smart indentation, Python
colorizing, and undo option
p IDLE
IDLE :
Python IDLE's code editor has features like syntax highlighting and code completion that make it simpler
and faster to write Python programmers.
Python IDLE has a built-in debugger that enables programmers to walk through their code and find faults
and problems.
Python IDLE may be used on Linux, macOS, and Windows thanks to its cross-platform nature.
Python IDLE is included with the Python installation, thus users don't need to install any more programmes
in order to begin coding in Python
p VISUAL STUDIO
Visual studio : It enables development for various platforms and has its own marketplace for extensions.
Features of visual studio :
i. It supports Python coding in visual studio, debugging, and other activities.
ii. It has both paid and free versions in the market with great features.
A visual studio code is a lightweight software application with a powerful source code editor that runs on
the desktop. It is a free source code editor developed by Microsoft for Windows, Mac OS and Linux. It is a
software editor that has a rich extension of various languages like C++, C+, C, Java, Python, PHP, Go, etc. and
runtime language extensions such as .NET and Unity. It is easy to edit, build, syntax highlighting, snippets,
code refactoring and debugging.
AKTU Full Courses (Paid)
Download Gateway Classes Application
From Google Play store
All Subjects
Link in Description
PYTHON PROGRAMMING
Q3 In some language every statement end with a semicolon(;) what happen when AKTU 2019-20
you put a semicolon at the end of python statement
Q5 What is python? How python is interpreted? What are the tools to find bugs or AKTU 2019-20
perform static analysis AKTU 2017-18
python is considered as interpreted language
compilation: In this process, the source code is translated into machine code or bytecode ahead of time. The
resulting compiled code can be executed directly without any further processing. Python uses a compiler to
transform the source code into bytecode, which can be executed by the Python virtual machine. This is how
Python code is executed in environments like PyCharm, Visual Studio Code, or other integrated development
environments (IDEs) that use Python’s static analysis tools.
Interpretation: In this process, the source code is interpreted and executed directly by the interpreter at
runtime. When you run a Python script from the command line or an interactive shell, the interpreter reads
the source code and executes it line by line. This is how Python code is executed in interactive environments
like Jupyter notebooks, or in web applications where Python code is executed on the server side.
python is considered as interpreted language
Python’s compilation and interpretation work together to provide a flexible and dynamic programming environment.
When Python code is compiled, the resulting bytecode can be cached and reused for faster execution in the future.
This also allows for some level of static analysis and optimization of the code. When Python code is interpreted, it
allows for rapid development and debugging, and provides a more interactive programming experience
Advantages of Interpreted Language
Portability: Interpreted languages are typically platform-independent, which means that they can run on
different operating systems without modification. This is because the interpreter itself is usually written
in a low-level language that is compiled for each platform.
Easy to learn and use: Interpreted languages typically have simple syntax and a smaller set of language
constructs, making them easier to learn and use than compiled languages
Rapid development: Because there is no need to compile or link the code before running it, interpreted
languages offer a faster development cycle than compiled languages. Changes to the code can be tested
and seen immediately, which is especially useful in a development environment.
Advantages of Interpreted Language
Flexibility: Interpreted languages are often more flexible than compiled languages, as they allow for dynamic
typing and more dynamic programming constructs such as reflection and introspection. This can make it
easier to write code that adapts to changing requirements or situations.
Debugging: Debugging can be easier in an interpreted language because error messages often include
detailed information about the line of code where the error occurred. Additionally, many interpreted
languages include debugging tools that allow developers to step through code and inspect variables at
runtime.
Interoperability: Interpreted languages can often interoperate with other languages more easily than
compiled languages. For example, Python can call C code using the ctypes module, and JavaScript can be
embedded in HTML pages
Disadvantages of Interpreted Language
Slower execution speed: Interpreted languages are generally slower than compiled languages because
the code is translated into machine instructions on-the-fly at runtime, rather than being compiled ahead
of time into optimized machine code. This can make them less suitable for applications that require high
performance, such as video games or scientific simulations.
Lack of static type checking: Interpreted languages often use dynamic typing, which means that variable
types are determined at runtime rather than being declared in advance. This can make it harder to catch
errors related to type mismatches or incorrect function calls until runtime.
Security concerns: Interpreted languages can be more vulnerable to security issues such as cross-site
scripting (XSS) or SQL injection attacks. This is because the code is executed in the context of the
interpreter, which can make it easier for attackers to exploit vulnerabilities in the interpreter itself.
python as a Interpreted Language
A – The Python interpreter reads the source code line by line and then executes each line of code one at a
time. It translates the source code into bytecode, which is then executed by the Python virtual machine.
Q2 – Can Python be compiled?
A – Yes, Python can be compiled into bytecode or into native machine code.
Q3 – Is Python slower than compiled languages like C or C++?
A – Yes, Python is generally slower than compiled languages like C or C++. This is because the interpreter has
to translate the source code into bytecode at runtime, which takes more time than compiling the code
ahead of time into machine code.
What happen when you put semicolon at the end of python statement
The common meaning of a semicolon(;) in various programming languages is to end or discontinue the
current statement. In programming languages such as C, C++, and Java, it is necessary to use a semicolon
to end a line of code. However, this is not the case with Python.
A semicolon in Python signifies separation rather than termination. It allows you to write multiple
statements on a single line
Print(“hi”);print(“hello”);print(“bye”)
Output
hi
hello
bye
What happen when you put semicolon at the end of python statement
In this example, we’ll try to loop through two statements separated by a semicolon and see if the loop
prints both or just the first one
for I in range (4):
print(‘hi’);
Print(“hello”);
OUTPUT
Hi
Hello
Hi
Hello
Hi
Hello
Hi
Hello
What happen when you put semicolon at the end of python statement
Python will throw an error if you use a semicolon to separate a normal expression from a block statement i.e loop.
print('Hi') ; for i in range (4): print ('Hello')
Output
Error
Conclusion
A semicolon in Python is mostly used to separate multiple statements written on a single line.
A semicolon is used to write a minor statement and reserve a bit of space like name = Marie; age = 23;
print(name, age)
The use of semicolons is very “non-pythonic” and it is recommended not to be used unless you
desperately need it.
What type of language is python
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics developed by
Guido van Rossum. It was originally released in 1991. Designed to be easy as well as fun, the name "Python" is a nod to
the British comedy group Monty Python.
Element of python
Writing efficient, reliable, and secure code is highly valued in software development.
With the popularity of Python programming language skyrocketing in recent years, it has become
increasingly important for developers to ensure their code is error-free, secure, and optimized.
However, manually inspecting every line of Python code can be daunting and time-consuming. That is
where static code analysis comes into play.
Static code analysis is the procedure of inspecting application source code without executing it.
It detects potential errors, security flaws, dependencies, bugs, and other issues in the codebase.
Benefits of Using Static Code Analysis for Python
Pychecker and Pylint are the static analysis tools that help to find bugs in python.
Pychecker is an opensource tool for static analysis that detects the bugs from source code and warns
about the style and complexity of the bug.
Pylint is highly configurable and it acts like special programs to control warnings and errors, it is an
extensive configuration file Pylint is also an opensource tool for static code analysis it looks for
programming errors and is used for coding standard. it checks the length of each programming line. it
checks the variable names according to the project style. it can also be used as a standalone program, it
also integrates with python IDEs such as Pycharm, Spyder, Eclipse, and Jupyter
Pychecker can be simply installed by using pip package pip install Pychecker if suppose if you use python
3.6 version use upgrade pip install Pychecker --upgrade Pylint can be simply installed by using pip
package
pip install Pylint
AKTU Full Courses (Paid)
Download Gateway Classes Application
From Google Play store
All Subjects
Link in Description
PYTHON PROGRAMMING
On the division of two integers, we get On the division of two integers, we get
Division of Integers an integral value in Python 2. For a floating-point value in Python 3. For
instance, 7/2 yields 3 in Python 2. instance, 7/2 yields 3.5 in Python 3.
Integrated Language
• We can easily integrate it with other languages such as C, C++, etc. Hence, it is an integrated language.
Interpreted Language
• It uses an interpreter for converting the source code into machine code. This means that we execute the
python code line by line. Hence, it becomes easy to debug the error and solve it.
Huge Standard Library
• There are a very large number of libraries in python. These libraries contain predefined modules and
functions for certain tasks. Hence, it becomes easy for the programmer to develop the code since he
does not have to do all the things by himself. Moreover, the library is portable and cross-platform
compatible.
BOOLEAN EXPRESSION
Boolean expressions are the expressions that evaluate a condition and result in a Boolean value i.e true
or false. Ex: (a>b and a> c) is a Boolean expression. It evaluates the condition by comparing if 'a' is
greater than 'b' and also if 'a' is greater than 'c'. If both the conditions are true only then does the
Boolean expression result is true. If any one condition is not true then the Boolean expression will result
in false.
Boolean expressions are written using Boolean operators (and ) , (or) and (not)
Example:
1. (x>1) and (x<5) - returns true if both the conditions are true, i.e if the value of 'x' is between 1 and 5.
2. (x%x) or (x%1) - returns true if any one condition is true, i.e: either 'x' is divisible by itself OR if 'x' is
divisible by 1.
3. not (x==0) - returns true if the value of 'x' is other than 0. If the value of 'x' is 0 then it returns false
BOOLEAN EXPRESSION
x=10
z=(x>1) and (x<5)
print(z)
Output
False
x=10
y=12
print(x>22 or y<25)
Output
true
BOOLEAN EXPRESSION
x=10
y=12
print(not (x>22 or y<25))
Output
false
p PEP
PEP (Python Enhancement Proposal) is like a suggestion box for the Python programming language. It's a
way for people who work on Python to suggest new ideas or changes to Python, and it helps everyone
discuss, plan, and decide if those ideas are good for Python.
Just like when you have an idea, you write it down and share it with others, in the Python community, PEPs
are used to write down and share ideas for making Python better. They explain what the idea is, why it's a
good idea, and how it would work. Then, the Python community talks about it, and if most people agree it's
a good idea, it might become a part of Python in the future.
In simple terms, a PEP is a way to suggest, discuss, and plan improvements or new features for Python, just
like a suggestion box for your favorite programming language.
p PEP
PEP stands for "Python Enhancement Proposal." PEPs are design documents that provide information to
the Python community or describe a new feature or improvement in the Python programming language.
They are the primary mechanism for proposing and discussing changes to Python's core language and
standard library.
The PEP process is used to suggest and debate ideas, document the design and implementation of new
features, and, in many cases, reach a consensus within the Python community before a change is accepted
and incorporated into Python. PEPs cover a wide range of topics, from language enhancements to the
development process itself
p PEP
PEPs are typically authored and submitted by Python developers and enthusiasts and go through a review
and approval process. Some common types of PEPs include:
PEP8 , PEP20, PEP257,PEP333 etc
p PEP 8
PEP 8 is a Python Enhancement Proposal that outlines the style guide for writing clean and readable
Python code. It provides a set of conventions and guidelines to make Python code consistent and easy to
understand. Following PEP 8 recommendations is considered good practice and helps ensure that Python
code is more accessible and maintainable.
Here are some key points from PEP 8 in plain language:
Indentation: Use 4 spaces for each level of indentation. Don't use tabs. Consistent indentation makes your
code look neat and organized.
Maximum Line Length: Limit each line of code to a maximum of 79 characters for code, and 72 character
p PEP 8
Whitespace: Use a single space after commas, colons, and semicolons, but not immediately before. Avoid
extraneous whitespace (e.g., at the end of lines).
Comments: Write comments to explain complex or non-obvious parts of your code. Comments should be
clear and concise. Use complete sentences and follow a consistent style for writing comments.
Naming Conventions: Use descriptive variable and function names. Variable names should be lowercase
with words separated by underscores (e.g., my_variable_name). Function names should be lowercase with
words separated by underscores (e.g., my_function_name()).
Blank Lines: Use blank lines to separate functions, classes, and blocks of code inside functions for better
readability.
p PEP 8
Whitespace in Expressions and Statements: Avoid extraneous whitespace within expressions and
statements. For example, don't put spaces immediately inside parentheses or square brackets.
Encoding: Always specify the source code encoding as UTF-8 at the top of your Python files to ensure
proper character encoding.
Documentation Strings (Docstrings): Write docstrings for modules, classes, and functions to explain their
purpose and usage.
Imports: Import statements should usually be on separate lines and should come at the top of your file.
Imports should be grouped in the following order: standard library imports, related third-party imports, and
local application/library specific imports.
p PEP 8
Following PEP 8 helps maintain a consistent coding style across Python projects, making it easier for
developers to collaborate and understand each other's code. It promotes clean, readable, and more
maintainable Python code. Most Python developers adhere to PEP 8 recommendations to create code that is
not only functional but also easy to work with.
p How memory is managed in python
In In Python, memory management, including the allocation and deallocation of memory on the private
heap, is handled by the Python memory manager. Python uses a private heap to manage memory, and it
employs a system of reference counting along with a cyclic garbage collector to keep track of and clean up
memory when it's no longer in use.
Here's how memory management works in Python:
Private Heap: Python uses a private heap to store all its data structures and objects. The private heap is
managed by the Python memory manager.
Reference Counting: Each object in Python has a reference count associated with it. The reference count is the
number of references or pointers to an object. When an object's reference count drops to zero, it means there
are no references to that object, and it is considered to be eligible for deallocation
p How memory is managed in python
a=100
b=100
python memory manager creates only one object i.e "100" and reference count is "2". Whenever a new
object is created pyhon manager will checks the memory for the object. If object already exists python
manager will not create new object instead it references the name to the object and increases the reference
counter of the object.
Every python object holds three things
object type
object value
object reference counter
p How memory is managed in python
Type int
Value 100
reference count 2
reference a, b
Example
a = 100
print(id(a)) # 10914336
b = 100 print(id(b)) # 10914336
print(id(a) == id(b)) # True
p How memory is managed in python
Automatic Memory Allocation: When you create a new object in Python (e.g., a variable, list, dictionary, etc.),
the memory for that object is allocated from the private heap. Python takes care of this memory allocation
automatically.
Memory Deallocation: When the reference count of an object drops to zero (i.e., there are no more references
to the object), Python's memory manager deallocates the memory associated with that object. This process is
automatic and transparent to the programmer.
p How memory is managed in python
Garbage Collection: In addition to reference counting, Python uses a cyclic garbage collector to detect and
clean up objects with circular references (objects referencing each other in a cycle) that may not be detected by
simple reference counting. This cyclic garbage collector identifies and reclaims memory for objects that are no
longer reachable.
Garbage collection is the process of removing the unused variables/names and freeing the memory.
In python garbage collection is performed based on the reference count mechanism. Whenever the object is
created the python will increases the reference count of the object by one. Whenever the reference is removed
then it decreases the reference count by one. Garbage collector periodically checks and removes the objects
from memory whose reference count is zero.
p How memory is managed in python
a = 100
b = 100 # reference count of object 100 is 2
del a # reference count of object 100 is 1
del b # reference count of object 100 is 0
# So, garbage collector will remove the object 100 from the memory..
p How memory is managed in python
Memory Leaks: In some cases, if you create circular references or maintain references to objects
unnecessarily, you can encounter memory leaks. These are situations where objects are not properly
deallocated because their reference count never reaches zero. It's essential to be mindful of your code and
ensure that you manage references appropriately to prevent memory leaks..
AKTU Full Courses (Paid)
Download Gateway Classes Application
From Google Play store
All Subjects
Link in Description
PYTHON PROGRAMMING
Version of python
Keywords and identifiers
By PRAGYA RAJVANSHI
Print()
B.Tech, M.Tech( C.S.E)
p AKTU QUESTION
..
Q1 How memory is managed in python? Explain PEP8 AKTU 2019-20
Q4 Discuss why python is interpreted language. Explain the history and features of AKTU 2022-23
python while comparing python 2 and python 3 version
p Print()
. Python print() function prints the message to the screen or any other standard output device
syntax : print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)
Parameters:
value(s): Any value, and as many as you like. Will be converted to a string before printed
sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than one.Default :’ ‘
end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’
file : (Optional) An object with a write method. Default :sys.stdout
flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False). Default: False
Return Type: It returns output to the screen.
p Print()
OUTPUT
GATEWAY CLASS
HELLO GUYS**BYE
how are you$$
p Print()
By default, print() separates the items by spaces. The optional sep= parameter sets a different separator text
print(12, 24, -2, sep=':')
print('but', 'not', 'including', sep='**')
print('but', 'not', 'including', sep=' ')
print('hi','hello')
print("gateway","classes", sep='')
Output
12:24:-2
but**not**including
but not including
hi hello
gatewayclasses
p Print()
Python Keywords are some predefined and reserved words in Python that have special meanings. Keywords are
used to define the syntax of the coding. The keyword cannot be used as an identifier, function, or variable name.
All the keywords in Python are written in lowercase except True and False
Rules for Keywords in Python
Python keywords cannot be used as identifiers.
All the keywords in Python should be in lowercase except True and False.
import keyword
print(keyword.kwlist)
p keyword
Keyword.kwlist
This is a predefined variable of keyword module that stores all the keyword of python .Thus it can be used to
display all the keyword of just by calling it
Python provides an in-built module keyword that allows you to know about the reserved keywords of python.
The keyword module allows you the functionality to know about the reserved words or keywords of Python and
to check whether the value of a variable is a reserved word or not. In case you are unaware of all the keywords of
Python you can use this module to retrieve this information. Also, it helps you to check whether a word is a
keyword or not just by using its functions on Python shell mode
p keyword
keyword.iskeyword(parameter)
This function returns True if the parameter passed is a Python keyword else returns False. The parameter can be a
string or a variable storing a string. It accordingly compares the parameter with Python keywords defined in the
language and returns the output.
p keyword
import keyword
s="if“
t="in“
u="hello“
print(s,"is a keyword in python",keyword.iskeyword(s))
print(t,"is a keyword in python",keyword.iskeyword(t))
print(u,"is a keyword in python",keyword.iskeyword(u))
print("lambda is a keyword",keyword.iskeyword("lambda")
)print("print is a keyword",keyword.iskeyword("print"))
p keyword
output
if is a keyword in python True
in is a keyword in python True
hello is a keyword in python False
lambda is a keyword True
print is a keyword False
p IMPORT
Import in python is similar to #include header_file in C/C++. Python modules can get access to code from another
module by importing the file/function using import. The import statement is the most common way of invoking the
import machinery, but it is not the only way
import module_name
When the import is used, it searches for the module initially in the local scope by calling __import__() function.
The value returned by the function is then reflected in the output of the initial code.
import math
pie = math.pi
print("The value of pi is : ",pie)
The value of pi is : ', 3.14159265358979
p IMPORT
In the above code module, math is imported, and its variables can be accessed by considering it to be a class and
pi as its object.
The value of pi is returned by __import__(). pi as a whole can be imported into our initial code, rather than
importing the whole module.
from math import pi
print(pi)
p IMPORT
Python Identifier is the name we give to identify a variable, function, class, module or other object.
AKTU Full Courses (Paid)
Download Gateway Classes Application
From Google Play store
All Subjects
Link in Description
COMPUTER ORGANIZATION AND ARCHITECTURE (BCS302)
OUTPUT QUESTION
By PRAGYA RAJVANSHI
B.Tech, M.Tech( C.S.E)
Output Question
at is Stack Organization?
x=6 x=5 x=5 x-=y
y=3 y=4 y=4 print(x)
print(x/y) print(x % y) x+=y x/=y
output Output print(x) print(x)
2.0 1 x*=y x%=y
x=6 x=5 print(x) print(x)
y=3 y=7 Output Output
print(x//y) print(x%y) 9 32
output Output 36 8.0
2 5 0.0
Output Question
at is Stack Organization?
x=3 x=5 x=True x=2*4+7
y=5 y=6 y=False print(x)
print(x==y) print(x>y) print(x and y) y=2*(4+7)
print(x!=y) print(x<y) print(x or y) print(y)
Output print(x>=y) print(not x) output
False print(x<=y) print(not y) 15
True Output Output 22
False False
True True
False False
True True
Output Question
at is Stack Organization?
x='24'+'45‘ x=input("enter a number") Output
print(x) print(type(x)) enter a number4
y=24+45 y=int(input("enter a integer")) <class 'str'>
print(y) print(type(y)) enter a integer4
Output z=float(input("enter a number")) <class 'int'>
2445 print(type(z)) enter a number4
69 <class 'float'>
Output Question
at is Stack Organization?
x=y=z=300 x,y,z=2,3,4 x=10*4+7-6/6
print("x =",x) print("x=",x) print(x)
print("y=",y) print("y=",y) output
print("z=",z) print("z=",z) 46.0
Output Output
x = 300 x= 2
y= 300 y= 3
z= 300 z= 4
Output Question
at is Stack Organization?
x=3/3=4/4//5*6 x=3/34/4//5*6 x=2*6**2
print(x) print(x) print(x)
Output 0.0 Output
File "/home/main.py", line 1 72
x=3/3=4/4//5*6
^^^
SyntaxError: cannot assign
to expression
AKTU Full Courses (Paid)
Download Gateway Classes Application
From Google Play store
All Subjects
Link in Description