0% found this document useful (0 votes)
17 views14 pages

Python

Python is a high-level, dynamically typed programming language created by Guido Van Rossum in 1989 and released to the public in 1991. It is known for its readability, simplicity, and support for multiple programming paradigms, including functional and object-oriented programming. Python is widely used in various applications such as data analysis, machine learning, web development, and more, while also having limitations in performance and mobile application development.
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)
17 views14 pages

Python

Python is a high-level, dynamically typed programming language created by Guido Van Rossum in 1989 and released to the public in 1991. It is known for its readability, simplicity, and support for multiple programming paradigms, including functional and object-oriented programming. Python is widely used in various applications such as data analysis, machine learning, web development, and more, while also having limitations in performance and mobile application development.
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

HISTORY
●​ Python is a popular programming language
●​ Python was developed by Guido Van Rossum in 1989 while working at the National Research
Institute in the Netherlands.
●​ But officially, Python was made available to public in 1991
●​ The Official Date of Birth for Python is February 20, 1991

TY
●​ The name "Python" was selected from the TV show "The Monty Python's Flying Circus," which
was broadcast on BBC from 1969 to 1974
●​ Guido developed Python language by taking almost all programming features from different

N
languages.

A
Eg1: To print Hello World:

H
print("Hello World")
Eg2: To print the sum of 2 numbers:

O
1) a=10
2) b=20
IM
3) print("The Sum:", (a+b))
What is Python?
●​ Functional programming language feature from C.
XM

●​ Object-oriented programming language feature from C++.


●​ Scripting language features from Perl and shell scripting.
●​ Modular programming language feature from Modular-3.
LA

●​ Python focuses on making code readable by using significant indentation. It is dynamically typed
and includes automatic garbage collection.
●​ Python supports various programming styles, including structured, object-oriented, and
A

functional programming.
AY

Uses
●​ Data Analysis Application
IJ

●​ Machine Learning
●​ Developing Artificial Intelligence Applications
B

●​ Developing Desktop Applications


●​ Developing Database Applications
●​ Developing Web Applications
●​ Developing Desktop Games
Feature
➢​ SIMPLE AND EASY TO LEARN
➔​ Python is a simple programming language. When we read a Python program, we
can feel like we are reading an English statement.
➔​ The syntax is very simple; only 30+ keywords are available
➔​ When compared with other languages, it can write programs with a very small
number of lines, resulting in more readability and simplicity.

TY
➔​ We can reduce the development cost of the project.

➢​ FREE AND OPEN SOURCE

N
➔​ We can use Python software without any license, and it is freeware.
➔​ Its source code is open so that we can customize it based on our requirements.

A
➔​ "Open source" means it is free to use. We can use it for individuals or for

H
enterprises.

O
➢​ HIGH-LEVEL PROGRAMMING LANGUAGE
➔​ It is a high-level programming language, and hence, it is a programmer-friendly
IM
language.
➔​ Being programmers, we are not required to concentrate on low-level activities
like memory management, security, etc.
XM

➢​ PLATFORM INDEPENDENT
➔​ Once we write a Python program, it can run on any platform without rewriting it
LA

again. (WINDOWS, LINUX, MAC, etc.)


➔​ Internally, PVM (Python Virtual Machine) is responsible for converting the data
into machine-understandable form.
A
AY

➢​ PORTABILITY
➔​ Python programs are portable, i.e., we can migrate from one platform to
another very easily. Python programs will provide the same results on any
IJ

platform.
B

OLA—UBER—RAPIDO—>SAME DESTINATION
➢​ DYNAMICALLY TYPED
➔​ In Python we are not required to declare types for variables. Whenever we
assign a value, based on that value, type will be allocated automatically. Hence,
Python is considered as a dynamically typed language.
➔​ But Java, C, etc. are Statically typed language because we have to provide type at
the beginning only
➔​ This dynamic typing nature will provide more flexibility to the programmer

➢​ BOTH PROCEDURAL AND OBJECT-ORIENTED


➔​ Python language supports both procedure-oriented (like C, pascal, etc.) and
object-oriented (like C++, Java) features
➔​ Hence, we can get benefits of both, like security, reusability, etc.
➢​ INTERPRETED
➔​ We are not required to compile Python programs explicitly. Internally, the

TY
Python interpreter will take care of that compilation.
➔​ If compilation falls, the interpreter raises syntax errors. Once compilation is
successful, PVM is responsible for execution.

N
➢​ EXTENSIVE LIBRARY

A
➔​ Python has a rich built-in library.

H
➔​ Being programmers, we can use this library directly and we are not responsible
for implementing the functionality, etc.

O
➢​ Extensible
➔​ We can use other language programs in Python. The main advantages of this
IM
approach are the following:
➔​ We can use already existing legacy non-Python code
➔​ We can improve the performance of the application
XM

➢​ Embedded:
➔​ We can use Python programs in any other language. i.e., we can embed Python
programs anywhere
LA

LIBRARY— > COLLECTION OF BOOKS— > AUTHOR— > REUSE CONCEPTS


LIBRARY—> COLLECTION OF CODES—> PROGRAMMERS—> REUSE CODE
(manually install libraries)
A
AY

Limitations of Python
1. Performance-wise, it's not up to the mark because it is interpreted language.
2. Not using for mobile Applications
IJ
B

IDE- (Integrated Development Environment)


We are developing our application in this
-Each IDE had different GUI (graphical user interface)

GOOGLE COLAB-
CPU—CENTRAL PROCESSING UNIT
GPU-GRAPHICAL PROCESSING UNIT-(USE IN DEEP LEARNING AND MACHINE LEARNING
ALGORITHMS)
TPU-TENSOR PROCESSING UNIT (USE IN DEEP LEARNING AND MACHINE LEARNING
ALGORITHMS)
Code Execution:
In Python, the process of code execution involves a few steps, and it doesn't involve a traditional
compilation step like in languages such as C or C++. Instead, Python uses an interpreted and
dynamically typed approach. Here's a simplified overview of how a Python script is executed:

TY
1.​ Source Code: You write high-level, human-readable Python code. This is called the source code.
2.​ Lexical Analysis (Tokenization): The Python interpreter performs lexical analysis on the source
code, breaking it down into a sequence of tokens. This involves identifying keywords, identifiers,

N
literals, and operators.
3.​ Syntax Analysis (Parsing): The parser then organizes the tokens into a hierarchical structure

A
called the Abstract Syntax Tree (AST). The AST represents the syntactic structure of the Python

H
code.
4.​ Intermediate Code Generation (Bytecode): The Python interpreter generates an intermediate

O
code known as bytecode from the AST. Bytecode is a low-level, platform-independent
representation of the source code.
IM
5.​ Bytecode Compilation: The bytecode is stored in compiled form [Link] files or within memory,
ready for execution. This compilation step enhances the efficiency of the interpretation process.
6.​ Execution by the Python Virtual Machine (PVM):
a.​ The Python Virtual Machine (PVM) is responsible for executing the bytecode. It's part of the
XM

Python interpreter.
b.​ The PVM uses a stack-based virtual machine to execute operations defined by the bytecode.
c.​ The dynamic nature of Python allows for features like runtime type checking and late
LA

binding.
7.​ Memory Management and Garbage Collection:
a.​ Python employs automatic memory management with a combination of reference counting
and a cyclic garbage collector.
A

b.​ Memory is allocated for objects during execution and reclaimed when objects are no longer
AY

referenced.
8.​ Dynamic Typing and Runtime Evaluation: Python is dynamically typed, meaning that variable
types are determined at runtime. This allows for flexibility but requires runtime type checking.
IJ

9.​ Exception Handling: The interpreter includes mechanisms for handling exceptions at runtime.
When an exception occurs, the interpreter searches for an appropriate exception handler in the
B

call stack.
10.​Standard Library Interaction: The Python interpreter interacts with the Python Standard Library,
which provides a vast collection of modules and packages for various functionalities.

This process allows Python to be a highly dynamic and flexible language. The focus is on
readability, ease of use, and rapid development rather than a separate compilation step. The
compilation to bytecode and execution by the PVM happen on-the-fly, making Python an
interpreted language.
Input And Output Statements:
Reading dynamic input from the keyboard:
In Python 2, the following 2 functions are available to read dynamic input from the
keyboard.
1. raw_input()
2. input()
1. raw_input():
This function always reads the data from the keyboard in the form of String Format. We

TY
have to convert that string type to our required type by using the corresponding type
casting methods.
e.g.:

N
x = raw_input("Enter First Number:")
print(type(x)) It will always print str type only for any input type

A
2. input():

H
The input() function can be used to read data directly in our required format. We are not
required to perform type casting.

O
e.g.:
x = input("Enter Value ”)
IM
type(x)
10 ===> int
"durga" ===> str
XM

10.5===>float
True==>bool
Note: But in Python 3 we have only input() method and raw_input() method is not
LA

available.
The Python 3 input() function behaves exactly the same as the raw_input() method of Python
2. i.e
Every input value is treated as a str type only.
A

raw_input() function of Python 2 is renamed as input() function in Python 3.


AY
IJ
B
Q. Write a program to read 2 numbers from the keyboard and print sum.
1)-----------------------------------------------------
x=input("Enter First Number:")
y=input("Enter Second Number:")
i = int(x)
j = int(y)
print("The Sum:",i+j)
Enter First Number:58

TY
Enter Second Number:45
The Sum: 103
2)-----------------------------------------------------

N
x=int(input("Enter First Number:"))
y=int(input("Enter Second Number:"))

A
print("The Sum:",x+y)
Enter First Number:58

H
Enter Second Number:45
The Sum: 103

O
3)-----------------------------------------------------------
IM
print("The Sum:",int(input("Enter First Number:"))+int(input("Enter Second Number:")))
Enter First Number:58
Enter Second Number:45
The Sum: 103
XM

Q. Write a program to read Employee data from the keyboard and print that data.
eno=int(input("Enter Employee No:"))
ename=input("Enter Employee Name:")
LA

esal=float(input("Enter Employee Salary:"))


eaddr=input("Enter Employee Address:")
print("Please Confirm Information")
A

print("Employee No :",eno)
print("Employee Name :",ename)
AY

print("Employee Salary :",esal)


print("Employee Address :",eaddr)
Enter Employee No:2857
Enter Employee Name:Arushi
IJ

Enter Employee Salary:40000


Enter Employee Address:Odisha
B

Please Confirm Information


Employee No : 2857
Employee Name : Arushi
Employee Salary : 40000.0
Employee Address : Odisha
Boolean input Example:
user_input = bool(input("Are you hungry? True or false: "))
if user_input == "True":
print(" You need to eat some foods ")
else:
​ print("Let's go for walk")
Are you hungry? True or false: false
Let's go for walk

IDENTIFIER
●​ A name in a Python program is called identifier.
●​ It can be a class name, a function name, a module name, or a variable name.

TY
Example:- a = 10
Rules to define identifiers in Python:
1. The only allowed characters in Python are

N
●​ alphabet symbols (either lowercase or upper case)
●​ digits (0 to 9)

A
●​ underscore symbol(_)

H

By mistake, if we are using any other symbol, like $, then we will get syntax errors.


●​ cash = 10

O
●​ ca$h =20


2. identifier should not start with digit
IM

●​ 123total
●​ total123
XM

3. Identifiers are case-sensitive. Of course, Python is a case-sensitive language.


●​ total=10
●​ TOTAL=999
LA

●​ print(total) #10
●​ print(TOTAL) #999
Identifier:
A

1.​ Alphabet Symbols (Either Upper case OR Lower case)


2.​ If the identifier starts with underscore (_), then it indicates it is private.
AY

3.​ Identifiers should not start with Digits.


4.​ Identifiers are case-sensitive.
5.​ We cannot use reserved words as identifiers Eg: def=10
IJ

6.​ There is no length limit for Python identifiers. But it is not recommended to use too lengthy
identifiers.
B

7.​ dollar ($) symbol is not allowed in Python.


Q. Which of the following are valid Python identifiers?


1)​ 123total


2)​ total123


3)​ java2share
4)​ ca$h


5)​ _abc_abc_


6)​ def
7)​ if

Note:
1. If identifier starts with _ symbol, then it indicates that it is private

TY
2. If the identifier starts with __(two underscore symbols), this indicates a strongly private identifier.
3. If the identifier starts and ends with two underscore symbols, then the identifier is
language-defined special name,which is also known as magic methods

N
. Eg: __add_
Reserved Words

A
➢​ In Python, some words are reserved to represent some meaning or functionality. Such types

H
of words are called reserved words.
➢​ There are 33 reserved words available in Python.

O
●​ True,False, None
●​ and, or, not, is
IM
●​ if,elif,else
●​ while,for,break,continue,return,in,yield
●​ Try,except,finally,raise,assert
XM

●​ import,from,as,class,def,pass,global,nonlocal,lambda,del,with
Note:
1. All reserved words in Python contain only alphabetical symbols.
2. Except the following 3 reserved words, all contain only lower case alphabet symbols.
LA

●​ True
●​ False
●​ None
A


AY


Eg: a= true
a=True
IJ

TO SEE THE KEYWORDS IN CONSOLE—


>>> import keyword
B

>>> [Link]
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else',
'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or',
'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Variables:
●​ A variable in Python is a named storage location used to store data values. Variables are created
when you assign a value to them.
●​ Python is a dynamically typed language, which means you don't have to declare the type of a
variable explicitly; it is inferred at runtime.

Naming Rules for Variables:


●​ Valid Characters: Variable names can contain letters (a-z, A-Z), numbers (0-9), and underscores
(_).

TY
●​ They cannot start with a number.
●​ Case-sensitivity: Python is case-sensitive. For example, myVar and myvar are treated as two
different variables.

N
●​ Reserved Words: Avoid using Python reserved words (keywords) as variable names. Examples
include if, else, while, for, etc.

A
●​ Meaningful Names: Choose descriptive and meaningful variable names that reflect the purpose
of the variable.

H
●​ Avoid Special Characters: Special characters (except underscores) are not allowed in variable
names. For example, my$var is not a valid variable name.

O
●​ Conventions: Follow Python naming conventions. For example, use lowercase with underscores
IM
for variable names (snake_case).
●​ Assignment Operator(=) is used to assign a value on the right side and variable on the left side.

Eg:- (variable)---> X = --->(assignment operator) 12 < —--- (value )


XM

Example: Variable and Naming Rules:


LA

# Valid variable names


my_var = 10
user_age = 25
total_sum = my_var + user_age
A
AY

# Invalid variable names


# 1invalid = 5 # Variable names cannot start with a number
# my-var = 7 # Hyphen is not allowed in variable names
IJ

# if = 3 # Avoid using reserved words as variable names

# Following conventions
B

user_name = "Alice"
user_email = "alice@[Link]"
In this example, my_var, user_age, and total_sum are valid variable names, following the naming
rules. The commented-out lines show examples of invalid variable names that violate the rules.

➢​ Local and Global Variables:


In Python, variables can be categorized into two main types based on their scope: global
variables and local variables.
●​ Global Variables: A global variable is defined outside of any function and is accessible
throughout the entire program, including inside functions.

Example:

global_var = 10 # This is a global variable


def print_global_var():
print(global_var)
print_global_var() # Output: 10
In this example, global_var is a global variable accessible both outside and inside the function

TY
print_global_var.

N
●​ Local Variables: A local variable is defined inside a function and is only accessible within that
function. It is not visible to code outside the function.

A
Example:

H
def print_local_var():

O
local_var = 20 # This is a local variable
print(local_var)
IM
print_local_var() # Output: 20
# Trying to access local_var outside the function will result in an error.
# Uncommenting the line below will result in a NameError.
XM

# print(local_var)
In this example, local_var is a local variable that is only accessible within the function
print_local_var.
LA

Using Global Variables Inside Functions:

If you want to modify a global variable inside a function, you need to use the global keyword.
A

Example:
AY

global_var = 10
IJ

def modify_global_var():
global global_var
B

global_var = 30

modify_global_var()
print(global_var) # Output: 30
In this example, the modify_global_var function uses the global keyword to indicate that it is
modifying the global variable global_var. After calling the function, the value of global_var
outside the function is changed.
NOTE:

While global variables provide a way to share data across different parts of a program, it's
generally a good practice to use them judiciously. Overuse of global variables can lead to code
that is harder to understand and maintain. In many cases, passing values as parameters and
returning values from functions is a cleaner and more modular approach.

Remember that local variables in functions are confined to the scope of that function, and
modifying them does not affect variables with the same name outside the function.

TY
Data Types:
●​ Data Type represents the type of data present inside a variable.
●​ In Python we are not required to specify the type explicitly. Based on the value provided,the

N
type will be assigned [Link] Python is Dynamically Typed Language.
●​ Every value in Python has a data type. It is a set of values, and the allowable operations on

A
those values.
●​ It helps to understand the kind of operations that can be performed.

H
●​ Primarily Data types are 6 types in Python:

O
➔​ Numeric Type
➔​ Boolean
IM
➔​ Sets
➔​ Mapping
➔​ Sequence
➔​ Binary
XM

➢​ Numeric Types:
●​ int: Integer type, e.g., x = 5.
●​ float: Floating-point type, e.g., y = 3.14.
●​ complex: Complex number type, e.g., z = 2 + 3j.
LA

Code:
# int
A

x=5
print(x, type(x))
AY

5 <class 'int'>

# float
IJ

y = 3.14
print(y, type(y))
B

3.14 <class 'float'>


# complex
z = 2 + 3j
print(z, type(z))
(2+3j) <class 'complex'>
➢​ Sequence Types:
●​ str: String type, e.g., name = "John".
●​ list: List type, e.g., numbers = [1, 2, 3]

●​ tuple: Immutable sequence, e.g., coordinates = (10, 20).

Code:
# str
name = "John"
print(name, type(name))

TY
John <class 'str'>

# list

N
numbers = [1, 2, 3]
print(numbers, type(numbers))

A
[1, 2, 3] <class 'list'>

H
# tuple

O
coordinates = (10, 20)
print(coordinates, type(coordinates))
IM
(10, 20) <class 'tuple'>
XM

➢​ Set Types:
●​ set: Set type, e.g., my_set = {1, 2, 3}.

Code:
LA

# set
my_set = {1, 2, 3}
print(my_set, type(my_set))
{1, 2, 3} <class 'set'>
A
AY

➢​ Mapping Type:
●​ dict: Dictionary type, e.g., person = {'name': 'John', 'age': 30}.

Code:
IJ

# dict
person = {'name': 'John', 'age': 30}
B

print(person, type(person))

➢​ Boolean Type:
●​ bool: Boolean type, either True or False.

Code:
# dict
person = {'name': 'John', 'age': 30}
print(person, type(person))
{'name': 'John', 'age': 30} <class 'dict'>

➢​ None Type:
●​ NoneType: Represents the absence of a value, often denoted as None.

Code:
# NoneType

TY
no_value = None
print(no_value, type(no_value))
None <class 'NoneType'>

N
➢​ Specialized Numeric Types:
●​ Decimal: Fixed-point and floating-point arithmetic, e.g., from decimal import Decimal.

A
●​ Fraction: Rational numbers, e.g., from fractions import Fraction.

H
Code:
# Decimal

O
from decimal import Decimal
decimal_number = Decimal('3.14')
IM
print(decimal_number, type(decimal_number))
3.14 <class '[Link]'>
XM

# Fraction
from fractions import Fraction
fraction_number = Fraction(3, 4)
print(fraction_number, type(fraction_number))
LA

3/4 <class '[Link]'>


➢​ Binary Types:
●​ bytes: Immutable sequence of bytes, e.g., binary_data = b'hello'.
A

●​ bytearray: Mutable sequence of bytes, e.g., mutable_binary = bytearray(b'hello').


●​
AY

memoryview: A view object that exposes an array’s buffer interface.

# bytes
binary_data = b'hello'
IJ

print(binary_data, type(binary_data))
b'hello' <class 'bytes'>
B

# bytearray
mutable_binary = bytearray(b'hello')
print(mutable_binary, type(mutable_binary))
bytearray(b'hello') <class 'bytearray'>
➢​ Other Built-in Types:
●​ range: Represents a range of numbers, e.g., my_range = range(5).

# range
my_range = range(5)
print(my_range, type(my_range))
range(0, 5) <class 'range'>
➢​ User-Defined Types:

TY
●​ class: Allows you to define your own types using classes.

Python contains the following inbuilt data types

N
1.​ Int
2.​ float

A
3.​ complex

H
4.​ bool
5.​ str

O
6.​ bytes
IM
7.​ bytearray
8.​ range
9.​ list
XM

10.​tuple
11.​set
12.​frozenset
13.​dict
LA

14.​None

Note: Python contains several inbuilt functions


A

[Link]() -to check the type of variable


AY

2. id() - to get address of object


3. print() -to print the value In Python everything is object
In Python everything is object
IJ
B

You might also like