Python Unit I
Python Unit I
Python Unit I
UNIT-I
UNIT-II
Boolean Expressions - Selection Control – if, if-else, if-elif- else- Iterative Control - While
Statement, do while and for loop - break, continue, pass. Strings: string slices,
immutability, string functions and methods, string module;
UNIT-III
UNIT-IV
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists,
list parameters; Tuples: tuple assignment, tuple as return value; Dictionaries: operations
and methods; advanced list processing – list comprehension
UNIT-V
Files and exception: text files, reading and writing files, format operator; command line
arguments, errors and exceptions, handling exceptions, modules, packages;
TEXT BOOK:
1. Allen B. Downey, “Think Python: How to Think like a Computer Scientist”, 2nd
Edition,
Computer hardware includes the physical parts of a computer, such as a case, central
processing unit (CPU), random access memory (RAM), monitor, and mouse which
processes the input according to the set of instructions provided to it by the user and gives
the desired output
System Software
Application Software
System Software
The system software is a collection of programs designed to operate, control, and extend
the processing capabilities of the computer itself. System software is generally prepared by
the computer manufacturers. These software products comprise of programs written in
low-level languages, which interact with the hardware at a very basic level. System
software serves as the interface between the hardware and the end users.
Application Software
Application software may consist of a single program, such as Microsoft's notepad for
writing and editing a simple text. It may also consist of a collection of programs, often
called a software package, which work together to accomplish a task, such as a spreadsheet
package.
Payroll Software
Microsoft Word
Microsoft Excel
Microsoft PowerPoint
Characteristics of Python
1. For learning it is easy and to use: Python is easy to learn and use, even for
beginners. The syntax is plain and straightforward, almost like writing in English.
3. Interpreted: Python is an interpreted language, which implies line by line the code
is executed. This makes the process faster and more efficient as it eliminates the
need for a compilation step, and if some error occurs, it will not wait for the whole
code to compile. It will throw an error at that particular line itself.
9. Free and open source: The Python programming language is free and open
source, which suggests it can be utilized on any working framework for
complimentary. You'll be able download Python and the related libraries and
documentation from the official Python site.
10. Extensive feature: The Python programming language can be extended and is
more versatile than many other programming languages. Its adaptability to various
functionalities makes Python a universal programming language in the software
development industry. Code written in different programming languages can be
executed. Python gains new capabilities and functionality by integrating code from
other programming languages.
11. Database support: Python provides robust support for working with databases
through its standard library and third-party packages such as SQLite3, MySQL
Connector, PostgreSQL, SQLAlchemy, and MongoDB. Python also supports
Object-Relational Mapping (ORM) frameworks such as Django ORM and
SQLAlchemy, which provide an abstraction layer on top of databases, making it
easier to work with data in object-oriented Python code.
13. Python's simplicity, versatility, and readability make it popular for developers
across many industries and applications
Applications of Python
1. Web development: Django, Flask, and Pyramid are popular web frameworks in
Python, used for building applications ranging from small websites to large
enterprise applications.
2. Data science and analytics: Python is a highly demanded language in data science
and machine learning, with popular libraries like NumPy, Pandas, Matplotlib, and
Scikit-learn for data analysis, visualization, and ML.
4. Automation and scripting: Python is extensively used for automation tasks, such
as scripting, testing, and deployment, providing an efficient way to automate
repetitive tasks and integrate systems and services.
5. Desktop GUI applications: Python provides several GUI toolkits like Tkinter,
PyQt, and wxPython, allowing developers to create desktop applications with a
native look and feel.
6. Game development: Python can be used to develop games with libraries like
Pygame, which provides graphics, sound, and input handling tools for game
development.
8. Education: Python's simplicity and ease of use make it a popular choice for
introductory programming courses in academia and online.
9. DevOps: Python is used extensively in the DevOps community for tasks such as
automation, infrastructure management, and deployment. Tools such as Ansible
and SaltStack are written in Python.
10. Finance: Python is widely used for quantitative analysis, algorithmic trading, and
risk management. Banks such as JPMorgan and Goldman Sachs use Python for
financial modeling and analysis.
11. Healthcare: Python is used for medical imaging, data analysis, and research. The
National Institutes of Health (NIH) uses Python for genomic data analysis.
Literals:
Python Literals
1. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single
as well as double quotes to create a string.
Types of Strings:
a) Single-line String- Strings that are terminated within a single-line are known as
Single line Strings.
Example:
text1='hello'
Example:
text1='hello\
user'
print(text1)
'hellouser'
Example:
str2='''''welcome
to
SSSIT'''
print str2
Output:
welcome
to
SSSIT
Numeric literals:
Numeric Literals are immutable. Numeric literals can belong to following four
different numerical types.
#Float Literal
float_1 = 100.5
float_2 = 1.5e2
#Complex Literal
a = 5+3.14j
print(x, y, z, u)
print(float_1, float_2)
Output:
100.5 150.0
Boolean literals:
A Boolean literal can have any of the two values: True or False.
x = (1 == True)
y = (2 == False)
z = (3 == True)
a = True + 10
b = False + 10
print("x is", x)
print("y is", y)
print("z is", z)
print("a:", a)
print("b:", b)
Output:
x is True
y is False
z is False
a: 11
b: 10
Special literals.
None is used to specify to that field that is not created. It is also used for the end of lists
in Python.
val1=10
val2=None
print(val1)
print(val2)
Output:
10
None
Literal Collections.
Python provides the four types of literal collection such as List literals, Tuple literals,
Dict literals, and Set literals.
List:
o List contains items of different data types. Lists are mutable i.e.,
modifiable.
o The values stored in List are separated by comma(,) and enclosed
within square brackets([]). We can store different types of data in
a List.
list=['John',678,20.4,'Peter']
list1=[456,'Andrew']
print(list)
print(list + list1)
Output:
Dictionary:
Example
Output:
Tuple:
o Python tuple is a collection of different data-type. It is immutable
which means it cannot be modified after creation.
o It is enclosed by the parentheses () and each element is
separated by the comma(,).
Example
tup = (10,20,"Dev",[2,3,4])
print(tup)
Output:
set = {'apple','grapes','guava','papaya'}
print(set)
Output:
Since Python is an infer language that is smart enough to determine the type of a variable,
we do not need to specify its type in Python.
Variable names must begin with a letter or an underscore, but they can be a group of both
letters and digits.
The name of the variable should be written in lowercase. Both Rahul and rahul are distinct
variables.
Identifier Naming
Identifiers are things like variables. An Identifier is utilized to recognize the literals
utilized in the program. The standards to name an identifier are given underneath.
o The variable's first character must be an underscore or alphabet
(_).
o Every one of the characters with the exception of the main person
might be a letter set of lower-case(a-z), capitalized (A-Z),
highlight, or digit (0-9).
o White space and special characters (!, @, #, %, etc.) are not
allowed in the identifier name. ^, &, *).
o Identifier name should not be like any watchword characterized in
the language.
o Names of identifiers are case-sensitive; for instance, my name,
and MyName isn't something very similar.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.
Local Variable
The variables that are declared within the function and have scope
within the function are known as local variables.
Ex:
# Declaring a function
def add():
a = 20
b = 30
c=a+b
# Calling a function
add()
Output:
We get the error that follows if we attempt to use them outside of the function.
add()
print(a)
Output:
Global Variables
Global variables can be utilized all through the program, and its
extension is in the whole program. Global variables can be used inside
or outside the function.
By default, a variable declared outside of the function serves as the
global variable.
Ex:
x = 101
def mainFunction():
global x
print(x)
x = 'Welcome To Javatpoint'
print(x)
mainFunction()
print(x)
Output:
101
Welcome To Javatpoint
Welcome To Javatpoint
Explanation:
In the above code, we declare a global variable x and give out a value
to it. We then created a function and used the global keyword to access
the declared variable within the function. We can now alter its value.
After that, we gave the variable x a new string value and then called the
function and printed x, which displayed the new value.
Python Operators
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
Arithmetic Operators
Operator Description
/ (divide) It returns the quotient after dividing the first operand by the
second operand. For example, if a = 20, b = 10 => a/b = 2.0
% (reminder) It returns the reminder after dividing the first operand by the
second operand. For example, if a = 20, b = 10 => a%b = 0
** (Exponent) As it calculates the first operand's power to the second
operand, it is an exponent operator.
Comparison operator
==,!=,<=,>=,>,<
Assignment Operators
=,+=,-=,*=,%=
** a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign
= 4**2 = 16 to a.
//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will assign
4//3 = 1 to a.
Bitwise Operators
The two operands' values are processed bit by bit by the bitwise
operators. The examples of Bitwise operators are bitwise OR (|), bitwise
AND (&), bitwise XOR (^), negation (~), Left shift (<<), and Right shift
(>>).
example,
if a = 7
b=6
a | b = 0111
a ^ b = 0100
~ a = 1000
Binary of y = 1000
Bitwise OR = 1101
8421
1 1 0 1 = 8 + 4 + 1 = 13
0000 = 0
8421
1 1 0 1 = 8 + 4 + 1 = 13
~x = -6
Operator Description
& (binary A 1 is copied to the result if both bits in two operands at the
and) same location are 1. If not, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise,
the resulting bit will be 1.
^ (binary If the two bits are different, the outcome bit will be 1, else it will
xor) be 0.
<< (left The number of bits in the right operand is multiplied by the
shift) leftward shift of the value of the left operand.
>> (right The left operand is moved right by the number of bits present
shift) in the right operand.
Logical Operators
And,or,not
Operator Precedence
Operator Description
<= < > >= Comparison operators (less than, less than equal
to, greater than, greater then equal to).
Data Types
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary