Python Notes for Degree Students_1st Unit
Python Notes for Degree Students_1st Unit
Degree Students
UNIT-I
1. Introduction to Python
2. Features of Python
3. Executing python program using command line window and IDLE
graphics window, Python Virtual Machine
4. Identifiers
5. Reserved Keywords
6. Variables, Comments in Python
7. Input , Output and Import Functions
8. Operators
9. Data Types and Operations
10. int, float, complex, Strings, List, Tuple, Set, Dictionary
11. Mutable and Immutable Objects
12. Data Type Conversion, Illustrative programs
Low level languages are two types one is machine language and other one is assembly language.
Program Structure of
procedure language
Compilation structure of C language
1.4: High level language:
A high-level language (HLL) is a programming language such that enables a programmer to write
programs that are more or less independent of a particular type of computer.
Such languages are considered high level, because they are closer to human languages and further
from machine languages.
English like computer language and that supports object oriented programming is called as high
level programming language
Object oriented programming can be defined as a programming model which is based upon the concept
of objects. Objects contain data in the form of attributes and code in the form of methods. In object
oriented programming, computer programs are designed using the concept of objects that interact with
real world. Object oriented programming languages are various but the most popular ones are class-
based, meaning that objects are instances of classes, which also determine their types.
Languages used in Object Oriented Programming:
Java, C++, C#, Python, PHP, JavaScript, Ruby, Perl, Objective-C, Dart, Swift, Scala.
Step 3: Click “Downloads” Link at the top of the page, Click on “Download Python 3.9.3 or 3.10.3
Step 4: When the installation window comes up, click “Install Now”
You can choose to “Add Python 3.7.3 to PATH”
Note: Depending on how Windows is set up, you might need to provide an administrator password to
install on your system at this point.
You can choose to “Customize Installation” if you want, especially if you want to install to a location
other than the default one shown. Generally I recommend installing to the default location unless you
have a problem doing so.
In any case, you might want to note the location of the installation in case you have difficulty later. If
you are specifying the location yourself, put it in a location you are likely to easily find/remember.
Step 6: Whenever you click on install button the process will begins
2.4: How to open python IDLE Software and Execute the program:
1
Step 1: click on windows search bar and type IDLE, then click on open
2
1
3
1
Step 2: After click on open a shell window will open, beginner should remind that was not a program plane,
it is called as result plane or shell or caluculator. So you will not write your program here.
Step 3: Go to file option on menu bar.
Step 6: Now you can write your program, I will write an example program
Step 7: After writing the program, the very next step is execution, for execution you can click on run option
and then click on run module.
Step 8: Now it asks for save the program, then you click on ok.
Step 9: Now you can give any name to your program and select program path, then click on save.
Step 10: Earlier we discussed about shell plane, now you got answer in this plane.
2.5: How to execute python program using notepad
Step 1: Go to windows search and type notepad then click on open.
Step 4: Now save the file, for saving the file, go to file and click on save
Step 5: you should follow some rules while save the file, that is:
1) File name extension should be .py only
Ex: I want give my program name as sampleprog
Then I will give my file name as sampleprog.py
2) Set file type as all files
3) Remember the drive name and folder name while saving the file
Step 6: Now go to windows search and type cmd, then open command prompt
Step 7: A black screen will appear, now type the drive name where the program saved.
Ex: I saved my program in E drive, so I type E: then click on enter
Step 8: you enters in saved drive, now you will enter in folder, where the program saved
Ex: I saved in my python programs folder, so I can type command like this
cd my python programs then click on enter
step 9: You entered in saved folder, now type saved program file name with .py extension
Ex: I saved file name as sampleprog.py
So I can type sampleprog.py then click on enter
Step 10: Now you got answer
2.6: How to execute python program command prompt or command line window
Note: before executing the python program in command prompt, everyone aware that, you should install
any of python software like IDLE. Otherwise you couldn’t run python program
Step 1: go to windows search and type cmd, then open command prompt
Step 2: type python then click on enter
Step 3: if you install python software properly, you will get details regarding that version of python
software
Step 4 : Now you can write any program execute it
The draw back of the command prompt programming is we couldn’t save files, its like shell
plane
2.7: Python Tokens
1) Identifiers
2) Variables
3) Keyword
4) Data types
5) Operators
2.8: Identifier
Identifier is nothing but user defined words or a word used by the programmer
(or)
Giving a name to the variable or class or function in python is called as identifiers
2.9: Variables
A Variable is an identifier which allocates some memory
(Or)
In computer programming, a variable is an abstract storage location paired with an associated symbolic
name, which contains some known or unknown quantity of information referred to as a value; or in simpler
terms, a variable is a container for a particular set of bits or type of data.
Detailed Explanation of
variable
In this topic, you’ll find a basic introduction to all Python keywords along with other resources that will be
helpful for learning more about each keyword.
Python keywords are special reserved words that have specific meanings and purposes and can’t be used
for anything but those specific purposes. These keywords are always available—you’ll never have to import
them into your code.
Python keywords are different from Python’s built-in functions and types. The built-in functions and types
are also always available, but they aren’t as restrictive as the keywords in their usage.
An example of something you can’t do with Python keywords is assign something to them. If you try, then
you’ll get a SyntaxError.
1) Go to IDLE
import keyword
keyword.kwlist
Programming reflects your way of thinking in order to describe the single steps that you took to solve a
problem using a computer. Commenting your code helps explain your thought process, and helps you
and others to understand later on the intention of your code. This allows you to more easily find
errors, to fix them, to improve the code later on, and to reuse it in other applications as well.
Commenting is important to all kinds of projects, no matter whether they are - small, medium, or
rather large. It is an essential part of your workflow, and is seen as good practice for developers.
Without comments, things can get confusing, real fast. In this article we will explain the various
methods of commenting Python supports, and how it can be used to automatically create
documentation for your code using the so-called module-level doc strings
Types of Comments
A comment in Python starts with the hash character, #, and extends to the end of the physical line. A hash
character within a string value is not seen as a comment, though. To be precise, a comment can be written
in three ways - entirely on its own line, next to a statement of code, and as a multi-line comment block.
Such a comment starts with a hash character (#), and is followed by text that contains further explanations
As already mentioned above, an entire comment block is also understood by Python. These comments
serve as in-line documentation for others reading your code, and explain things in more detail, usually It's
originally intended to be used for creating documentation (see more about this below), but it can also be
used for multi-line comments.
Note that the latter version needs to be enclosed in special quotation marks ( """ ) to work, and not hash
characters.
The role of Python Virtual Machine (PVM) is to convert the byte code instructions into machine code so
that the computer can execute those machine code instructions and display the final output. To carry out
this conversion, PVM is equipped with an interpreter. The interpreter converts the byte code into machine
code and sends that machine code to the computer processor for execution. Since interpreter is playing the
main role, often the Python Virtual Machine is also called an interpreter.
2.13. Data Types:
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.
Following are the standard or built-in data type of Python:
Numeric
Sequence Type
Boolean
Set
Dictionary
# INTEGER
p=2345678565436
print(type(p))
# in python any kind of rounded number is called as integer, so no need of confusion about short int, long int, etc.,
# FLOAT
s = 4654.765765
p = 0.4e7
t = 4.2e-4
# complext
s=5j+3
Creating String
Strings in Python can be created using single quotes or double quotes or even triple quotes.
print(s)
kakinada
venkat nagar'''
print(t)
Ans: apssdc
<class 'str'>
i am the student of pragati college
kakinada
venkat nagar
<class 'str'>
2) List:
Lists are just like the arrays, declared in other languages which is a ordered collection of data. It is very
flexible as the items in a list do not need to be of the same type.
Creating List
Lists in Python can be created by just placing the sequence inside the square brackets[].
Accessing elements of List
In order to access the list items refer to the index number. Use the index operator [ ] to access an item in
a list. In Python, negative sequence indexes represent positions from the end of the array. Instead of
having to compute the offset as in List[len(List)-3], it is enough to just write List[-3]. Negative indexing
means beginning from the end, -1 refers to the last item, -2 refers to the second-last item, etc.
Lists are also called mutable data types
# List Program
s=[2,3,5,56.67,3+7j,'apssdc'] # mutable
print(type(s)) # this instruction is used for to know the data type
print(s)
Tuple:
Just like list, tuple is also an ordered collection of Python objects. The only difference between tuple and
list is that tuples are immutable i.e. tuples cannot be modified after it is created. It is represented
by tuple class.
Creating Tuple
In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the
use of parentheses for grouping of the data sequence. Tuples can contain any number of elements and of
any datatype (like strings, integers, list, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky. Having one element in the
parentheses is not sufficient; there must be a trailing ‘comma’ to make it a tuple.
Tuples are also called immutable data types
# Tuple
s=(2,3,5,56.67,3+7j,'apssdc') # immutable
# Program
# Boolean program
a=True
b=False
print(type(a))
print(type(b))
b={2,3,5,56.67,3+7j,'apssdc'} # mutable
print(b)
Ans:
<class 'set'>
{2, 3, 5, 'apssdc', (3+7j), 56.67}
Dictionary in Python is an unordered collection of data values, used to store data values like a map,
which unlike other Data Types that hold only single value as an element, Dictionary holds key:value pair.
Key-value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is
separated by a colon :, whereas each key is separated by a ‘comma’.
Creating Dictionary
In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces,
separated by ‘comma’. Values in a dictionary can be of any datatype and can be duplicated, whereas keys
can’t be repeated and must be immutable. Dictionary can also be created by the built-in function dict().
An empty dictionary can be created by just placing it to curly braces{}.
Note – Dictionary keys are case sensitive, same name but different cases of Key will be treated distinctly.
# Dictionary program
b={'sow':34567,'bhanu':87834,'devi':75783457}
print(b)
Ans:
# Sample program
a=5
b=5
c=5
d=5
e=a+b+c+d
print(e)
Explanation: if we have same different variables with same values, then we use below method for reducing
lines in program, that method is:
# Sample program
a=b=c=d=5
e=a+b+c+d
print(e)
Note: Now you can observe above program has only 3 line with result, so this is another kind of giving input
2.15. Output:
Python provides the print() function to display output to the standard output devices.
print('3+4') # here 3+4 is a string data thats why we got the output 3+4
# any data is started with single or double quatation and ended with the same quotation
print('pragathi degree college') # any data is started with quatation and ended with same quotation
print('The value of 3+4 is', 3+4) # in this statement we give two kinds of data one is string data type and
# when we run this code, we got the output as string displayed as it is like what we given in the input
There is an optional argument called end that you can use to keep the print function from advancing to the next line.
Here is an example:
Of course, this could be accomplished better with a single print, but we will see later that there are interesting uses
for the end argument.
Sep=’ ‘ operator:
sep Python will insert a space between each of the arguments of the print function. There is an optional argument
called sep
365, short for separator, that you can use to change that space to something else. For example, using sep=':' would
separate the arguments by a colon and sep='##' would separate the arguments by two pound signs. One particularly
useful possibility is to have nothing inside the quotes, as in sep=''. This says to put no separation between the
arguments. Here is an example where sep is useful for getting the output to look nice:
Formatting Output
Formatting output in Python can be done in many ways. Let’s discuss them below
We can use formatted string literals, by starting a string with f or F before opening quotation marks or
triple quotation marks. In this string, we can write Python expressions between { and } that can refer to a
variable or any literal value.
Example: Python String formatting using F string
# Sample program
name = "Pragati"
We can also use format() function to format our output to make it look presentable. The curly
braces { } work as placeholders. We can specify the order in which variables occur in the output.
Example: Python string formatting using format() function
# Sample program:
a = 20
b = 10
sum = a + b
sub = a- b
Using % Operator:
We can use ‘%’ operator. % values are replaced with zero or more value of elements. The formatting
using % is similar to that of ‘printf’ in the C programming language.
%d – integer
%f – float
%s – string
%x – hexadecimal
%o – octal
add = num + 5
print("The sum is %d" %add)
Exponentiation Python uses ** for exponentiation. The caret, ^, is used for something else.
Integer division The integer division operator, //, requires some explanation. Basically, for positive numbers it
behaves like ordinary division except that it throws away the decimal part of the result. For instance, while 8/5 is 1.6,
we have 8//5 equal to 1. We will see uses for this operator later. Note that in many other programming languages
and in older versions of Python, the usual division operator / actually does integer division on integers.
Modulo The modulo operator, %, returns the remainder from a division. For instance, the result of 18%7 is 4 because
4 is the remainder when 18 is divided by 7. This operation is surprisingly useful. For instance, a number is divisible by
n precisely when it leaves a remainder of 0 when divided by n. Thus to check if a number, n, is even, see if n%2 is
equal to 0. To check if n is divisible by 3, see if n%3 is 0. One use of this is if you want to schedule something in a loop
to happen only every other time through the loop, you could check to see if the loop variable modulo 2 is equal to 0,
and if it is, then do that something. The modulo operator shows up surprisingly often in formulas. If you need to
“wrap around” and come back to the start, the modulo is useful. For example, think of a clock. If you go six hours
past 8 o’clock, the result is 2 o’clock. Mathematically, this can be accomplished by doing a modulo by 12. That is,
(8+6)%12 is equal to 2. As another example, take a game with players 1 through 5. Say you have a variable player
that keeps track of the current player. After player 5 goes, it’s player 1’s turn again. The modulo operator can be
used to take care of this:
player = player%5+1
Using randint is simple: randint(a,b) will return a random integer between a and b including both a and b. (Note that
randint includes the right endpoint b unlike the range function). Here is a short example:
#Sample program
x = randint(1,10)
The random number will be different every time we run the program.
sin(0) = 0.0
Built-in math functions There are two built in math functions, abs (absolute value) and round that are available
without importing the math module. Here are some examples:
print(abs(-4.3))
print(round(3.336, 2))
print(round(345.2, -1))
output: 4.3
3.37
350.0
The round function takes two arguments: the first is the number to be rounded and the second is the number of
decimal places to round to. The second argument can be negative.
>>> dir(math)
Output: ['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign',
'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'hypot', 'isinf', 'isnan', 'ldexp', 'log',
'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
This gives a list of all the functions and variables in the math module. You can ignore all of the ones that start with
underscores. To get help on a specific function, say the floor function, you can type help(math.floor). Typing
help(math) will give you help for everything in the math module.
# Sample Program:
import math
print(math.pi)
output: 3.141592653589793
import module_name.member_name
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.
# sample program
from math import pi
print(pi) # pi directly.
output: 3.141592653589793
from module_name import *
In the above code module, math is not imported, rather just pi has been imported as a variable.
All the functions and constants can be imported using *.
#sample program
from math import *
print(pi)
print(factorial(6))
output: 3.141592653589793
720
As said above import uses __import__() to search for the module, and if not found, it would raise ImportError
#sample program
import mathematics
print(mathematics.pi)
output:
Traceback (most recent call last):
File "C:/Users/GFG/Tuples/xxx.py", line 1, in
import mathematics
ImportError: No module named 'mathematics'
x = randint(1,100)
#Sample Program 2:
# generate trignometric function
from math import sin,pi,cos
output:
Pi is roughly 3.141592653589793
sin(0) = 0.0
sin(30) = -0.9880316240928618
sin(45) = 0.8509035245341184
sin(90) = 0.8939966636005579
cos(0) = 1.0
#Sample Program 3:
# generate factorial function
from math import factorial
print(factorial(s))
479001600
#Sample Program 4:
# generate square root function
from math import sqrt
r=sqrt(s)
print(r)
# another way to represent math function is (*), using this (*), it include all math functions, programmer
need not to specify the particular function
#Sample Program 5:
# generate any math function using import * method
from math import *
print(sin(s))
#Sample Program 6:
# generate any math function using import * method
from math import *
print(factorial(5))
output:120
#Sample Program 7:
# generate any math function using import * method
from math import *
print(pow(2,7))
output: 128.0
#Sample Program 8:
# generate any math function using import * method
# ciel will round the float value to single number
print(ceil(4.1))
output: 5
#Sample Program 9:
# generate any math function using import * method
# floor will eliminate the float number give before point value
print(floor(22/5))
output: 4
print(abs(-8.3))
print(round(3.456,2))
print(round(345.2,2))
Output: 8.3
3.46
345.2
import math
a=int(input())
print (math.copysign(a,b))
output: 10
-26
c = 10
d = 15
print (math.gcd(c,d))
output:
2.17. Operators:
Operators are used to perform operations on variables and values. Python Operators in general are used
to perform operations on values and variables. These are standard symbols used for the purpose of
logical and arithmetic operations. In this article, we will look into different types of Python operators.
Arithmetic operators
Logical operators
Bitwise operators
Assignment operators
Comparison or relative operators
Identity operators
Membership operators
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(fdiv)
print(mod)
print(p)
Output:
13
5
36
2.25
2
1
6561
For equation simplification mathematics follow BODMAS rule but in python mathematics follows
PEMDAS rule, so exact maths order in python as shown below:
order of operations (PEMD%DDAS)
Peranthesis -- ()
Exponential -- **
Multiplication -- *
Division -- /
Modulo -- %
Floor Division -- //
Addition -- +
Subtraction -- (-)
0
1
2
3
4
5
6
7
8
9
29 28 27 26 25 24 23 22 21 20
512 256 128 64 32 16 8 4 2 1
1 0 1 0 =10
1 0 0 0 1 1 =35
1 1 1 1 1 0 0 1 1 1 =999
Decimal Octal 4 2 1
Numbe Number
r
0 0 0 0 0
1 1 0 0 1
2 2 0 1 0
3 3 0 1 1
4 4 1 0 0
5 5 1 0 1
6 6 1 1 0
7 7 1 1 1
4 2 1
56
32 16 8 4 2 1
Binary 1 1 1 0 0 0
Octal = 70 7 0
(65)10 -->>( ? )8
65
256 128 64 32 16 8 4 2 1
Binary 0 0 1 0 0 0 0 0 1
Octal 1 0 1
Octal 1 0 1
Binary 0 0 1 0 0 0 0 0 1
64 32 16 8 4 2 1
Decimal 65
Octal to Decimal conversion system
34
32 16 8 4 2 1
Binary 0 0 1 0 0 0 1 0
Hexa decimal 2 2
E 5
Hex 1 1 1 0 0 1 0 1
Binary 128 64 32 16 8 4 2 1
Decimal 128+64+32+4+1=229
Hexa Decimal to decimal conversion
Bitwise and: -
A=5, B=6 do bitwise and operation to the two variables
a=1
b=5
print(a & b) # perform bitwise logical and operation like above shown
Output: 1
8 4 2 1
A=1 -- >> 0001
&
B=5 -- >> 0101
------------------------------------------
0001 = 1
Bitwise OR: -
a=1
b=5
Output: 5
8 4 2 1
A=1 -- >>0001
|
B=5 -- >>0101
------------------------------------------
0101
Bitwise X-OR: -
a=1
b=5
Output: 4
8 4 2 1
A=1 -- >>0001
^
B=5 -- >>0101
------------------------------------------
0100
Bitwise Not: -
a=5
Print(~a)
8 4 2 1
a=5 -- >>0 1 0 1 = -6
(0 1 0 1) + 1 = -6
A=18 128 64 32 16 8 4 2 1
A=18 1 0 0 1 0
A=36 1 0 0 1 0 0
A=72 1 0 0 1 0 0 0
A=144 1 0 0 1 0 0 0 0
Bitwise Right shift:-<<
a=5
print(a>>1)
a=5 -- >> 8 4 2 1
a>>1
A=5 128 64 32 16 8 4 2 1 d
A=5 0 1 0 1
A=2 0 0 1 0 1
A=1 0 0 0 1 0
#sample program:
a1 = 3
b1 = 3
a2 = 'andhrapradeshstateskilldevelopmentcorporation'
b2 = 'andhrapradeshstateskilldevelopmentcorporation'
a3 = [1,2,3]
b3 = [1,2,3]
print(a1 is b1)
print(a3[1] is b3[1])
print(a3 is b3)
Output:
False
True
True
True
False
y = [1,2,3,'b']
print('K' in x)
print('BCA' not in x)
print('g' not in x)
print(3 in y)
print('h' in y)
Output:
True
False
True
True
False
2.18. Data type conversion or Type Casting:
Python defines type conversion functions to directly convert one data type to another which is useful in day-to-
day and competitive programming. This article is aimed at providing information about certain conversion
functions.
There are two types of Type Conversion in Python:
1. Implicit Type Conversion
2. Explicit Type Conversion
Let’s discuss them in detail.
Implicit Type Conversion
In Implicit type conversion of data types in Python; the Python interpreter automatically converts one data type to
another without any user involvement. To get a more clear view of the topic see the below examples.
# sample program:
x = 10
print("x is of type:",type(x))
y = 10.6
print("y is of type:",type(y))
x=x+y
print(x)
print("x is of type:",type(x))
Output:
x is of type: <class 'int'>
y is of type: <class 'float'>
20.6
x is of type: <class 'float'>
As we can see the type of ‘x’ got automatically changed to the “float” type from the “integer” type. this is
a simple case of Implicit type conversion in python.
Explicit Type Conversion
In Explicit Type Conversion in Python, the data type is manually changed by the user as per their
requirement. Various forms of explicit type conversion are explained below:
1. int(a, base): This function converts any data type to integer. ‘Base’ specifies the base in which string
is if the data type is a string.
2. float(): This function is used to convert any data type to a floating-point number
#Sample program
# using int(), float()
# initializing string
s = "10010"
# printing string converting to int base 2
c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)
# printing string converting to float
e = float(s)
print ("After converting to float : ", end="")
print (e)
Output:
After converting to integer base 2 : 18
After converting to float : 10010.0
#sample program:
# initializing string
s = 'pragati'
# printing string converting to tuple
c = tuple(s)
print ("After converting string to tuple : ",end="")
print (c)
# printing string converting to set
d = set(s)
print ("After converting string to set : ",end="")
print (d)
# printing string converting to list
e = list(s)
print ("After converting string to list : ",end="")
print (e)
output:
After converting string to tuple : ('p', 'r', 'a', 'g', 'a', 't', 'i')
After converting string to set : {'p', 't', 'g', 'i', 'r', 'a'}
After converting string to list : ['p', 'r', 'a', 'g', 'a', 't', 'i']
dict() : This function is used to convert a tuple of order (key,value) into a dictionary.
str() : Used to convert integer into a string.
complex(real,imag) : This function converts real numbers to complex(real,imag) number.
# Sample Program
# initializing integers
a=1
b=2
# initializing tuple
tup = (('a', 1) ,('f', 2), ('g', 3))
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}
chr(number): This function converts number to its corresponding ASCII character.
# Convert ASCII value to characters
a = chr(76)
b = chr(77)
print(a)
print(b)
output:
L
M