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

Python Notes for Degree Students_1st Unit

Uploaded by

pstudenty123
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Python Notes for Degree Students_1st Unit

Uploaded by

pstudenty123
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 61

Python Notes for

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

1.1: Introduction to python


PYTHON is an interpreted, object oriented high-level programming language with dynamic semantics. Its
high level built in data structures, combined with dynamic typing and dynamic binding, make it very
attractive for rapid application development, as well as a scripting or glue language to connect existing
component together.

1.2: Types of Programming Languages


1. Low-level programming Language

2. Middle- Level Programming Language


3. High- Level Programming Language
1.2.1:Low level language
 Low level language abbreviated as LLL, are languages close to the machine level instruction set.
They provide less or no abstraction from the hardware.
 A low-level programming language interacts directly with the registers and memory.
 Since, instructions written in low level languages are machine dependent.
 Programs developed using low level languages are machine dependent and are not portable.
 Low level language does not require any compiler or interpreter to translate the source to machine
code.
 An assembler may translate the source code written in low level language to machine code.

Low level languages are two types one is machine language and other one is assembly language.

1.2.2: Machine level language


 Machine language is closest language to the hardware.
 It consists set of instructions that are executed directly by the computer. These instructions are
a sequence of binary bits.
 Each instruction performs a very specific and small task.
 An instruction written in machine language is machine dependent and varies from computer to
computer.
Example of machine language
1.2.3: Assembly Language
 Assembly language is an improvement over machine language.
 Similar to machine language, assembly language also interacts directly with the hardware.
 Instead of using raw binary sequence to represent an instruction set, assembly language
uses mnemonics.
 Mnemonics are short abbreviated English words used to specify a computer instruction.
 Each instruction in binary has a specific mnemonic.
 They are architecture dependent and there is a list of separate mnemonics for different computer
architectures.
 Examples of mnemonics are – ADD, MOV, SUB etc.

Assembly language coding pattern


In assembly language assembler converts user defined instruction to machine understandable instructions
i.e., 1s and 0s and vice versa

1.3: Middle level language


 We are called ‘C’ language as intermediate language
 Because it supports functional language and it doesn’t support to object oriented language
 It is a procedural language
 It supports high level programming environment

1.3.1: What is procedural language


Procedural Programming can be defined as a programming model which is derived from structured
programming, based upon the concept of calling procedure. Procedures, also known as routines,
subroutines or functions, simply consist of a series of computational steps to be carried out. During a
program’s execution, any given procedure might be called at any point, including by other procedures or
itself.
Example of procedural or middle level languages:
FORTRAN, ALGOL, COBOL, BASIC, Pascal and C.

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

1.5: Object Oriented Programming

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.

Levels of object oriented programming


1.6: What is meant by interpreter?
An interpreter is a program that translates a programming language into a comprehensible
language. –

 It translates only one statement of the program at a time.


 Interpreters, more often than not are smaller than compilers.

1.7: Difference between compiler and interpreter:

1.8: Invention of python:


 Python is invented by Guido van Rossum
 Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde & Informatica
(CWI) in the Netherlands as a successor to the ABC language (itself inspired by SETL), capable of
exception handling and interfacing with the Amoeba operating system. Its implementation began in
December 1989.

1.9: Features of python:


 Easy to Learn and Use. Python is easy to learn and use. ...
 2) Expressive Language. Python language is more expressive means that it is more understandable
and readable.
 3) Interpreted Language. ...
 4) Cross-platform Language. ...(other OS)
 5) Free, Open source and community development.
 6) Object-Oriented Language.
 7) Extensible.(you can write some of your Python code in other languages like C++. This
makes Python an extensible language)
 8) Extensive support libraries(NumPy for numerical calculations, Pandas for data analytics etc.)
 9) Presence of third-party modules
 10) Dynamically typed language(No need to mention data type based on value assigned, it takes
data type)

2.0: Applications of Python


1) Web applications
2) Image based applications
3) Internet of things
4) Cad based applications
5) Enterprise applications
6) Artificial intelligence
7) Machine learning
8) GUI based desktop applications(Games,Scientific Applications)
9) Operating Systems

10) Language Development

2.1: MNCs that are used python:


1) Google(Components of Google spider and Search Engine)
2) Yahoo(Maps)
3) YouTube
4) Mozilla
5) Dropbox
6) Microsoft
7) Cisco
8) Spotify
9) Quora

2.2: Disadvantages of python


 Speed. Python is slower than C or C++. ...
 Mobile Development. Python is not a very good language for mobile development . ...
 Memory Consumption. Python is not a good choice for memory intensive tasks. ...
 Database Access. Python has limitations with database access . ...
 Runtime Errors.
2.3:How to Install Python IDLE Software:
Step 1: Click on Google chrome or any of your browser, type www.python.org on search bar

Step 2: Click “Downloads” Link at the top of the page

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

Step 7: After completing the process, click on close

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 4: click on new file


Step 5: Now an untitled file is opened, it is actual program plane, so you will write your program here.

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 2: Now an untitled blank notepad file has opened


Step 3: Now write your python program on notepad

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.8.1: Types of identifiers


 Variables
 Functions
 Class
 Object
 Files
 Package
2.8.2: Rules for declare identifiers
 Identifier must start with alphabet – abc=23
 Must not start with number – 123abc=45
 Must not contain special characters – 1@rt=45
 Only allow underscore – abc_de = 56
 Don’t give reserved or keywords – print=34

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

2.10: Reserved keywords:


Every programming language has special reserved words, or keywords, that have specific meanings and
restrictions around how they should be used. Python is no different. Python keywords are the fundamental
building blocks of any Python program.

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.

In python we have 33 keywords are there

2.10.1.How to find keywords:

1) Go to IDLE

2) Type the below instructions

import keyword

keyword.kwlist

3) then click on enter

4) now you will get list of keywords


2.11.Comments in python

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.

In the following sections I'll describe each type of comment.

2.11.1. Single-Line Comments

Such a comment starts with a hash character (#), and is followed by text that contains further explanations

2.11.2. Multi-Line Comments

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.

2.12. Python Virtual Machine:


We know that computers understand only machine code that comprises 1s and 0s. Since computer
understands only machine code, it is imperative that we should convert any program into machine code
before it is submitted to the computer for execution. For this purpose, we should take the help of a
compiler. A compiler normally converts the program source code into machine code.
A Python compiler does the same task but in a slightly different manner. It converts the program source
code into another code, called byte code. Each Python program statement is converted into a group of byte
code instructions. Then what is byte code? Byte code represents the fixed set of instructions created by
Python developers representing all types of operations. The size of each byte code instruction is 1 byte (or
8bits) and hence these are called byte code instructions. Python organization says that there may be newer
instructions added to the existing byte code instructions from time to time. We can find byte code
instructions in the .pyc file. Following Figure shows the role of virtual machine in converting byte code
instructions into machine code:

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

2.13.1.Number Data types:


In Python, numeric data type represent the data which has numeric value. Numeric value can be integer,
floating number or even complex numbers. These values are defined as int, float and complex class in
Python.
 Integers – This value is represented by int class. It contains positive or negative whole numbers
(without fraction or decimal). In Python there is no limit to how long an integer value can be.
 Float – This value is represented by float class. It is a real number with floating point representation.
It is specified by a decimal point. Optionally, the character e or E followed by a positive or negative
integer may be appended to specify scientific notation.
 Complex Numbers – Complex number is represented by complex class. It is specified as (real part) +
(imaginary part)j. For example – 2+3j
Note – type() function is used to determine the type of data type.

# INTEGER

s=1 # s is a variable name

print(type(s)) # this instruction is used for to know the data type

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

Ans: <class 'int'>


<class 'int'>

# FLOAT

s = 4654.765765

p = 0.4e7

t = 4.2e-4

print(type(s)) # this instruction is used for to know the data type

print(type(p)) # this instruction is used for to know the data type

print(type(t)) # this instruction is used for to know the data type

# in float numbers we have different kinds of numbers

Ans: <class 'float'>


<class 'float'>
<class 'float'>

# complext

s=5j+3

print(type(s)) # this instruction is used for to know the data type

Ans: <class 'complex'>

2.13.2. Sequence data Types:


In Python, 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
In Python, Strings are arrays of bytes representing Unicode characters. A string is a collection of one or
more characters put in a single quote, double-quote or triple quote. In python there is no character data
type, a character is a string of length one. It is represented by str class.

Creating String
Strings in Python can be created using single quotes or double quotes or even triple quotes.

# single line string generation


s = 'apssdc'

print(s)

print(type(s)) # this instruction is used for to know the data type

# multi line string generation

t= '''i am the student of pragati college

kakinada

venkat nagar'''

print(t)

print(type(t)) # this instruction is used for to know the data type

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)

Ans: <class 'list'>


[2, 3, 5, 56.67, (3+7j), 'apssdc']

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

print(type(s)) # this instruction is used for to know the data type


print(s)

Ans: <class 'tuple'>


(2, 3, 5, 56.67, (3+7j), 'apssdc')

Boolean Data type:


Data type with one of the two built-in values, True or False. Boolean objects that are equal to True are
truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be evaluated in
Boolean context as well and determined to be true or false. It is denoted by the class bool.
Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an error.

# Program

# Boolean program

a=True
b=False
print(type(a))
print(type(b))

ans: <class 'bool'>


<class 'bool'>

SET Data Type:


In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate
elements. The order of elements in a set is undefined though it may consist of various elements.
Creating Sets
Sets can be created by using the built-in set() function with an iterable object or a sequence by placing
the sequence inside curly braces, separated by ‘comma’. Type of elements in a set need not be the same,
various mixed-up data type values can also be passed to the set.
# Set program

b={2,3,5,56.67,3+7j,'apssdc'} # mutable

print(type(b)) # this instruction is used for to know the data type

print(b)

Ans:
<class 'set'>
{2, 3, 5, 'apssdc', (3+7j), 56.67}

Dictionary Data Type:

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)

type(b) # this instruction is used for to know the data type

Ans:

{'sow': 34567, 'bhanu': 87834, 'devi': 75783457}


dict

Accessing elements of Dictionary


In order to access the items of a dictionary refer to its key name. Key can be used inside square brackets.
There is also a method called get() that will also help in accessing the element from a dictionary.
2.14. Input and output
2.14.1. Types of giving inputs:
# Sample program
a=1
b=2
c=3
d=4
e=a+b+c+d
print(e)
Note: above program consists of 6 lines, but if we have a chance to write same program in less lines by
comparing current program, then that was called as efficient coding, so we can write below program in
another way, that is:
# Sample program
a,b,c,d=1,2,3,4
e=a+b+c+d
print(e)
Note: Now you can observe above program has only 3 line with result, so this is one kind of giving input

# 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.14.2. Types of inputs:


We have two kinds of input methods, one is fixed input and second one is user defined input or variable
input
 Fixed input:
a=23
b=34.6
c=a+b
print(c)
Explanation: above program has two input variables, values in the variables do not change, no matter how
many times this program is executed.
 User defined input(integer type):
a=int(input())
b=int(input())
c=a+b
print(c)
Explanation: Whenever the program is executed above, the computer asks the user to enter values. But
when we specify integer in the program, user only the integer should be given, so if we give another data
type like float, complex kind of data, the error message will be shown.
 User defined input(float type):
a=float(input())
b=float(input())
c=a+b
print(c)
Explanation: Whenever the program is executed above, the computer asks the user to enter values. But
when we specify float number in the program, user can enter either integer or float value, so if we give
another data type like integer kind of data, user can get the result but in the float number form only.
 User defined input(complex type):
a=complex(input())
b=complex(input())
c=a+b
print(c)
Explanation: Whenever the program is executed above, the computer asks the user to enter values. But
when we specify complex number in the program, user can enter either integer, float or complex value, so
if we give another data type like integer kind of data, user can get the result but in the complex number
form only.
 User defined input(eval type): (integer, float, complex, list, tuple, set, dictionary)
a=eval(input())
b=eval(input())
c=a+b
print(c)
Explanation: Whenever the program is executed above, the computer asks the user to enter values. But
when we specify eval type in the program, user can enter either integer, float or complex value, so if we
give another data type, user can get the result but you will get the result according to input given.
 User defined input(string type):
a=input()
print(a)
Explanation: Whenever the program is executed above, the computer asks the user to enter the string. But
when we specify string in the program, user can enter either words, letters, numbers, symbols value, so if
we give another data type like integer kind of data, user can get the result but in the string number form
only.

2.15. Output:
Python provides the print() function to display output to the standard output devices.

basic print programs:


print(3+4) # here 3+4 is a number data thats why we got the output 7

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

# that is printed as it is at the output

print('The value of 3+4 is', 3+4) # in this statement we give two kinds of data one is string data type and

another one integer

# when we run this code, we got the output as string displayed as it is like what we given in the input

# 3+4 is displayed at the output as 7, because is is not sorrounded by quatations


 end=’ ‘ operator:
end The print function will automatically advance to the next line. For instance, the following will print on two lines:

print('On the first line')

print('On the second line')

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:

print('On the first line', end='')

print('On the second line')

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:

print ('The value of 3+4 is ', 3+4, sep='#')

ans: The value of 3+4 is#7

Formatting Output
Formatting output in Python can be done in many ways. Let’s discuss them below

 Using formatted string literals

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"

print(f'Hello {name} How are you?')

Output: Hello Pragati How are you?


 Using format()

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

print('The value of a is {} and b is {}'.format(a,b))

print('{2} is the sum of {0} and {1}'.format(a,b,sum))

print('{sub_value} is the subtraction of {value_a} and {value_b}'.format(value_a = a ,value_b =


b,sub_value = sub))

 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

# Taking input from the user


num = int(input("Enter a value: "))

add = num + 5
print("The sum is %d" %add)

output: Enter a value: 50


The sum is 55
2.16. Import Functions
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.

2.16.1. Math Operators:


Here is a list of the common operators in Python:

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

When player is 5, player%5 will be 0 and expression will set player to 1.

2.16.2. Random numbers:


To make an interesting computer game, it’s good to introduce some randomness into it. Python comes with a
module, called random, that allows us to use random numbers in our programs. Before we get to random numbers,
we should first explain what a module is. The core part of the Python language consists of things like for loops, if
statements, math operators, and some functions, like print and input. Everything else is contained in modules, and if
we want to use something from a module we have to first import it—that is, tell Python that we want to use it. At
this point, there is only one function, called randint, that we will need from the random module. To load this
function, we use the following statement:

from random import randint

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

from random import randint

x = randint(1,10)

print('A random number between 1 and 10: ', x)

Output: A random number between 1 and 10: 7

The random number will be different every time we run the program.

2.16.3 Math functions:


The math module Python has a module called math that contains familiar math functions, including sin, cos, tan, exp,
log, log10, factorial, sqrt, floor, and ceil. There are also the inverse trig functions, hyperbolic functions, and the
constants pi and e. Here is a short example:

from math import sin, pi

print('Pi is roughly', pi)

print('sin(0) =', sin(0))

output: Pi is roughly 3.14159265359

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.

2.16.4. Getting help from Python:


There is documentation built into Python. To get help on the math module, for example, go to the Python shell and
type the following two lines:
>>> import math

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

Sample programs on import function:


#Sample Program 1:
# generate a random number
from random import randint

x = randint(1,100)

print('A random number between 1 and 100: ', x)

Output: A random number between 1 and 100: 93

#Sample Program 2:
# generate trignometric function
from math import sin,pi,cos

print('Pi is roughly', pi)

print('sin(0) =', sin(0))

print('sin(30) =', sin(30))

print('sin(45) =', sin(45))

print('sin(90) =', sin(90))

print('cos(0) =', cos(0))

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

s=int(input('enter your factorial number: '))

print(factorial(s))

output: enter your factorial number: 12

479001600

#Sample Program 4:
# generate square root function
from math import sqrt

s=int(input('enter your square root number: '))

r=sqrt(s)

print(r)

output: enter your square root number: 64


8.0

# 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 *

s=int(input('enter your sqrt number: '))

print(sin(s))

output: enter your sqrt number: 90


0.8939966636005579

#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

from math import *

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

from math import *

print(floor(22/5))

output: 4

#Sample Program 10:


# generate any math function using import * method
from math import *

print(abs(-8.3))

print(round(3.456,2))

print(round(345.2,2))

Output: 8.3

3.46

345.2

#Sample Program 11:


# generate copy sign function using math method
''' copysign(a,b) :- This function returns the number with the value of ‘a’ but with the sign of ‘b’. The returned
value is float type.'''

import math

a=int(input())

b=int(input()) # returning the absolute value.

print ("The copysigned value of a and b is : ", end="")

print (math.copysign(a,b))
output: 10

-26

The copysigned value of a and b is : -10.0

#Sample Program 12:


# generate GCD function using math method
''' gcd() :- This function is used to compute the greatest common divisor of 2 numbers mentioned in its arguments.
This function works in python 3.5 and above.'''

c = 10

d = 15

# returning the gcd of 12 and 18

print ("The gcd of 'c' and 'd' is : ", end="")

print (math.gcd(c,d))

output:

The gcd of 'c' and 'd' is : 5

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.

Python divides the operators in the following groups:

 Arithmetic operators
 Logical operators
 Bitwise operators
 Assignment operators
 Comparison or relative operators
 Identity operators
 Membership operators

2.17.1. Arithmetic Operators:


Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication, and
division.
# Examples of Arithmetic
Operator
a=9
b=4
# Addition of numbers
add = a + b
# Subtraction of numbers
sub = a - b
# Multiplication of number
mul = a * b
# Division(float) of number
div1 = a / b
# Division(floor) of number
fdiv = a // b
# Modulo of both number
mod = a % b
# Power
p = a ** b

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

2.17.2. Logical Operators:


Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is used to combine conditional
statements.
If you want to understand logical operators you must know about logical gates and its truth tables
Basic Gates
# Examples of Logical Operator
a = True
b = False
# Print a and b is False
print(a and b)
# Print a or b is True
print(a or b)
# Print not a is False
print(not a)
output: False
True
False
2.17.3. Bitwise Operators:
Bitwise operators act on bits and perform the bit-by-bit operations. These are used to operate on binary
numbers.
Before you know about bitwise operators you must know about different number systems
NUMBER SYSTEM
1) Decimal ()10
2) Binary ()2
3) Octal ()8
4) Hexa Decimal ()16

1) Decimal Number system


0 to 9 -->> 10

0
1
2
3
4
5
6
7
8
9

2) Binary Number system


Bi means 2
Binary:- 0,1
Decimal:- 10 – ( ? )2
Decimal:- 35 – ( ? )2
Decimal:- 999 – ( ? )2

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

Binary to decimal and decimal to binary conversion


3) Octal:- ( )8
0,1,2,3,4,5,6,7 :- 0 to 7

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

Octal conversion table


Decimal:- Binary:- Octal
(56)10 -->>( ? )8

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

Decimal to octal conversion system

(101)8 -->>( ? )10


OCTAL to DECIMAL

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

4) HEXA DECIMAL System:


0-15 :- 8+4+2+1=15

S.No Hexa powers


8 4 2 1
0 0 0 0 0 0
1 1 0 0 0 1
2 2 0 0 1 0
3 3 0 0 1 1
4 4 0 1 0 0
5 5 0 1 0 1
6 6 0 1 1 0
7 7 0 1 1 1
8 8 1 0 0 0
9 9 1 0 0 1
10 A 1 0 1 0
11 B 1 0 1 1
12 C 1 1 0 0
13 D 1 1 0 1
14 E 1 1 1 0
15 F 1 1 1 1
8 4 2 1

Decimal:- Binary:- hexa


(34)10 -->>( ? )16 – (22)

34
32 16 8 4 2 1
Binary 0 0 1 0 0 0 1 0
Hexa decimal 2 2

Decimal to Hexal decimal conversion


(E5)16 -->>( ? )10

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

print(a | b) # perform bitwise logical and operation like above shown

Output: 5

8 4 2 1
A=1 -- >>0001
|
B=5 -- >>0101
------------------------------------------
0101
Bitwise X-OR: -
a=1

b=5

print(a ^ b) # perform bitwise logical and operation like above shown

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

Bitwise left shift:-<<


a=18
print(a<<3)
a=18 -- >> 8 4 2 1
a<<3

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

2.17.4. Comparison Operators:


Comparison of Relational operators compares the values. It either returns True or False according to the
condition.

# Examples of Relational Operators


a = 13
b = 33
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
Output:
False
True
False
True
False
True
2.17.5. Assignment operators:
Assignment operators are used to assign values to the variables.
# Examples of Assignment Operators
a = 10
# Assign value
b=a
print(b)
# Add and assign value
b += a
print(b)
# Subtract and assign value
b -= a
print(b)
# multiply and assign
b *= a
print(b)
# bitwise lishift operator
b <<= a
print(b)
Output:
10
20
10
100
102400
2.17.6. Identity Operators:
is and is not are the identity operators both are used to check if two values are located on the same part
of the memory. Two variables that are equal do not imply that they are identical.

is True if the operands are identical


is not True if the operands are not identical

#sample program:
a1 = 3

b1 = 3

a2 = 'andhrapradeshstateskilldevelopmentcorporation'
b2 = 'andhrapradeshstateskilldevelopmentcorporation'

a3 = [1,2,3]

b3 = [1,2,3]

print(a1 is not b1)

print(a1 is b1)

print(a3[1] is b3[1])

print(a3 is b3)

Output:

False

True

True

True

False

2.17.7. Membership Operators:


in and not in are the membership operators; used to test whether a value or variable is in a
sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence

x = 'Pragati BCA Kakinada'

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

ord() : This function is used to convert a character to integer.


hex() : This function is to convert integer to hexadecimal string.
oct() : This function is to convert integer to octal string.
# sample program
# initializing integer
s = '4'
c = ord(s)
print ("After converting character to integer : ",end="")
print (c)
d = hex(56)
print ("After converting 56 to hexadecimal string : ",end="")
print (d)
e = oct(56)
print ("After converting 56 to octal string : ",end="")
print (e)
output:
After converting character to integer : 52
After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70
tuple() : This function is used to convert to a tuple.
set() : This function returns the type after converting to set.
list() : This function is used to convert any data type to a list type.

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

# printing integer converting to complex number


c = complex(1,2)
print ("After converting integer to complex number : ",end="")
print (c)

# printing integer converting to string


c = str(a)
print ("After converting integer to string : ",end="")
print (c)

# printing tuple converting to expression dictionary


c = dict(tup)
print ("After converting tuple to dictionary : ",end="")
print (c)

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

You might also like