Unit Wowo
Unit Wowo
PYTHON
Python Interpreter and its working
● 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.
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
Example:
i="123456"
print(type(i))
num = int(i)
print(num)
print(type(num))
j = 190.98
print(int(j));
Function Description
ciel(x) The ceiling value of x, i.e., the smallest integer that is not less than x.
floor(x) The floor value of x, i.e., the greatest integer that is less than x.
pow(x,y) Returns x ** y.
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:
Reassigning Strings
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 range slice operator. It is used to access the characters from the specified range.
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.
● 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:
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)
Removing elements
Finding elements
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")
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
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
● 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:
Syntax [] () {}
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
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:
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.
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
def fun():
print("Welcome")
return num3
# Driver code
num1, num2 = 5, 15
ans = add(num1, num2)
print(f"The addition of {num1} and {num2} results {ans}.")
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
Output:
x: 10
y: 50
Keyword Arguments
# Keyword arguments
student(firstname='hello', lastname='world')
student(lastname='hello', firstname='world')
Output:
hello world
Hello world
Positional Arguments
Output:
Hello
Welcome
to
SRM
Example 2: Variable length 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__)
if (x % 2 == 0):
print("even") Output:
else: Function to check if the
print("odd") number is even or odd
# 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.
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.