Python U-I
Python U-I
Unit-I
Python is a high-level, interpreted language that emphasizes code readability and simplicity. Created
by Guido van Rossum in 1991, Python supports multiple programming paradigms and is used for web
development, data science, automation, and more. Key reasons for its popularity include platform
independence, extensive libraries, and a beginner-friendly syntax.
• Comments: Start with # for single lines; triple quotes for multi-line.
• Print Example:
python
print("Hello, World!")
Output:
text
Hello, World!
What is Python?
OR
the most widely used introductory language because it handles much of the
software development,
mathematics,
system scripting.
Fast prototyping
Why Python?
language.
programming languages.
PYTHON FEATURES
Python is easy to learn as compared to other programming languages. Its syntax is straightforward and
much the same as the English language. There is no use of the semicolon or curly-bracket, the
indentation defines the code block. It is the recommended programming language for beginners.
2) Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello world
program you simply type
print("Hello World"). It will take only one line to execute,while Java or C takes multiple lines.
3) Interpreted Language
Python is an interpreted language; it means the Python program is executed one line at a time. The
advantage of being interpreted language, it makes debugging easy and portable.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh, etc.
So, we can say that Python is a portable language. It enables programmers to develop the software for
several competing platforms by writing a program only once.
Python is freely available for everyone. It is freely available on its official website www.python.org. It
has a large community across the world that is dedicatedly working towards make new python
modules and functions. Anyone can contribute to the Python community. The open-source means,
"Anyone can download its sourcecode without paying any penny."
6) Object-Oriented Language
Python supports object-oriented language and concepts of classes and objects come into existence. It
supports inheritance, polymorphism, and encapsulation, etc. The object-oriented procedure helps to
programmer to write reusable code and develop applications in less code.
Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy are the
libraries which are used for developing the web application.
9) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by line
like C,C++ Java. It makes easy to debug the code.
PYTHON APPLICATIONS
1) Web Applications
We can use Python to develop web applications. It provides libraries to handle internet protocols such
as HTML and XML, JSON, Email processing, request, beautiful Soup, Feedparser, etc. One of Python
The GUI stands for the Graphical User Interface, which provides a smooth interaction to any
application. Python provides a Tk GUI library to develop a user interface.
3) Console-based Application
Console-based applications run from the command-line or shell. These applications are computer
program which are used commands to execute. This kind of application was more popular in the old
generation of computers. Python can develop this kind of application very effectively. It is famous for
having REPL, which means the Read-Eval-Print Loop that makes it the most suitable language for
4) Software Development
Python is useful for the software development process. It works as a support language and can be used
to build control and management, testing, etc.
This is the era of Artificial intelligence where the machine can perform the task the same as the
human. Python language is the most suitable language for Artificial intelligence or machine
learning. It consists of many scientific and mathematical libraries,which makes easy to solve complex
calculations.
6) Business Applications
Business Applications differ from standard applications. Ecommerce and ERP are an example of a
business application. This kind of application requires extensively, scalability and readability,
Python is flexible to perform multiple tasks and can be used to create multimedia applications. Some
multimedia applications which are made by using Python are TimPlayer, cplay, etc.
8) 3D CAD Applications
The CAD (Computer-aided design) is used to design engineering related architecture. It is used to
develop the 3D representation of a part of a system. Python can create a 3D CAD application by
9) Enterprise Applications
Python can be used to create applications that can be used within an Enterprise or an Organization.
Python contains many libraries that are used to work with theimage. The image can be manipulated
according to our requirements.
Installation: There are many interpreters available freely to run Python scripts like IDLE (Integrated
Development Environment) which is installed when you install the python software from
http://python.org/downloads/ Steps to be followed and remembered:
Step 6: Add Python Path to Environment Variables (Optional) Working with Python Python Code
Execution: Python’s traditional runtime execution model: Source code you type is translated to byte
code, which is then run by the Python Virtual Machine (PVM). Your code is automatically compiled,
but then it is interpreted. Source Byte code Runtime Source code extension is .py Byte code
extension is .pyc (Compiled python code)
Running Python in interactive mode: Without passing python script file to the interpreter, directly
execute code to Python prompt.
>>> print("hello world") hello world # Relevant output is displayed on subsequent lines without the >>>
symbol >>> x=[0,1,2] # Quantities stored in memory are not displayed by default. >>> x #If a quantity
is stored in memory, typing its name will display it. [0, 1, 2] >>> 2+3 5 The chevron at the beginning
of the 1st line, i.e., the symbol >>> is a prompt the python interpreter uses to indicate that it is ready. If
the programmer types 2+6, the interpreter replies 8.
Running Python in script mode: Alternatively, programmers can store Python script source code in a
file with the .py extension, and use the interpreter to execute the contents of the file.
To execute the script by the interpreter, you have to tell the interpreter the name of the file.
computer, then you can download it for free from the following
website: https://www.python.org/
Verify installation
C:\Users\Your Name>python –
print("Hello, World!")
PYTHON BASICS
Digits 0-9
@_(underscore)
formfeed.
IDENTIFIERS
AND ARE USED AS THE GENERAL TERMINOLOGY FOR THE NAMES GIVEN
The first character must be a letter; the underscore (_) counts as a letter.
Upper and lower-case letters are different. All characters are significant.
The digits 0 through 9 can be part of the identifier except for the first character.
Identifiers are unlimited in length. Case is significant i.e., Python is case sensitive as
KEYWORDS IN PYTHON
Keywords are the reserved words in Python. We cannot use a keyword as a variable name, function
name or any
other identifier.
• Control Flow: if, else, elif, for, while, break, continue, pass, return, yield
• Other: and, or, not, in, is, del, global, nonlocal, assert, with, async, await
PYTHON VARIABLES
Variables are identifiers of a physical memory location, which is used to hold values temporarily
Python interpreter allocates memory based on the values(letter or a number) data type of variable,
different data types like integers, decimals, characters, etc. can be stored in these variables.
Python Variable Declaration
In Python, like many other programming languages, there is no need to define variables in advance.
given below:
<variable-name> =<value>
Python interpreter can determine what type of data is stored, so before assigning a value, variables
do not need to be declared.
Usually, in all programming languages, equal sign = is used to assign values to a variable. It assigns
the values of the right side operand to the left side operand.
Example:
OUTPUT
Packing box
10
20.5
print (name)
print (height)
print (width)
followed:
A variable name can only contain alphanumeric characters and underscore, such as (a-z, A-Z, 0-9,
and_ ).
Example
a=4
A = "Sally"
DATA TYPES
3. List - mutable(changed/modified)
5. Dictionary - mutable(changed/modified)
1. NUMBERS
N umeric values are stored in numbers. The whole number, float, and
a=5
b = 40.5
c = 1+3j
Output
NUMERICAL DATA.
15 decimal places.
the string.
Example
3. LIST
Lists in Python are like arrays in C, but lists can contain data of
different types. The things put away in the rundown are isolated
To gain access to the list's data, we can use slice [:] operators. Like
Example
print(type(list1))
print (list1)
# List slicing
print (list1[3:])
# List slicing
print (list1[0:2])
print (list1 * 3)
Out put
[2]
[1, 'hi']
1, 'hi', 'Python', 2]
4. TUPLE
In many ways, a tuple is like a list. Tuples, like lists, also contain a
Example
up = ("hi", "Python", 2)
print (type(tup))
print (tup)
# Tuple slicing
print (tup[1:])
print (tup[0:1])
print (tup * 3)
t[2] = "hi"
Out put
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
last):
5. DICTIONARY
specific value for each key, like an associative array or a hash table.
Value is any Python object, while the key can hold any primitive data
type.
The comma (,) and the curly braces are used to separate the items in
the dictionary.
Example
# Printing dictionary
print (d)
print (d.keys())
print (d.values())
Out Put
6. SETS
Set. It is iterable, mutable(can change after creation), and has remarkable components. The
elements of a set have no set order; It might return the element's altered sequence. Either a
sequence of elements is passed through the curly braces and separated by a comma to create the
set or the built-in function set() is used to create the set. It can contain different kinds of values.
EXAMPLE
set1 = set()
print(set2)
set2.add(10)
print(set2)
set2.remove(2)
print(set2)
Out Put
PYTHON - OPERATORS
Arithmetic Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Python arithmetic operators are used to perform mathematical operations on numerical values.
These operations are Addition, Subtraction, Multiplication, Division, Modulus, Exponents and Floor
Division. Operator Description
- (Subtraction) It is used to subtract the second operand from the first operand. If the first operand is
less than the second operand, the value results negative.
For example, if a = 20, b = 5 => a - b =15
/ (divide) It returns the quotient after dividing the first operand by the second operand. For example, if
a
% (reminder) It returns the reminder after dividing the first operand by the second operand. For
example, if
** (Exponent) As it calculates the first operand's power to the second operand, it is an exponent
operator.
// (Floor division) It provides the quotient's floor value, which is obtained by dividing the two
operands.
Python comparison operators compare the values on either sides of them and decide the relation
among
Python assignment operators are used to assign values to variables. These operators include simple
assignment operator, addition assign, subtraction assign, multiplication assign, division and assign
operators etc.
Operator
Name Example
= Assignment Operator a = 10
5)
2)
Name Example
~ Binary Ones
Complement
<< Binary Left Shift Shift left by pushing zeros in from the right
and let the leftmost bits fall off
Shift
Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples.
There are
• Variables:
python
x=5
name = "Alice"
Int x = 20
Float y = 20.5
complex z = 1j
range r = range(6)
Data Type Example Assignment
bool b = True
NoneType n = None
python
x=5
python
python
print("Type:", type(num))
• Input Conversion:
python
Precedence of Operators
• Exponentiation **
• Multiplication/Division/Modulus *, /, //, %
• Addition/Subtraction +, -
• Lowest precedence: or
Examples:
python
result = 10 - 5 + 3 * 2
print(result) # Output: 11
python
python
a = 5 # int
b = 2.5 # float
result = a + b
python
s = "100"
num = int(s)
Conditional Statements
Example:
python
age = 25
print("Child.")
print("Teenager.")
print("Young adult.")
else:
print("Adult.")
Nested if:
python
age = 70
is_member = True
if is_member:
else:
else:
Ternary Operator:
python
python
match number:
case 1:
print("One")
case 2 | 3:
print("Two or Three")
case _:
print("Other number")
for loop:
python
print(fruit)
while loop:
python
i=1
while i < 5:
print(i)
i += 1
Nested loops:
python
for i in range(3):
for j in range(2):
print(i, j)
python
i=2
j=2
if not(i%j): break
j += 1
i += 1
print("Good bye!")
python
for i in range(10):
if i == 5:
break
print(i)
# Output: 0 to 4
python
for i in range(10):
if i % 2 == 0:
continue
print(i)
# Output: 1, 3, 5, 7, 9
python
for i in range(10):
python
x = "global"
def foo():
global x
x = "modified"
foo()
python
try:
except ValueError:
• While-Else Statement:
python
i=0
while i < 5:
print(i)
i += 1
else: