0% found this document useful (0 votes)
24 views31 pages

My Notes

Python is a high-level programming language created by Guido van Rossum in 1991, designed for readability and ease of use. It supports various programming paradigms, including object-oriented programming, and is widely used in web development, AI, game development, and more. Python features a large standard library, dynamic typing, and a strong community, making it versatile for numerous applications.

Uploaded by

saisrireddy634
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views31 pages

My Notes

Python is a high-level programming language created by Guido van Rossum in 1991, designed for readability and ease of use. It supports various programming paradigms, including object-oriented programming, and is widely used in web development, AI, game development, and more. Python features a large standard library, dynamic typing, and a strong community, making it versatile for numerous applications.

Uploaded by

saisrireddy634
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

UNIT -I

History of python:

python is a widely used general-purpose, high-level programming language created by Guido


van Rossum in 1991. It was primarily developed to improve the readability of code, allowing
developers to write codes in fewer lines.

The first public version, Python 0.9.0, was released in February 1991, and it was the first to
offer functions, modules, exception handling, and dynamic typing - making it possible for
users to program what they wanted with ease.
Why is Python built?

Guido Van Rossum needed to build a language which was:

 Interpreted Programming Language:


Python does not need compilation like languages like C or Java, and that
makes coding and debugging much easier.

 Whitespace is Important:

Python lets its users define indentation as a part of the syntax; this helps
improve the organization of code and is more readable.
 High-Level Language:
Python is designed to be easy to read and write, using English-like keywords
and a simple syntax.
 Dynamic Typing:
Python does not require explicit type declarations; the type of a variable is
determined at runtime.
 Object-Oriented Programming:
Python supports object-oriented programming concepts like classes, objects,
inheritance, and polymorphism.
 Open Source and Free:
Python is free to use and distribute, and its open-source nature fosters a large
and active community.
 Cross-Platform:
Python code can run on various operating systems (Windows, macOS, Linux)
without modification.
 Large Standard Library:
Python comes with a comprehensive standard library that provides a wide
range of modules and functions for common tasks.
 Large Community Support:
The Python community is large and active, providing ample resources,
tutorials, and support for developers.
 versatile and Flexible:
Python can be used for a wide range of applications, including web
development, data analysis, machine learning, scripting, and more.
 Readability:
Python emphasizes code readability, using whitespace for formatting and
English keywords, making it easier to understand and maintain.
 Frameworks:
frameworks for various tasks, such as web development (Django, Flask), data
science (NumPy, Pandas, Scikit-learn), and more.

Applications of Python

1. Web Development

Python is widely used in web development. It makes use of simple code to build a beautiful
and functional website.

2. Artificial Intelligence and Machine Learning

Many AI and ML models are built using Python. Data analysts use it too. The fundamental
cause for this is the availability of many tools and libraries specific to these applications.

3. Game Development

One of the interesting applications of the Python Programming language is to build games
like egg catcher, snake game, etc.

4. Desktop GUI Development

Its simplicity and platform independence nature make it a good choice for GUI applications.

5.Software Development
Python supports the development of software with its libraries and packages. It is used for
building, testing, management, and so on.

6. Educational Purposes

Python helps beginners get introduced to the Programming environment. It is because of its
simple syntax and beginner-friendly nature.

7. Operating Systems Development

Many operating systems are using Python as a backbone. Generally, it is used along with C.

8. Language Development

Yes! Python being one of the programming languages helps in building other languages.
These have similar syntax object models and indentation as compared to Python.

9. Web Scraping

Nowadays, Python is being widely used for web scraping purposes. We can access the huge
data over the internet using these web scraping techniques.

10.Data Science and Data Analysis

Data Science and Data Analysis are two of the booming fields in the market. This involves
analysis of a huge amount of data, finding relations and doing future predictions.

FRAMEWORKS :
 Pandas for Data Manipulation and Analysis.

 NumPy and SciPy for mathematical computations.

 Seaborn and Matplotlib for visualization.

 Scikit learn, Tensor Flow, Keras for algorithms

 Flask a microframework known for its flexibility and simplicity,

Variables
 Variables are containers for storing data values.
 Variable names can contain letters, numbers, and underscores.
 They must start with a letter or an underscore.
 Variable names are case-sensitive (e.g., age, Age, and AGE are distinct variables).
 Avoid using Python's reserved keywords as variable names.
Creating Variables
 Python has no command for declaring a variable.
 A variable is created the moment you first assign a value to it.
 Variables do not need to be declared with any particular type, and can even change type
after they have been set.

Example
x=5
y = "John"
print(x)
print(y)

Get the Type


You can get the data type of a variable with the type() function.
Example
x=5
y = "John"
print(type(x))
print(type(y))

Case-Sensitive: Variable names are case-sensitive.

Example

This will create two variables:

a=4
A = "Sally"

DIFFERENT VALUES TO MULTIPLE VARIABLES

A,b,c=1,”sri”,4.5

Print(a)

Print(b)

Print(c)

Type Casting a Variable

Type Casting is the process of converting the value of one data type into another. In some
cases, Python automatically converts types. However, there are few built-in functions
like int(), float(), str() and more.

Implicit type conversion happens automatically by the interpreter.

explicit type conversion, also known as type casting, is done by the programmer using built-
in functions.
Example

# type casting

a = 10 # int

# implicit type casting

b=a/3

print(b)

# int -> float

# explicit type casting

b= int(b)

print(b)

# float -> int

output:

3.33

Keywords

Python has a set of keywords that are reserved words that cannot be used as variable
names, function names, or any other identifiers:

Keyword Description

and A logical operator

break To break out of a loop

class To define a class

continue To continue to the next iteration of a loop


def To define a function

del To delete an object

elif Used in conditional statements, same as else if

else Used in conditional statements

except Used with exceptions, what to do when an exception occurs

False Boolean value, result of comparison operations

finally Used with exceptions, a block of code that will be executed no matter if
there is an exception or not

for To create a for loop

from To import specific parts of a module

global To declare a global variable

if To make a conditional statement

import To import a module

in To check if a value is present in a list, tuple, etc.

is To test if two variables are equal

lambda To create an anonymous function

None Represents a null value

not A logical operator


or A logical operator

pass A null statement, a statement that will do nothing

raise To raise an exception

return To exit a function and return a value

True Boolean value, result of comparison operations

try To make a try...except statement

while To create a while loop

with Used to simplify exception handling

yield To return a list of values from a generator

Operators:
Operators are the symbols used to perform a specific operation on different
values and variables. These values and variables are considered as
the Operands, on which the operator is applied. Operators serve as the
foundation upon which logic is constructed in a program in a particular
programming language.
Different types of Operators used in Python are as follows:
1. Arithmetic Operators
2. Comparison Operators
3. Assignment Operators
4. Logical Operators
5. Bitwise Operators
6. Membership Operators
S. No. Operator Syntax Description

1 + (Addition) r=a+b Used to add


two operands.
7. Identity Operators
For example, if
a = 15, b = 10
=> a + b = 15 +
10 = 25

2 - (Subtraction) r=a-b This operator is


used to
subtract the
second
operand from
the first
operand. if a =
20, b = 5 => a -
b = 20 – 5 = 15

3 / (divide) r=a/b This operator


returns the
quotient if a =
15, b = 4 => a /
b = 15 / 4 =
3.75

4 * (Multiplication) r=a*b This operator is


used to
multiply one
operand with
the other. if a =
20, b = 4 => a *
1. Comparison Operators b = 20 * 4 = 80

5 % (reminder) r=a%b This operator


returns the
reminder if a =
20, b = 10 => a
% b = 20 % 10 =
0

6 ** (Exponent) r = a ** b calculates the


first operand's
power to the
second
 comparison operators are mainly used for the purpose of
comparing two values or variables (operands) and return a
Boolean value as either True or False accordingly.

S. No. Operator Syntax Description

1 == a == b Equal to: If the value of two


operands is equal, then the
condition becomes true.

2 != a != b Not Equal to: If the value of two


operands is not equal, then the
condition becomes true.

3 <= a <= b Less than or Equal to: The condition


is met if the first operand is smaller
than or equal to the second operand.

4 >= a >= b Greater than or Equal to: The


condition is met if the first operand
is greater than or equal to the
second operand.
5 > a>b Greater than: If the first operand is
greater than the second operand,
then the condition becomes true.

6 < a<b Less than: If the first operand is less


than the second operand, then the
condition becomes true.

a = 46 # Initializing the value of a


b=4 # Initializing the value of b
# printing different results
If(a==b):
print(' Two numbers are equal or not:')
elif(a!=b):
print(‘Two numbers are not equal or not:')
elif(a<=b):
print(' a is less than or equal to b:')
elif(a>=):
print(' a is greater than or equal to b:')
elif(a>b):
print('a is greater b:')
else:
print('a is less than b:')

2. Assignment Operators:
 the right expression's value is assigned to the left operand.
Python offers different assignment operators to assign values to
the variable.

S. No. Operator Syntax Description

1 = a=b+c This operator assigns the


value of the right expression
to the left operand.

2 += a += b => a = a + b Add AND: This operator adds


the operand on the right side
to the operand on the left side
and assigns the resultant
value to the left operand

3 -= a -= b => a = a - b subtract AND: This operator


subtracts the operand on the
right side from the operand
on the left side and assigns
the resultant value to the left
operand.

4 *= a *= b => a = a * b Multiply AND: This operator


multiplies the operand on the
right side with the operand on
the left side and assigns the
resultant value to the left
operand

5 /= a /= b => a = a / b Divide AND: This operator


divides the operand on the
left side with the operand on
the right side and assign the
resultant value to the left
operand.

6 %= a %= b => a = a % Modulus AND: This operator


b calculates the modulus of
using the left-side and right-
side operands and assigns the
resultant value to the left
operand.

7 **= a **= b => a = a Exponent AND: This operator


** b calculates the exponent value
using the operands on both
side and assign the resultant
value to the left operand.

8 //= a //= b => a = a // Divide (floor) AND: This


b operator divides the operand
on the left side with the
operand on the right side and
assign the resultant floor
value to the left operand.

Example:
a = 34 # Initialize the value of a
b=6 # Initialize the value of b

# printing the different results


print('a += b:', a + b)
print('a -= b:', a - b)
print('a *= b:', a * b)
print('a /= b:', a / b)
print('a %= b:', a % b)
print('a **= b:', a ** b)
print('a //= b:', a // b)

3. Logical Operators
 Python offers different types of logical operators such as and, or,
and not. In the case of the logical AND, if the first one is 0, it does
not depend upon the second one. In the case of the logical OR, if
the first one is 1, it does not depend on the second one.

S. No. Operator Syntax Description

1 and a and b Logical AND: The condition will


also be true if the expression is
true. If the two expressions a and
b are the same, then a and b both
must be true.

2 or a or b Logical OR: The condition will be


true if one of the phrases is true. If
a and b are the two expressions,
then either a or b must be true to
make the condition true.

3 not not a Logical NOT: If an expression a is


true, then not (a) will be false and
vice versa.

4. Bitwise Operators
 he two operands' values are processed bit by bit by the bitwise
operators. There are various Bitwise operators used in Python,
such as bitwise OR (|), bitwise AND (&), bitwise XOR (^),
negation (~), Left shift (<<), and Right shift (>>).

S. No. Operator Syntax Description

1 & a&b Bitwise AND: 1 is copied to the result if


both bits in two operands at the same
location are 1. If not, 0 is copied.

2 | a|b Bitwise OR: The resulting bit will be 0 if


both the bits are zero; otherwise, the
resulting bit will be 1.

3 ^ a^b Bitwise XOR: If the two bits are different,


the outcome bit will be 1, else it will be 0.

4 ~ ~a Bitwise NOT: The operand's bits are


calculated as their negations, so if one bit is
0, the next bit will be 1, and vice versa.

5 << a << Bitwise Left Shift: The number of bits in the


right operand is multiplied by the leftward
shift of the value of the left operand.

6 >> a >> Bitwise Right Shift: The left operand is


moved right by the number of bits present
in the right operand.

a=7 # initializing the value of a


b=8 # initializing the value of b
# printing different results
print('a & b :', a & b)
print('a | b :', a | b)
print('a ^ b :', a ^ b)
print('~a :', ~a)
print('a << b :', a << b)
print('a >> b :', a >> b)

output:
a&b:0
a | b : 15
a ^ b : 15
~a : -8
a << b : 1792
a >> b : 0
5. Membership Operators
 We can verify the membership of a value inside a Python data
structure using the Python membership operators. The result is
said to be true if the value or variable is in the sequence (list,
tuple, or dictionary); otherwise, it returns false.

S. No. Operator Description

1 in If the first operand (value or variable) is present in the


second operand (sequence), it is evaluated to be true.
Sequence can either be a list, tuple, or dictionary

2 not in If the first operand (value or variable) is not present in


the second operand (sequence), the evaluation is true.
Sequence can either be a list, tuple, or dictionary

# initializing a list
myList = [12, 22, 28, 35, 42, 49, 54, 65, 92, 103, 245, 874]

# initializing x and y with some values


x = 31
y = 28

# printing the given list


print("Given List:", myList)

# checking if x is present in the list or not


if (x not in myList):
print("x =", x,"is NOT present in the given list.")
else:
print("x =", x,"is present in the given list.")

output:
Given List: [12, 22, 28, 35, 42, 49, 54, 65, 92, 103, 245, 874]
x = 31 is NOT present in the given list.
6. Identity Operators
 Operators that are used to check if two values are located on the
same part of the memory.

S. No. Operator Description

1 is If the references on both sides point to the


same object, it is determined to be true.

2 is not If the references on both sides do not point at


the same object, it is determined to be true.

Indentation
Python relies on indentation (whitespace at the beginning of a line) to define
scope in the code. Other programming languages often use curly-brackets for
this purpose.
Example
If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error

a = 33
b = 200
if b > a:
print("b is greater than a")

Input and Output in Python


Python input() function is used to take user input. By default, it returns the
user input in form of a string.

>> name = input("Enter your name: ")


print(name)

>>name=”john”
Print(name)

Printing Output using print() in Python


 we can simply use the print() function to print output.
 The print() function is taking a single parameter.
Example:
print('Good Morning students')
print('we are from MCA')
output:
Good Morning students
we are from MCA

Python print() with end Parameter


# print with end whitespace
print('Good Morning students', end= ' ')
print('we are from MCA')

output:
Good Morning students we are from MCA

Expressions in Python
An expression is a combination of operators and operands that
produces some other value. an expression is evaluated as per the precedence
of its operators. their precedence decides which operation will be performed
first
There are different types of expressions in Python.
1. Arithmetic Expressions
x = 2
y = 4

add = x + y
sub = x - y
pro = x * y
div = x / y

print(add)
print(sub)
print(pro)
print(div)
Operator Precedence
It is simple to process if there is only operator in an expression but if there are multiple
operators it is quite complex to evulate.it may give different results based on order of
evaluating the expression.

Operator Precedence simply defines the priority of operators that which operator is to be
executed first.

nt

Example:

# Multiplication has higher precedence


# than subtraction
>>> 10 - 4 * 2
2
# Parentheses () has higher precedence
>>> (10 - 4) * 2
12
Conditional Statements
Conditional statements in Python allow your program to make decisions based on certain
conditions. They form the backbone of decision-making in programming,
The if Statement
The if statement is the simplest form of a conditional statement. It checks whether a specific
condition is true and executes the associated block of code if it is. If the condition is
evaluated as false, the program skips the block and continues with the rest of the code.
Syntax:
if condition :

Example:
Number=12
If number>10:
Print(“the number is greater then 10”)

The if-else Statement


The if-else statement extends the functionality of the if statement by providing an alternative
path of execution when the condition is evaluated as false. This ensures that a block of code
is executed whether the condition is true or false.
Syntax:
if condition :
# code is executed if the condition is true
Else:
# code is executed if the condition is false

Example:
age=18
If age>=18:
Print(“you are eligible to vote”)
else:
Print(“you are not eligible to vote”)

The if-elif-else
The if-elif-else provides a multi-condition functionality to evaluates multiple conditions
sequentially executing the first block whose condition evaluates to true. If none of the
conditions are true, the else block runs.
Syntax:
if condition 1:
# code is executed if the condition is true
elif condition 2:
# code is executed if the condition is true
elif condition 3:
# code is executed if the condition is true
else:
# code is executed if the condition is false
Example:
Marks=90
If marks >=90
Print(“Grade: A”)
elif marks >=75:
Print (“Grade: B”)
elif marks >=50:
print (Grade: C”)
else:
print(“Grade: F”)

Looping Statements
Looping statements in Python allow you to execute a code block based on a condition
repeatedly. They are essential when performing repetitive tasks like iterating through a
list.

The for Loop


The for loop iterates over a sequence, such as a list, tuple, string, or range. It processes each
item in the sequence one by one,
Syntax:
For variable in sequence:
# code to execute for each item in the sequence

Example:
Cars=[Toyoa,Maruthi,Hyundai,Mahindra]
For car in cars:
Print(cars)

The while Loop


The while loop executes a code block if a specified condition remains true. where the number
of iterations depends on dynamic conditions.

Syntax:
While condition:
#executes if the condition is true

Example:
Count=1
While count<=5:
Print(count)
Count +=1
Jump Statements
Jump statements in Python allow you to control the flow of loops and conditional blocks by
altering the standard execution sequence. program immediately stops the current iteration and
exits the loop.

Syntax:
For items in iteration :
If condition:
break

Example:
For n in range(1,10):
If n ==5:
break
Print(n)

The continue Statement


The continue statement used to skip the current iteration of a loop and proceed directly to the
next iteration. It doesn’t terminate the loop but bypasses the remaining code in the current
cycle.

Syntax:
For items in iteration :
If condition:
Continue

Example:
For n in range(1,20):
If n %2==0:
Continue
Print(n)

The pass Statement


The pass statement is a placeholder that does nothing when executed. It is often used as a
temporary stand-in for code that will added later or to define an empty block where syntax
requires some content.
Syntax:
If condition:
Pass

Example:
For n in range(1,10):
If n ==5:
Pass
else:
Print(n)

Python Functions
Python Functions is a block of statements that return the specific task. The idea is to put
repeatedly done tasks together and make a function so that instead of writing the same code
again and again for different inputs, we can do the function calls to reuse code contained in it
over and over again.
Benefits of Using Functions
 Increase Code Readability
 Increase Code Reusability
Python Function Declaration
Types of Functions in Python
 Built-in library function: These are Standard functions in Python that are available
to use.
 User-defined function: We can create our own functions based on our requirements.
Creating a Function in Python
We can define a function with the def keyword. We can add any type of functionalities and
properties to it as we require. we can create Python function definition by using def keyword.

def fun():
print("Hello Students”)

Calling a Function in Python


After creating a function we can call it by using the name of the functions parenthesis
containing parameters of that particular function.

def fun():
print(" How are you")
# Driver code to call a function
fun()
Output:
How are you
Python Function Syntax with Parameters
def function_name(parameter: data_type) -> return_type:
# body of the function
return expression

Example 1:
def add(num1: int, num2: int) -> int:
"""Add two numbers"""
num3 = num1 + num2
return num3
# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print( ans)

Output
20

Python Function Arguments


Arguments are the values passed inside the parenthesis of the function. A function can have
any number of arguments separated by a comma.

Example:
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")

# Driver code to call the function


evenOdd(2)
evenOdd(3)

Output
even
odd

Types of Python Function Arguments


Various types of arguments that can be passed at the time of the function call
1. Default argument
2. Keyword arguments (named arguments)
3. Positional arguments
4. Arbitrary arguments (variable-length arguments *args and **kwargs)
1. Default Arguments
A default argument is a parameter that assumes a default value if a value is not provided in
the function call for that argument.

Example:
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
myFun(10)

Output
x: 10
y: 50

2. Keyword Arguments
To specify the argument name with values so that the caller does not need to remember the
order of parameters.
def student(firstname, lastname):
print(firstname, lastname)
student(firstname=”Sai Sri”, lastname=” Reddy'')
student(lastname='Reddy', firstname='Sai Sri')

Output
Sai Sri Reddy
Reddy Sai Sri

Positional Arguments
We used the Position argument during the function call so that the first argument is assigned
to name and the second argument is assigned to age. By changing the position, or if you
forget the order of the positions, the values can be used in the wrong places.
def fun1(name, age):
print( name)
print( age)
fun1("SRI", 27)
fun1(27, "SRI")

Output
SRI 27
27 SRI

Arbitrary Keyword Arguments


Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable number of
arguments to a function using special symbols. There are two special symbols:
 *args in Python (Non-Keyword Arguments)
 **kwargs in Python (Keyword Arguments)
Example 1: Variable length non-keywords argument
def Fun(*argv):
for arg in argv:
print(arg)
Fun(“HI)

Output
HI

Example 2: Variable length keyword arguments


def Fun(**kwargs):
for key, value in kwargs.items():
print( (key, value))
Fun(first=''M”, mid='C ', last='A')

Output
first == M
mid == C
last == A
Anonymous Functions in Python
An anonymous function means that a function is without a name. As we already know the def
keyword is used to define the normal functions and the lambda keyword is used to create
anonymous functions.
EXAMPLE:
def cube(x): return x*x*x
cube_v2 = lambda x : x*x*x
print(cube(7))
print(cube_v2(7))

Output
343
343

You might also like