You are on page 1of 53

UNIT-1

PYTHON
Python Interpreter and its working

● Python is an object-oriented programming language like Java. Python is called an interpreted


language.
● The standard implementation of Python is called “cpython”.

● The byte code (.pyc or .pyo) can’t be understood by the CPU. So we need an interpreter called
the Python virtual machine to execute the byte codes.
How Python Code Works?
Data types in Python

A variable can contain a variety of values. On the other hand, a person's id must be stored as an integer,
while their name must be stored as a string.

The storage method for each of the standard data types that Python provides is specified by Python. The
following is a list of the Python-defined data types.

1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
Numbers
Numeric values are stored in numbers. The whole number, float, and complex qualities have a place
with a Python Numbers datatype. Python offers the type() function to determine a variable's data
type. The instance () capability is utilized to check whether an item has a place with a specific class.

When a number is assigned to a variable, Python generates Number objects. For instance,

1. a=5
2. print("The type of a", type(a))
3.
4. b = 40.5
5. print("The type of b", type(b))
6.
Python Numbers

● The number data types are used to store the numeric values inside the
variables.
● Number objects are created when some value is assigned to a variable. For
example, a = 5 will create a number object a with value 5.
● Python also allows us to delete the reference of a number by using the del
keyword. For example, del a will delete the object a declared above.
● In Python, there are four types of numbers that can be assigned to a variable
● Int (signed Integer object) : they are the negative or non-negative numbers with no decimal
point.
● There is no limit on an integer in python.

Prefix Interpretation Base Example

0b Binary 2 0b10 = 2 (decimal)


0B 0b1010 = 10 (decimal)
0B101 = 5 (decimal)

0o Octal 8 0o10 = 8
0O 0o12 = 10
0O132 =decimal

0x Hexadecimal 16 0xA = 10
0X 0xB = 11
0XBE = 190
➔ float (floating point numbers) :
◆ The float type is used to store the decimal point (floating point) numbers.
◆ In python, float may also be written in scientific notation representing the power
of 10. for example, 2.5e2 represents the value 250.0.
➔ Complex (complex numbers):
◆ Complex numbers are of the form a+bj where a is the real part of the number and
bj is the imaginary part of the number.
◆ The imaginary i is nothing but the square root of -1. It is not as much used in the
programming.
Number type conversion

○ int (a) converts a to integer.


○ float(a) converts a to float.
○ complex(a) converts a to complex.
○ complex (a,b) converts a and b to complex numbers with real
part a and imaginary part b.

Example:

i="123456"
print(type(i))
num = int(i)
print(num)
print(type(num))
j = 190.98
print(int(j));
Function Description

abs(x) The (positive) distance between x and 0.

ciel(x) The ceiling value of x, i.e., the smallest integer that is not less than x.

cmp(x,y) Compares x and y. It returns 0 if x == y, -1 if x<y, 1 if x > y.

exp(x) The exponent of x that is ex.

fabs(x) The absolute value of x.

floor(x) The floor value of x, i.e., the greatest integer that is less than x.

log(x) The natural log value of x.

max(x1,x2, ......) The maximum of the sequence is returned.

min(x1,x2,.....) The minimum of the sequence is returned.

pow(x,y) Returns x ** y.

round(x) The value of x is rounded to n digits.

sqrt(x) The square root of x is returned.


Sequence 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.
● String dealing with Python is a direct undertaking since Python gives worked-in capabilities and administrators to
perform tasks in the string.
● When dealing with strings, the operation "hello"+" python" returns "hello python," and the operator + is used to
combine two strings.
● Because the operation "Python" *2 returns "Python," the operator * is referred to as a repetition operator.

Example:

1. str1 = 'hello javatpoint' #string str1


2. str2 = ' how are you' #string str2
3. print (str1[0:2]) #printing first two character using slice operator
4. print (str1[4]) #printing 4th character of the string
5. print (str1*2) #printing the string twice
6. print (str1 + str2) #printing the concatenation of str1 and str2
Things to remember

Reassigning Strings

● Updating the content of the strings is as easy as assigning


it to a new string.
● The string object doesn't support item assignment i.e.,
● A string can only be replaced with new string since its
content cannot be partially replaced.

Strings are immutable in Python.


str = "HELLO"
str[0] = "h"
print(str)

1. str = "HELLO"
2. print(str)
3. str = "hello"
4. print(str)
String Operators

+ It is known as concatenation operator used to join the strings given either side of the operator.

* It is known as repetition operator. It concatenates the multiple copies of the same string.

[] It is known as slice operator. It is used to access the sub-strings of a particular string.

[:] It is known as range slice operator. It is used to access the characters from the specified range.

in It is known as membership operator. It returns if a particular sub-string is present in the specified


string.

not in It is also a membership operator and does the exact reverse of in. It returns true if a particular
substring is not present in the specified string.

r/R It is used to specify the raw string. Raw strings are used in the cases where we need to print the actual
meaning of escape characters such as "C://python". To define any string as a raw string, the character
r or R is followed by the string.

% It is used to perform string formatting. It makes use of the format specifiers used in C programming like
%d or %f to map their values in python. We will discuss how formatting is done in python.
List
A list is an ordered and mutable collection of items. It's one of Python's fundamental data
structures, used to store multiple values in a single variable.

Key characteristics of lists:

● Ordered: Items have a specific order, with each assigned a unique index starting from
0.
● Mutable: You can change, add, or remove items after the list is created.
● Can hold mixed data types: A single list can contain elements of different data types
(e.g., numbers, strings, other lists).
● Created using square brackets: []
Basic operations on lists:

● Creating a list: my_list = ["apple", 5, True]


● Accessing elements: first_item = my_list[0]
● Adding elements: my_list.append("banana")
● Removing elements: my_list.remove(5)
● Iterating through elements: for item in my_list: print(item)
● Getting the length (number of items): list_length = len(my_list)

Common use cases:

● Storing collections of data


● Representing sequences of information
● Organizing and manipulating data in various algorithms
● Implementing data structures like stacks and queues
Operation Description Example Code Output

Accessing Retrieve a specific element my_list = [10, 20, 30] 20


elements by its index print(my_list[1])

Adding elements

append() Add an element to the end of my_list.append(40) [10, 20, 30, 40]
the list print(my_list)

insert() Add an element at a specific my_list.insert(2, "hello") [10, 20, "hello", 30, 40]
index print(my_list)

count() Count the occurrences of a apple_count = 2


value fruits.count("apple")
print(apple_count)
Sorting Arrange elements numbers = [3, 1, 4, 2] [1, 2, 3, 4]
in ascending order numbers.sort()
print(numbers)

Reversing Reverse the order numbers.reverse() [4, 3, 2, 1]


of elements print(numbers)

Iterating Loop through each for item in numbers: print(item) 4<br/>3<br/>2<br/>1


element in the list

Getting Determine the list_length = len(numbers) 4


length number of elements print(list_length)

Removing elements

remove() Remove the first my_list.remove(20) [10, "hello", 30, 40]


occurrence of a print(my_list)
specified value
pop() Remove the removed_item = my_list.pop(1) [10, 30, 40], "hello"
element at a print(my_list, removed_item)
specific index
(default is the
last)

Slicing Extract a sublist = my_list[1:3] [30, 40]


portion of the print(sublist)
list

Modifying Change the my_list[0] = 50 [50, 30, 40]


elements value of an print(my_list)
existing
element

Finding elements

index() Find the index fruits = ["apple", "banana", "apple"] 0


of the first apple_index = fruits.index("apple")
occurrence of print(apple_index)
a value
Task:
1. Grocery List Management:
2. Grade sheet Calculation
3. Password Generator
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 with a comma (,) and encased inside square sections [].

To gain access to the list's data, we can use slice [:] operators. Like how they worked with strings,
the list is handled by the concatenation operator (+) and the repetition operator (*).

Tuple:

In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from various
data types. A parenthetical space () separates the tuple's components from one another.

Because we cannot alter the size or value of the items in a tuple, it is a read-only data structure.
# Creating a list and a tuple with the same elements
my_list = ["apple", "banana", "cherry"]
my_tuple = ("apple", "banana", "cherry")

# Accessing elements by index (same for both)


print(my_list[1]) # Output: banana
print(my_tuple[2]) # Output: cherry

# Iterating over elements (same for both)


for fruit in my_list:
print(fruit)

for fruit in my_tuple:


print(fruit)

# Modifying elements (only possible for lists)


my_list[0] = "mango" # Allowed for lists
try:
my_tuple[1] = "orange" # Raises an error for tuples
except TypeError as e:
print("Error:", e)

# Printing the modified list and the original tuple


print(my_list) # Output: ["mango", "banana", "cherry"]
print(my_tuple) # Output: ("apple", "banana", "cherry")
Dictionary

A dictionary is a key-value pair set arranged in any order. It stores a 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:
1. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}
2.
3. # Printing dictionary
4. print (d)
5.
6. # Accesing value using keys
7. print("1st name is "+d[1])
8. print("2nd name is "+ d[4])
9.
10. print (d.keys())
11. print (d.values())
Task: 4. Login credential verification using dictionary
Method Description

keys() Returns a view of all keys in the dictionary

values() Returns a view of all values in the dictionary

items() Returns a view of all key-value pairs as tuples

get(key, default) Returns the value for a key, or a default value if not
found

pop(key) Removes the key-value pair with the specified key and
returns the value

clear() Removes all items from the dictionary

copy() Returns a shallow copy of the dictionary


Boolean

● True and False are the two default values for the Boolean type. These qualities are utilized to
decide the given assertion valid or misleading.
● The class book indicates this. False can be represented by the 0 or the letter "F," while true
can be represented by any value that is not zero.

Example:

is_valid = True
is_finished = False
if is_valid and is_finished:
print("!both true")
Set

● A set is a data collection type used in Python for storing multiple items in a single variable. Sets in
Python are unordered and, as such, are not always consistent in the order they get returned.
● Furthermore, items in the set are immutable — ie. cannot be changed. However, items can be
added and removed.
Example
Key takeaways from this program:

● Creating sets: Use curly braces {} to create sets.


● Adding elements: Use set.add(element) .
● Removing elements: Use set.remove(element) .
● Checking membership: Use element in set .
● Getting the number of elements: Use len(set).
● Iterating over elements: Use for element in set: .
● Creating sets from lists: Use set(list).
● Set operations: Union (|), intersection (&), difference (-).
● Clearing sets: Use set.clear() .
Differences Between LIST, TUPLE and SET

Feature List Tuple Set

Syntax [] () {}

Mutability Mutable Immutable Mutable


(changeable) (unchangeable) (changeable)

Order Ordered Ordered Unordered (no


(maintains order) specific order)

Duplicates Allows duplicates Allows duplicates No duplicates

Use cases Ordered Fixed collections Membership


collections, testing, unique
sequences elements
Assignment

Definition:
● Assignment is the process of assigning a value to a variable, creating a link between the variable name and the
value it holds.
● It uses the = operator.
● The value on the right side of the = is evaluated and then stored in the variable on the left side.

Examples:
Assigning to a single variable:
x = 10 # Assigns the integer value 10 to the variable x
name = "Alice" # Assigns the string "Alice" to the variable name
is_valid = True # Assigns the boolean value True to the variable is_valid

Assigning to multiple variables simultaneously:


x, y, z = 1, 2, 3 # Assigns 1 to x, 2 to y, and 3 to z
Augmented assignment operators:
x += 5 # Equivalent to x = x + 5
y -= 2 # Equivalent to y = y - 2
z *= 3 # Equivalent to z = z * 3
Key points:

● Variables must be defined before using them in assignments.


● The right-hand side of the assignment is evaluated first.
● Assignments create references to values, not copies.
● Python supports multiple assignments in a single line.
● Augmented assignment operators combine assignment with arithmetic or bitwise operations.

Expression

● An expression is a combination of values, variables, operators, and function calls that evaluates to a single
value.
● It's a fundamental building block of Python code that represents computations and actions.
● It's essentially a code snippet that produces a result.

Arithmetic expressions:

2 + 3 # Evaluates to 5
10 - 4 * 2 # Evaluates to 2 (due to operator precedence)
15 / 3 # Evaluates to 5.0 (floating-point division)
String expressions:

"Hello" + " " + "World!" # Evaluates to "Hello World!"


"Python" * 3 # Evaluates to "PythonPythonPython" Key points:

Boolean expressions: ● Expressions are evaluated from left to


right, following operator precedence
5 > 3 # Evaluates to True rules.
10 == 10 # Evaluates to True ● Parentheses can be used to control the
not True # Evaluates to False
order of evaluation.
● Expressions can be used within
Variable expressions:
assignments, conditional statements,
x=4 loops, and function calls.
y=2 ● They form the core of Python's ability to
result = x * y # Evaluates to 8 perform calculations and manipulate
data.
Function calls:

len("hello") # Evaluates to 5 (length of the string)


max(5, 10, 2) # Evaluates to 10 (largest value)
Control Flow Statements
● Control flow statements are instructions that regulate the execution order of code
blocks, allowing decision-making, branching, and repetition.
● They control the flow of the program, making it more versatile and adaptable to
different scenarios.

Types of Control Flow Statements:

1. Conditional Statements:

2. Looping Statements
# Conditional Statements
if condition:
# Code to execute if condition is True

if condition:
# Code to execute if condition is True
else:
# Code to execute if condition is False

if condition1:
Examples
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition1 is False and condition2 is True
else:
# Code to execute if all previous conditions are False

# Loops
for item in sequence:
# Code to execute for each item

while condition:
# Code to execute while condition is True
Python Functions

Python Functions is a block of statements that return the specific task. The idea is to
put some commonly or 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.

Some Benefits of Using Functions


● Increase Code Readability
● Increase Code Reusability
Python Function Declaration
The syntax to declare a function is:
Syntax of Python Function Declaration
Types of Functions in Python
There are mainly two 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.

Few Examples for Built-in library function

Input and Output:


● print( ): Displays output to the console.
print("Hello, world!")

● input( ): Takes user input from the console.


name = input("What is your name? ")
print("Hello,", name + "!")
Data Type Conversion:
● int( ): Converts a value to an integer.
age = int(input("Enter your age: "))
● float( ): Converts a value to a floating-point number.
price = float(input("Enter the price: "))
● str( ): Converts a value to a string.
number = 10
text = "The number is " + str(number)

Mathematical Operations:
● abs( ): Returns the absolute value of a number.
distance = abs(-50) # distance will be 50
● pow( ): Raises a number to a power.
result = pow(2, 3) # result will be 8
● round( ): Rounds a number to a specified number of decimal places.
rounded_value = round(3.14159, 2) # rounded_value will be 3.14
● sum( ): Returns the sum of elements in an iterable (like a list or tuple).
numbers = [1, 2, 3, 4, 5]
total = sum(numbers) # total will be 15
String Manipulation:
● sorted( ): Returns a sorted list of elements in an iterable.
names = ["Alice", "Bob", "Charlie"]
sorted_names = sorted(names) # sorted_names will be ["Alice", "Bob", "Charlie"]

File Handling:
● open( ): Opens a file for reading or writing.
file = open("my_file.txt", "r") # Opens the file for reading

Help and Documentation:


● help( ): Accesses Python's built-in help system.
● help(print) # Displays help information about the print function
User defined function

# A simple Python function

def fun():
print("Welcome")

Creating a Function in Python


We can define a function in Python, using the def keyword. We can add any type of functionalities
and properties to it as we require.
Calling a Python Function

# A simple Python function


def fun():
print("Welcome")
# Driver code to call a function
fun()

Defining and calling a function with parameters


def function_name(parameter: data_type) -> return_type:
"""Docstring"""
# body of the function
return expression
Example:

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(f"The addition of {num1} and {num2} results {ans}.")

The addition of 5 and 15 results 20.


Python Function Arguments
# A simple Python function to check
# whether x is even or odd
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

Python supports various types of arguments that can be passed at the time of
the function call. In Python, we have the following 4 types of function
arguments.
● Default argument
● Keyword arguments (named arguments)
● Positional arguments
● Arbitrary arguments (variable-length arguments *args and **kwargs)
Default Arguments

# Python program to demonstrate


# default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)

# Driver code (We call myFun() with only


# argument)
myFun(10)

Output:
x: 10
y: 50
Keyword Arguments

# Python program to demonstrate Keyword


Arguments
def student(firstname, lastname):
print(firstname, lastname)

# Keyword arguments
student(firstname='hello', lastname='world')
student(lastname='hello', firstname='world')

Output:
hello world
Hello world
Positional Arguments

def nameAge(name, age):


print("Hi, I am", name)
print("My age is ", age)
Output:
Case-1:
# You will get correct output because Hi, I am Suraj
My age is 27
# argument is given in order
Case-2:
print("Case-1:") Hi, I am 27
nameAge("Suraj", 27) My age is Suraj
# You will get incorrect output because
# argument is not in order
print("\nCase-2:")
nameAge(27, "Suraj")
Arbitrary Keyword Arguments

# Python program to illustrate


# *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print(arg)

myFun('Hello', 'Welcome', 'to', 'SRM')

Output:
Hello
Welcome
to
SRM
Example 2: Variable length keyword arguments

# Python program to illustrate


# *kwargs for variable number of keyword arguments

def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))

# Driver code
myFun(first ='Python', mid='for', last='all')

Output:
first == Python
mid == for
last == all
Docstring

The first string after the function is called the Document string or Docstring in short. This is used to
describe the functionality of the function. The use of docstring in functions is optional but it is
considered a good practice.
Syntax: print(function_name.__doc__)

Example: Adding Docstring to the function

# A simple Python function to check


# whether x is even or odd
def evenOdd(x):
"""Function to check if the number is even or odd"""

if (x % 2 == 0):
print("even") Output:
else: Function to check if the
print("odd") number is even or odd

# Driver code to call the function


print(evenOdd.__doc__)
Python Function within Functions

# Python program to
# demonstrate accessing of
# variables of nested functions

def f1():
s = 'I love Python'
Output:
def f2(): I love Python
print(s)

f2()

# Driver's code
f1()
Anonymous Functions in Python

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.

# Python code to illustrate the


cube of a number
Output:
# using lambda function 343
def cube(x): return x*x*x 343

cube_v2 = lambda x : x*x*x

print(cube(7))
print(cube_v2(7))
Recursive Functions in Python

def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)

print(factorial(4))
Pass by Reference and Pass by Value

➔ One important thing to note is, in Python every variable name is a reference.
➔ When we pass a variable to a function, a new reference to the object is created.
➔ Parameter passing in Python is the same as reference passing in Java.

# Here x is a new reference to same list lst


def myFun(x):
x[0] = 20

# Driver Code (Note that lst is modified


Output:
# after function call.
[20, 11, 12, 13, 14, 15]
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)
Try to guess the output of the following code.

void swap(int *a, int *b)


def swap(x, y):
{
temp = x int temp = *a;
x = y *a = *b;
y = temp *b = temp;
}
int main() {
int x = 5;
# Driver code int y = 10;
x = 2 cout << "Before swap: x =
y = 3 " << x << " , y = " << y
swap(x, y) << endl;
print(x) swap(&x, &y);
print(y) cout << "After swap: x =
" << x << ", y = " << y <<
endl;
return 0;
}

You might also like