0% found this document useful (0 votes)
11 views51 pages

Python Programming Basics and Data Types

The document provides an introduction to Python programming, covering fundamental concepts such as data types, operators, and data structures including lists, tuples, dictionaries, and sets. It explains the use of variables, type conversion, and the differences between global and local variables. Additionally, it discusses the programming cycle in Python and the role of integrated development environments (IDEs) in enhancing developer productivity.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views51 pages

Python Programming Basics and Data Types

The document provides an introduction to Python programming, covering fundamental concepts such as data types, operators, and data structures including lists, tuples, dictionaries, and sets. It explains the use of variables, type conversion, and the differences between global and local variables. Additionally, it discusses the programming cycle in Python and the role of integrated development environments (IDEs) in enhancing developer productivity.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON PROGRAMMING

UNIT-I
Introduction to Python: Python variables,
Python basic Operators, Understanding
python blocks. Python Data Types,
Declaring and using Numeric data types:
int, float etc.
.

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


Numeric Data

 Python, numeric data type is used to hold numeric values.


 Integers, floating-point numbers and complex numbers fall under
Python numbers category.
 They are defined data as INT, FLOAT and complex classes in
python.
 int - holds signed integers of non-limited length.
 float - holds floating decimal points and it's accurate up to 15
decimal places.
 complex - holds complex numbers.

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

output
hi is of type <class ‘string’>
bye is of type <class ‘string’>
hello is of type <class ‘string’>

String handling
str1="hello python Language"
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)

Output
he
el
0
m
hello python Languagehello python Language
welcomewelcomewelcomewelcome
hello python Languagewelcome
welcomehello python Language

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


Access Element In List
To access items from a list, we use the index number (0, 1, 2 ...).
For example
1) language=["python","c","java"]
print(language)
print(language[0])
print(language[1])
print(language[2])
Output
['python', 'c', 'java']
Python
C
Java

2) language=["python","c","java"]
print(language[3])

Output
ERROR!Traceback (most recent call last): File "", line 2, in
IndexError: list index out of range

Tuple data 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,
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])

output
('microsoft', 'xbox', 499.99)
('samsung', 'vivo', 2, 4.555)
type of product <class ‘tuple’>
type of product <class ‘tuple’>
microsoft
xbox
2

Dictionary datatypе
 dictionary is an ordered collection of items. It stores elements
in key/value pairs.
 Here, keys are unique identifiers that are associated with each
value

# create a dictionary named capital_city

capital_city = {'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England':1455


'London'}
print(capital_city)

Access Dictionary Values Using Keys


# create a dictionary named capital_city
capital_city = {'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England':
‘london’}
print(capital_city['Nepal']) # prints Kathmandu
print(capital_city['Kathmandu']) # throws error message

d={1:'c',2:'python',3:'datatype',4:'module'}
print(d)
print([Link]())
print([Link]())
print("1name is "+d[1])
print("3name "+d[3])

Output
dict_keys([1, 2, 3, 4])
dict_values(['c', 'python', 'datatype', 'module'])
1name is c
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.
1) a = True
type(a)
Output
<class ‘bool’>
2) b = False
type(b)
Output
<class ‘bool’>

Sets
 Sets are used to store multiple items in a single variable.
 Set is one of 4 built-in data types in Python used to store
collections of data, the other 3 are List, Tuple, and Dictionary, all
with different qualities and usage.
 A set is a collection which is unordered, unchangeable*, and
unindexed.
 * Note: Set items are unchangeable, but you can remove items
and add new items
 thisset = {"apple", "banana", "cherry"}
print(thisset)
Output {'apple', 'banana', 'cherry'}

 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.
DUPLICATES ARE NOT ALLOWED(THEY ARE IGNORED)
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
Output {'cherry', 'apple', 'banana'}
thisset = {"apple", "banana", "cherry", True, 1, 2, False,0}
print(thisset)
print(type(thisset))
Output
{False, True, 2, 'banana', 'cherry' apple'}
<class ‘set’>

Operator
 These are the special symbols in Python and are used to
execute an Arithmetic or Logical computation. An
operator alone cannot perform that the operator needs to
complete a task

 Types of Operators
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.
1. Arithmetic operators

2. Comparison operators
3. Assignment operators

4. Logical operators

5. Bitwise operators

6. Membership operators

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

Operator Description Example


Plus Adds two Operands. 3+3=6
-Minus Right-hand Operand 20-10=10
is subtracted from the
left hand operand.
Multiplication It Multiplies the 10*10 = 100
values on either side
of the operands.
/ Division left-hand operand 50/5 = 10
divided by right-hand
operand.
% modlus It divides the left- 7%2 = 1
hand operand by the
right-hand one and
also returns a
reminder.
// Floor Division that results 5.0/2
division in the whole number 2.5
being adjusted to the 5.0//2
left in the number 2.0
line.
** Exponent The left operand is 10 to the power
raised to the power of of 3 10**3=1000
the right
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 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 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

And - Logical AND


Or - Logical OR
Not – Logical
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 membership Operators


 Membership Operators are mainly used in Python to find
whether a value or variable is present in a sequence (string,
tuple, list, set, and directory). "In" and "Not In" are the two
membership operators available in Python.
1. Python In Membership Operator
 This In operator is used in Python to evaluate if a particular
value is there or not in a sequence. The In operator returns True
if it is the specified element found in the list, otherwise, it
returns false.
 list=[1,2,3,4,5]
b=2
if b in list:
print("present")
else:
print("not")
2. Python Not In Membership Operator
 "Not in" operator, the name itself expresses the meaning

that something is not inside. It goes through a particular


sequence to find whether a value is in the specified list or
not. If it finds there is no such value, it returns True,
otherwise False
 list=[1,2,3,4,5]

b=2
if b not in list:
print("hi")
else:
print("bye")
Output bye

Identity 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
Operator precedence and associativity
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.
Type Conversion in python
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 types of type conversion are there –

 Implicit type
 Explicit type (type casting)

1. Implicit Type Conversion (Type Promotion)

 It is automatically done by Python.


 Python converts smaller data types into larger data types to prevent data loss.

Example:

a = 5 # int
b = 2.5 # float
result = a + b
print(result)
print(type(result))

Output:

7.5
<class 'float'>

� Here, Python automatically converts a (int) to float before addition.

2. Explicit Type Conversion (Type Casting)

 It is manually done by the user.


 The user uses predefined functions like int(), float(), str(), etc.

Example:

x = "100"
y = int(x) # convert string to integer
print(y + 20)
Output:

120

� Here, the string "100" is explicitly converted to an integer using int().

Global Variable Local Variable


Definition declared outside the declared within the
functions functions

Data Sharing Offers Data Sharing It doesn't offers Data


Sharing
Scope Can be access throughout Can access only inside the
the code function

Lifetime They are created the They are created when the
execution of the program function starts its
begins and are lost when execution and are lost
the program is ended when the function ends

Value Once the value changes it once changed the variable


is reflected throughout don't affect other functions
of the program
the code

Programming Cycle for Python

 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:

➤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.
What is I D E

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.

Why IDE is important?

 Code editing
Programming languages have rules for how statements must
be structured. Because an IDE knows these rules, it contains
many intelligent features for automatically writing or editing
the source code.

 Syntax highlighting
An IDE can format the written text by automatically making
some words bold or italic, or by using different font colors.
These visual cues make the source code more readable and give
instant feedback about accidental syntax errors.

 Intelligent code completion


Various search terms show up when you start typing words in a
search engine. Similarly, an IDE can make suggestions to
complete a code statement when the developer begins typing.

 Refactoring support
Code refactoring is the process of restructuring the source code
to make it more efficient and readable without changing its core
functionality. IDEs can auto-refactor to some extent, allowing
developers to improve their code quickly and easily. Other
team members understand readable code faster, which supports
collaboration within the team.
 Local build automation
IDEs increase programmer productivity by performing
repeatable development tasks that are typically part of every
code change. The following are some examples of regular
coding tasks that an IDE carries out.

 Testing
The IDE allows developers to automate unit tests locally before
the software is integrated with developers' code and more
complex integration tests are run.

 Debugging
Debugging is the process of fixing any errors or bugs that
testing reveals. One of the biggest values of an IDE for
debugging purposes is that you can step through the code, line
by line, as it runs and inspect code behavior. IDEs also
integrate several debugging tools that highlight bugs caused by
human error in real time, even as the developer is typing.

Some python IDE

 PyCharm

 Spyder

 Pydev

 IDLE

 VISUAL STUDIO
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

Features

 Intelligent Code Editor:

 It helps us write high-quality codes!

 It consists of color schemes for keywords, classes,

and functions. This helps increase the readability

and understanding of the code.

 It helps identify errors easily.

 It provides the auto complete feature and

instructions for the completion of the code

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

SPYDER

Spyder is widely used for data science works. It is mostly used to

create reate aa 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.


 availability of breakpoints (debugging and conditional

breakpoints)

 Automatic colon insertion after if, while, etc

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.

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

2. Debugging:

PyDev has a built-in debugger. It allows us to step through our code

and identify and fix errors quickly.


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

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

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

6. Plugins:

PyDev supports plugins, which can extend its functionality to support

additional features, such as Django and Flask web frameworks.

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

How memory is managed in python

 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:

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

o 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

 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 typе

 object value

 object reference counter

 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

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

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

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

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

 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

 EPs 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, РEP20, PEР257,РЕР333 etc

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:

1. Indentation: Use 4 spaces for each level of indentation.

Don't use tabs. Consistent indentation makes your code look

neat and organized.

2. Maximum Line Length: Limit each line of code to a

maximum of 79 characters for code, and 72 character

3. Whitespace: Use a single space after commas, colons, and


semicolons, but not immediately before. Avoid extraneous

whitespace (e.g., at the end of lines).

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

5. 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()).

6. Blank Lines: Use blank lines to separate functions, classes,

and blocks of code inside functions for better readability.

7. Whitespace in Expressions and Statements: Avoid

extraneous whitespace within expressions and statements. For

example, don't put spaces immediately inside parentheses or

square brackets.

8. Encoding: Always specify the source code encoding as

UTF- 8 at the top of your Python files to ensure purpose and

usage.
9. Documentation Strings (Docstrings): Write docstrings for

modules, classes, and functions to explain their purpose and

usage.

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

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 theClass conditions are

true, i.e if the value of 'x' is between 1 and 5.

divisible by 1.

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.

i) x=10

z=(x>1) and (x<5)

print(z)

Output: False

ii) x=10

y=12

print(x>22 or y<25)

Output: true

iii) x=10 y=12

print(not (x>22 or y<25))

Output : False
Difference-
Comparison Python 2 Python 3
Parameter
year of Release Python 2 was release in python 3 was released in
the year 2000. the year 2008.

"Print" In Python 2, print is In Python 3, print is


Keyword considered to be a considered to be a
statement and not a function and not a
function. statement.

Storage of In Python 2, strings are In Python 3, strings are


Strings stored as ASCII by stored as UNICODE by
default. default.

Division of On the division of two On the division of two


Integers integers, we get an integers, we get a
integral value in Python floating-point value in
2. For instance, 7/2 Python 3. For instance,
yields 3 in Python 2. 7/2 yields 3.5 in Python
3.

Exceptions In Python 2, exceptions In Python 3, exceptions


are enclosed in are enclosed in
notations. parentheses.

variable The values of global The value of variables


leakage variables do change in never changes in Python
Python 2 if they are 3.
used inside a for-loop.

Iteration In Python 2, the In Python 3, the new


xrange() function has Range() function was
been defined for introduced to perform
iterations. iterations.

Ease of Syntax Python 2 has more Python 3 has an easier


complicated syntax than syntax compared to
Python 3. Python 2.

Libraries A lot of libraries of A lot of libraries are


Python 2 are not created in Python 3 to be
forward compatiable strictly used with Python
3.
Usage in Python 2 is no longer in Python 3 is more
today's times use since 2020. popular than Python 2
and is still in use in
today's times.
Backward Python 2 codes can be Python 3 is not
compatibility ported to Python 3 with backward compatible
a lot of effort. with Python 2.

Application Python 2 was mostly Python 3 is used in a lot


used to become a of fields like Software
DevOps Engineer. It is Engineering, Data
no longer in use after Science, etc.
2020.
Tools to find bugs and perform static analysis

 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

 Identify bugs in early stages: It can help identify bugs, type

checks, and common security issues early in the software

development cycle, reducing the risk of xpensve nd time

consuming fies laer:

 Enforces Coding Standards: By enforcing coding standards,


style guides, and best practices, static code analysis can help

produce more maintainable code that is easier to understand

and debug.

 Returns Instant Feedback: You can get instant feedback on

code improvements and alerts on external dependencies. In

addition, this process can highlight areas of the code that may

be difficult to read or understand, leading to better

documentation and more readable code.

 Reduce Technical Debt: Using static code analysis reduces

technical debt by specifying code areas that are inefficient,

challenging to maintain, or pose security risks.

Static code analysis tools 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


UNIT-II

Python Program Flow Control Conditional


blocks: if, else and else if, Simple for loops in
python, For loop using ranges, string, list and
dictionaries. Use of while loops in python, Loop
manipulation using pass, continue, break and
else. Programming using Python conditional and
loop blocks.
Conditional statement
 A conditional statement as the name suggests itself, is used to

handle conditions in your program.

 if statement

 Syntax :

 if expression:

statement

 If-else statement

 Syntax:

if conditiọn:

#block of statements

else:

#another block of statements (else-block)


 elif statement

if expression 1:

#.block of statements

elif expression 2:

# block of statements

elif expression 3:

# block of statement

else:

#statement
 Nested if else

if condition 1:

if condition2:
#nested if code
else:
#nested else code
else:

#else code
1. write a program to check whether a year is leap year or not
2. Write program to make calculator

 LOOPS

Loops is used to execute a block of statements repeatedly until a

given condition is satisfied.

1. while loop

Syntax

while expression:

statement(s)
2. for loop

Syntax

for var in iterable:

# statements
 Range ()

 The Python range() function returns a sequence of numbers, in a

given range.

 range (stoр)

for i in range(6):

print(i, end=” “)

output

012345

 range (start, stoр)

for i in range(5,20):

print(i, end=” “)

output

5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

 range (start, stop, step)

for i in range(0,30,4):

print(i, end=” “)

output

0 4 8 12 16 20 24 28
1. write a program to check whether number is Armstrong or not

2. write a program to find out the whether a number palindrome or

not

3. Write a program to find out the fibonnaci series upto n term

4. Write a program to find out the factorial of a number

5. Write a program to check whether a number is prime or not

6. Write a program to print the reverse of a number

7. Write a program to print the prime number in range

ALGORTHIM

1 start

2 enter the lower range upper range

3 Take one number one by one from the range

4 check number is greater than1 if yes then go to set 5

5 check whether that number is divisible by (2 to less than that

number)

6 if yes then break check for another number else print that number

Repeat the process for all the number

7 stop
Break statement
the break statement is used to terminate the loop immediately when it

is encountered. The syntax of the break statement is:

break:

for i in range(6):

if i == 3:

break

print(i)

output

2
Continue statement
The continue statement is used to skip the current iteration of the

loop and the control flow of the program goes to the next iteration.

The syntax

Continue;

for i in range(5):
if i == 3:
Continue
print(i)
output
0
1
2
4
Pass statement
This is a null statement. But the difference between pass and

comment is that comment is ignored by the interpreter whereas pass

is not ignored.

SYNTAX pass

What is pass statement in Python?


Write a program to check whether entered number is Fibonacci

number or not
DIFFRENCE BETWEEN

for loop While loop

For loop is used to iterate While loop is used to

over a sequence of items. repeatedly execute a block of

statements while a condition

is true.

For loops are designed for While loop is used when the

iterating over a sequence of number of iterations is not

items. Eg. list, tuple, etc. known in advance or when

we want to repeat a block of

code until a certain condition

is met.

For loop require a sequence While the loop requires an

to iterate over. initial condition thaţ is tested

at the beginning of the looр.

For loop is typically used for While loop is used for more

iterating over a fixed complex control flow

sequence of items situations.


Write a program to convert time from 12 hour to 24 hour format

You might also like