Malay Padhan Pytho Long Question Answer
Malay Padhan Pytho Long Question Answer
Ans-Tokens in Python
In Python, a token is the smallest unit of a program that has a meaning. The Python interpreter breaks down
the code into tokens during the tokenization phase before execution. Tokens are the building blocks that
make up a Python program. They can be classified into the following categories:
1. Keywords: Reserved words in Python that have predefined meanings, such as if, else, while, def,
etc. These cannot be used as identifiers.
o Example: if, for, return.
2. Identifiers: Names given to variables, functions, or classes, such as x, total, my_function. They
must begin with a letter or underscore and can contain letters, numbers, or underscores.
o Example: total_sum = 10.
3. Literals: Constants that appear directly in the code, such as integers, floats, strings, and boolean
values.
o Example: 42, 3.14, "Hello", True.
4. Operators: Symbols used to perform operations on variables and values, like arithmetic,
comparison, and logical operators.
o Example: +, -, ==, and.
5. Delimiters: Punctuation marks that help structure the code, such as parentheses (), brackets [],
commas ,, and colons :.
o Example: def my_function(x, y):.
6. Comments: Text starting with #, ignored by the interpreter but used for code explanation.
o Example: # This is a comments.
In Python, identifiers are names used to identify variables, functions, classes, modules, or other objects.
There are specific rules that must be followed when naming identifiers in Python:
1. Start with a Letter or Underscore: An identifier must begin with a letter (a-z, A-Z) or an
underscore (_). It cannot start with a number.
o Valid: name, _variable, x
o Invalid: 1st_number, @variable
2. Subsequent Characters: After the first character, an identifier can contain letters, digits (0-9), or
underscores.
o Valid: variable_1, sum2, my_function
o Invalid: var@, total#value
3. Case Sensitivity: Python is case-sensitive, meaning myVariable, myvariable, and MYVARIABLE are
considered different identifiers.
o Example: x and X are distinct identifiers.
4. No Reserved Keywords: Python keywords (such as if, while, def, for, return) cannot be used as
identifiers. These words have special meanings and are reserved for specific functionality in the
language.
o Invalid: if = 10, for = 5
5. Length: There is no explicit length limit for an identifier in Python, but it is a good practice to keep
identifiers reasonably short and meaningful. Avoid excessively long or cryptic names.
6. Naming Conventions: While not enforced by Python, there are conventions to follow for
readability:
o Snake_case: For variables and functions, use lowercase letters with underscores separating
words (e.g., my_variable, calculate_sum).
o PascalCase: For class names, use capital letters for each word without underscores (e.g.,
MyClass, CarModel).
o UPPERCASE: For constants, uppercase letters with underscores are typically used (e.g.,
MAX_VALUE, PI).
Ans-Keywords in Python
In Python, keywords are reserved words that have special meanings to the interpreter. These keywords
cannot be used as identifiers (such as variable names, function names, etc.) because they are reserved for
specific functions or constructs in the Python language.
Characteristics of Keywords:
1. Reserved words: They are predefined and cannot be redefined by the user.
2. Special meaning: Each keyword performs a specific function in the Python language, such as
controlling the flow of execution, defining functions, or managing data structures.
python
Copy
if x > 5:
print("x is greater than 5")
2. else: Used with if to define an alternative block of code if the condition is not met.
python
Copy
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
3. for: Used to initiate a loop that iterates over a sequence (like a list, tuple, or string).
python
Copy
for i in range(5):
print(i)
python
Copy
while x < 10:
x += 1
print(x)
python
Copy
def add(a, b):
return a + b
python
Copy
class Dog:
def __init__(self, name):
self.name = name
8. try / except: Used for exception handling to catch and handle errors.
python
Copy
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
python
Copy
import math
print(math.sqrt(16))
python
Copy
is_valid = True
if is_valid:
print("Valid")
Here’s a full list of Python keywords (they are fixed and cannot be used as identifiers):
python
Copy
False, None, True, and, as, assert, async, await, 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
Important Points:
Case-sensitive: Keywords in Python are case-sensitive. For example, True and true are different,
where True is a keyword and true is just an identifier.
Cannot be used as identifiers: You cannot use any of the keywords for variable names, function
names, or class names in your program.
4.What is literal explain the difference type of python with examples ?
In Python, literals are constant values that are directly used in the code. They represent fixed values in the
source code. Literals can be numbers, strings, booleans, or even special values like None. They are used to
assign values to variables or directly perform operations in the code.
1. Integer Literals: These are whole numbers without a fractional part. They can be in decimal, binary,
octal, or hexadecimal formats.
o Decimal: Numbers in base 10.
python
Copy
x = 100 # Integer literal in decimal
python
Copy
x = 0b1010 # Binary literal (10 in decimal)
python
Copy
x = 0o12 # Octal literal (10 in decimal)
python
Copy
x = 0xA # Hexadecimal literal (10 in decimal)
2. Floating-point Literals: These are numbers with a decimal point or in scientific notation (e.g., 1.23
or 1e2).
o Decimal: Numbers with a decimal point.
python
Copy
x = 3.14 # Floating-point literal
python
Copy
x = 1.23e4 # 1.23 * 10^4, which equals 12300
3. String Literals: A string literal is a sequence of characters enclosed in single quotes (') or double
quotes ("). You can also use triple quotes (''' or """) for multi-line strings.
o Single and Double Quotes:
python
Copy
string1 = 'Hello'
string2 = "World"
o Triple Quotes (for multi-line strings):
python
Copy
multiline_string = '''This is
a multi-line
string.'''
4. Boolean Literals: Python has two boolean literals: True and False, which represent truth values.
python
Copy
flag = True # Boolean literal
5. Special Literals:
o None: Represents the absence of a value or a null value.
python
Copy
x = None # None is a special literal
Key Points:
In Python, a variable is essentially a name that is used to refer to a memory location where data or values
are stored. Variables act as containers for data, making it easy to manage and manipulate values in a Python
program. Unlike many other programming languages, Python variables do not require explicit declaration of
type; the data type is inferred when you assign a value to a variable.
1. Variable Assignment: In Python, you assign values to variables using the = operator. The variable
name is on the left-hand side, and the value being assigned is on the right-hand side.
Example:
python
Copy
x = 10 # Assigns the integer 10 to variable 'x'
name = "Alice" # Assigns the string "Alice" to variable 'name'
2. Dynamic Typing: Python is dynamically typed, meaning you do not need to declare the data type
of a variable when you create it. The interpreter automatically infers the type based on the assigned
value. This allows you to reassign variables with different data types.
Example:
python
Copy
x = 5 # x is an integer
x = "hello" # x is now a string
3. Variable Naming Rules: There are certain rules and conventions for naming variables in Python:
o Valid Variable Names:
Must begin with a letter (a-z, A-Z) or an underscore (_).
Can contain letters, digits (0-9), or underscores.
Cannot start with a digit.
Cannot be a Python keyword (e.g., if, for, def, etc.).
o Invalid Variable Names:
Cannot start with a number: 1variable is invalid.
Cannot contain special characters: var@name is invalid.
Cannot be a reserved keyword: for, True, etc.
python
Copy
var_name = 10
_age = 25
student1 = "John"
4. Variable Types (Data Types): In Python, variables can store different types of data, such as
numbers, strings, lists, and more. Some of the common data types are:
o Integers: Whole numbers.
python
Copy
x = 10
python
Copy
y = 3.14
python
Copy
name = "Alice"
python
Copy
is_valid = True
o Lists: Ordered collections of elements.
python
Copy
numbers = [1, 2, 3, 4]
python
Copy
coordinates = (1, 2, 3)
python
Copy
student = {"name": "Alice", "age": 20}
python
Copy
value = None
5. Assigning Multiple Variables: You can assign values to multiple variables in a single line in
Python. This is known as multiple assignment.
Example:
python
Copy
a, b, c = 10, 20, 30 # Assigns 10 to a, 20 to b, and 30 to c
6. Reassigning Variables: In Python, you can reassign a variable to a new value of any type. Since
Python is dynamically typed, the data type of the variable can change during runtime.
Example:
python
Copy
x = 10 # x is an integer
x = "Hello" # x is now a string
Example:
python
Copy
x = 5 # Global variable
def my_function():
y = 10 # Local variable
print(x) # Accessing the global variable inside the function
print(y)
my_function()
print(x) # Global variable can be accessed outside the function
Global Variables in Functions: If you want to modify a global variable inside a function, you need
to declare it as global.
python
Copy
x = 10 # Global variable
def modify_global():
global x # Declare x as global to modify it
x = 20
modify_global()
print(x) # Output will be 20
8. Deleting Variables: You can delete a variable using the del keyword, which removes it from
memory.
Example:
python
Copy
x = 10
del x # Deletes the variable 'x'
# print(x) # This will raise an error because 'x' is deleted
9. Constants: Python does not have built-in constants, but by convention, you can use uppercase
variable names to indicate that a variable should not be changed.
Example:
python
Copy
MAX_SIZE = 100 # MAX_SIZE is treated as a constant (convention)
Summary:
Ans-In Python, declaring and assigning a variable is straightforward. Here's what each term means:
1. Declaring a variable:
In Python, declaring a variable is not a separate step as it is in some other languages (like C or Java).
You don't need to explicitly declare the type of the variable before using it.
Simply giving the variable a name is enough to declare it.
Example:
x = 10 # Here, 'x' is declared and assigned the value 10.
In this example:
Key points:
Variables are dynamically typed in Python, meaning you don’t need to declare the data type
explicitly. Python figures it out for you based on the value assigned.
x = 10 # x is an integer
x = "Hello" # Now x is a string
Here, x first holds an integer (10), and then is reassigned to hold a string ("Hello"). There's no need to
declare the type of x beforehand. Python automatically changes the type of the variable based on its value.
Conclusion:
Ans-In Python, operators are symbols used to perform operations on variables or values. Python has a
wide range of operators that fall into several categories based on the kind of operation they perform. Let's
break down these categories:
1. Arithmetic Operators
3. Logical Operators
These are used to combine conditional statements (like if, elif, else).
4. Assignment Operators
= (Assign): Assigns the value on the right to the variable on the left.
x = 10 # Assigns 10 to x
+= (Add and assign): Adds the right operand to the left operand and assigns the result to the left
operand.
x += 5 # Equivalent to x = x + 5
-= (Subtract and assign): Subtracts the right operand from the left operand and assigns the result to
the left operand.
x -= 3 # Equivalent to x = x - 3
*= (Multiply and assign): Multiplies the left operand by the right operand and assigns the result to
the left operand.
x *= 2 # Equivalent to x = x * 2
/= (Divide and assign): Divides the left operand by the right operand and assigns the result to the left
operand.
x /= 2 # Equivalent to x = x / 2
5. Identity Operators
is: Returns True if two variables refer to the same object in memory.
x is y # Checks if x and y refer to the same object
is not: Returns True if two variables do not refer to the same object.
x is not y # Checks if x and y are not the same object
6. Membership Operators
7. Bitwise Operators
Conclusion:
Python provides a wide variety of operators to perform basic arithmetic, logical comparisons, assignment,
and more. The key point is that operators allow you to manipulate values and variables in different ways to
achieve your programming goals.
Ans-In Python, statements and expressions are two fundamental concepts that are often used together to
write code, but they have different purposes and behaviors. Let's break down what each of these terms
means and how they are used:
1. Expression
An expression is any valid combination of variables, operators, literals, and function calls that can be
evaluated to produce a value.
Examples of expressions:
Simple expressions:
5 + 3 # Result: 8
"Hello" + " " + "World" # Result: "Hello World"
Complex expressions:
(2 * 3) + (4 / 2) # Result: 8.0
len("Python") # Result: 6 (the length of the string "Python")
2. Statement
A statement is a line of code that performs an action. It doesn't return a value like an expression does, but
instead it controls the flow of the program.
Statements are executed to perform some task (such as printing something, assigning a value to a
variable, or making decisions).
A statement is not evaluated for a value, but instead it does something, like creating a variable or
controlling the program’s flow.
Examples of statements:
Assignment statement:
x = 10 # This is a statement that assigns 10 to x
Print statement:
print("Hello, World!") # This is a statement that prints to the console
Conditional statement (if statement):
if x > 5: # This is a statement that checks a condition
print("x is greater than 5")
Loop statement:
for i in range(3): # This is a statement that starts a loop
print(i)
Expression Statement
Produces a value that can be used. Does something but doesn't produce a value.
Can be assigned to a variable or passed as an argument. Executes an action (e.g., print, assignment).
Examples: 5 + 3, x * y, len("hello") Examples: x = 10, if x > 5:, print()
Here, 5 + 3 is an expression that evaluates to 8, and that result is assigned to x using the assignment
statement x = 8.
Conclusion:
Expressions are parts of the code that evaluate to a value and can be used wherever values are
required.
Statements are lines of code that perform an action but do not return a value.
In Python, expressions are often used within statements, but the two serve distinct purposes.
9.what is the difference between “in” and “not in” membership operators in python ?
Ans-In Python, the membership operators in and not inare used to check if a value (element) exists
within a sequence (like a list, string, tuple, etc.). These operators test membership, but they work in opposite
ways.
1. in (Membership Operator)
Example:
# Using `in` with a list
fruits = ["apple", "banana", "cherry"]
result = "banana" in fruits # Checks if "banana" is in the list
print(result) # Output: True
Example:
# Using `not in` with a list
fruits = ["apple", "banana", "cherry"]
result = "orange" not in fruits # Checks if "orange" is not in the list
print(result) # Output: True
Key Differences:
Checks if a value exists in the Returns True if the value is found in the sequence, otherwise
in
sequence. False.
Checks if a value is not in the Returns True if the value is not found in the sequence, otherwise
not in
sequence. False.
Summary:
Both operators are commonly used with lists, tuples, strings, dictionaries, and other iterable types in Python.
1. if (Conditional Statement)
Purpose: The if is a conditional statement, used to test whether a specific condition is True or False and
to execute a block of code accordingly.
Functionality: It evaluates an expression (like a comparison or logical expression) and runs the code inside
the if block if the expression evaluates to True.
Example:
x = 10
if x > 5: # if condition is True, this block will run
print("x is greater than 5") # Output: "x is greater than 5"
It is a control flow statement that decides the execution path based on a condition.
It uses expressions (like comparisons or logical conditions).
2. is (Identity Operator)
Purpose: The is operator checks if two variables reference the same object in memory, not if they are
equal in value.
Functionality: It returns True if both operands refer to the same object in memory. If they point to two
different objects, even if those objects have the same value, is will return False.
Example:
x = [1, 2, 3]
y = x # y references the same object as x
z = [1, 2, 3] # z is a new object, even though it has the same value
It checks if two variables point to the same object in memory, not just if they have the same value.
It is often used to compare a variable to None (since None is a singleton in Python).
Summary of Differences
When to Use:
Use if when you want to test a condition and control the flow of the program based on that.
Use is when you need to check if two variables are exactly the same object in memory, which is common
when comparing with None or testing object identity.
For comparing values, use the equality operator (==) instead of is.
Ans-In Python, data types specify the kind of value a variable can hold. They are essential because they
determine what operations can be performed on the value stored in the variable. Python has several built-in
data types, each serving a different purpose.
int: Represents integers (whole numbers), which can be positive, negative, or zero.
o Example:
o x = 5 # An integer
o y = -3 # An integer
float: Represents floating-point numbers (decimal numbers).
o Example:
o a = 3.14 # A float
o b = -0.001 # A negative float
complex: Represents complex numbers (numbers with a real and imaginary part).
o Example:
o c = 2 + 3j # A complex number (2 + 3i)
list: Represents an ordered, mutable collection of items. Lists can hold elements of different data
types (integers, strings, etc.).
o Example:
o numbers = [1, 2, 3, 4, 5] # A list of integers
o names = ['Alice', 'Bob', 'Charlie'] # A list of strings
tuple: Represents an ordered, immutable collection of items. Once created, the elements of a tuple
cannot be changed.
o Example:
o point = (1, 2, 3) # A tuple
o colors = ('red', 'green', 'blue') # A tuple of strings
range: Represents an immutable sequence of numbers, commonly used in for loops.
o Example:
o r = range(5) # A range from 0 to 4
4. Mapping Data Type
dict: Represents a dictionary, which is an unordered collection of key-value pairs. Keys are
unique, and values can be of any data type.
o Example:
o student = {'name': 'Alice', 'age': 22, 'grade': 'A'}
set: Represents an unordered collection of unique items. Sets are mutable and do not allow
duplicate elements.
o Example:
o unique_numbers = {1, 2, 3, 4, 5} # A set of unique integers
frozenset: Similar to a set, but immutable (its elements cannot be changed after creation).
o Example:
o frozen_set = frozenset([1, 2, 3, 4]) # A frozenset of numbers
bytes: Represents an immutable sequence of bytes (used for binary data like images, files).
o Example:
o data = b"Hello" # A bytes object
bytearray: Similar to bytes, but mutable.
o Example:
o byte_arr = bytearray([65, 66, 67]) # A bytearray object (mutable)
memoryview: Represents a view of a memory buffer (used for handling large binary data efficiently).
o Example:
o buffer = memoryview(byte_arr) # A memoryview object
8. None Type
None: Represents the absence of a value or a null value. It is often used to initialize variables or to
indicate that a function has no return value.
o Example:
o result = None # A variable initialized with None
Conclusion:
Basic Data Types like int, float, str, and bool are used for numbers, text, and logical operations.
Sequence Data Types like list, tuple, and range are used to store ordered collections.
Set and Mapping Data Types like set, frozenset, and dict store unique items or key-value pairs.
NoneType represents the absence of a value.
Python is dynamically typed, meaning you don’t need to declare the type of a variable explicitly—Python
will infer it based on the assigned value.
Ans-In Python, you can convert a string to an integer using the int() function. This function takes a
string as an argument and returns its integer representation. However, the string must represent a valid
integer (i.e., it must contain only digits, possibly with a leading minus sign for negative numbers).
Syntax:
int(string, base=10)
Examples:
If the string contains a valid integer (positive or negative), int() will convert it to an integer.
You can also convert a string in a different base (e.g., binary, octal, hexadecimal) to an integer by specifying
the base.
If the string cannot be converted to an integer (e.g., it contains non-numeric characters), Python will raise a
ValueError.
invalid_str = "abc123"
try:
num_int = int(invalid_str)
except ValueError as e:
print(f"Error: {e}") # Output: Error: invalid literal for int() with base 10:
'abc123'
Conclusion:
int("123") → 123
int(" 456 ") → 456 (spaces are ignored)
int("101", 2) → 5 (binary to decimal)
Be sure the string is a valid representation of a number (or else handle exceptions).
13.explain comment in python and its purpose discus the importance of proper indention
and how its effect the code functionality ?
Comments are non-executable lines of code that provide explanations or notes about the code. They are
meant to make the code more readable and understandable to humans, without affecting the program's
execution.
In Python, comments are preceded by a hash symbol (#), and everything following the # on that line is
considered a comment.
a. Single-Line Comments:
b. Multi-Line Comments:
While Python does not have a specific syntax for multi-line comments, you can use consecutive single-line
comments or a multi-line string (triple quotes) that is not assigned to a variable. This can act as a comment.
'''
This is another way to write
multi-line comments, using triple quotes.
'''
Note: Triple quotes (''' or """) are technically used for docstrings (used for documentation of functions,
classes, etc.), but they are often used as multi-line comments when not assigned to a variable.
Purpose of Comments:
Documentation: Comments help explain what the code does, especially complex or non-obvious parts of the
code.
Code Maintenance: Comments make the code easier to maintain or update. Anyone (including the original
programmer) can quickly understand what each section of the code is doing.
Collaboration: When working in teams, comments allow collaborators to understand each other's code and
logic.
Code Debugging: You can temporarily comment out certain parts of code to test or debug specific sections.
Be clear and concise: Comments should describe "why" something is done, not "what" is done (since the
code itself should already show that).
Avoid unnecessary comments: Don’t comment on obvious things. For example, x = 5 # Assign 5 to x
is not useful.
Keep comments up to date: Outdated comments can be confusing. Always update comments if you change
the logic of the code.
Indentation refers to the spaces or tabs used at the beginning of a line of code to define the structure and
grouping of code blocks. In Python, indentation is not just for readability—it is syntactically significant
and defines the scope of loops, conditionals, functions, and classes.
2. Logical Grouping:
o Indentation helps organize the code logically by grouping related statements together. Without it,
the code would be much harder to understand.
3. Error Prevention:
o Incorrect indentation can cause IndentationError or lead to logical errors. Python will raise an error
if the indentation is inconsistent or incorrect.
Correct Example:
if x > 0:
print("x is positive")
y = x + 5
else:
print("x is non-positive")
In this example, the print() and y = x + 5 statements are part of the if block because they are
indented under the if condition. The else block is indented separately.
Indentation Level: The standard practice is to use 4 spaces for each level of indentation (although tabs can
also be used, it's recommended to use spaces for consistency).
Incorrect Example:
if x > 0:
print("x is positive")
y = x + 5
This will raise an IndentationError because the print() statement is not indented correctly under the
if block.
Incorrect Program Flow: If the indentation is inconsistent (e.g., mixing spaces and tabs or improper
alignment), the program may run incorrectly without any obvious syntax errors, leading to logical
bugs.
Example:
if x > 0:
print("x is positive")
y = x + 5
print("This is outside the if block")
In this example, the print("This is outside the if block") is outside the if block, so it will
always execute, regardless of the condition of x.
Incorrectly indenting or failing to group statements properly can lead to bugs that are hard to spot.
Summary:
Aspect Explanation
Used for documenting code. They help explain the purpose of the code to humans, and make
Comments
code easier to maintain.
Python uses indentation to define the structure of the program. It indicates where code blocks
Indentation
begin and end.
Effect on Improper indentation causes errors (e.g., IndentationError) and can lead to logical issues
Functionality (e.g., code outside a loop when it shouldn't be).
By adhering to proper indentation and making effective use of comments, your code will be much more
readable, maintainable, and less prone to errors.
14.explain the difference method to expect the input from the user in python with their
example ?
Ans-In Python, there are multiple ways to receive input from the user. The most common method is
using the built-in function input(), but there are other methods that can be used in specific scenarios (like
reading from files, command-line arguments, etc.).
Here, I'll explain the most common methods to get user input, focusing on input(), and other techniques
used in different contexts.
The most common and simplest way to get input from the user in Python is using the input() function.
Syntax:
input(prompt)
prompt: Optional. A string that is displayed to the user before they enter their input.
Example:
# Using input to get user input
name = input("Enter your name: ")
age = input("Enter your age: ")
In this example:
Note:
Input is always a string: Even if the user enters a number, it’s read as a string. You need to explicitly convert
it to another type (e.g., int(), float()).
As mentioned, input() always returns a string. If the user is expected to input a number, you often need to
convert it to a numeric type like int or float.
Example:
# Getting integer input from user
x = int(input("Enter an integer: "))
y = int(input("Enter another integer: "))
sum = x + y
print(f"The sum of {x} and {y} is {sum}")
In this example:
The user is prompted for integer input, and the int() function is used to convert the string input to an
integer.
You can also use float() to convert the string input to a floating-point number if needed:
In certain cases, like reading input for large scripts or command-line programs, sys.stdin is used to read
input from standard input (stdin).
Example:
import sys
In this example:
sys.stdin.read() is used to read all the input given to the program until EOF (End of File).
This is typically useful for reading large chunks of data (like from a file or when piping input).
When writing scripts that need to accept command-line arguments, you can use the argparse module. This
is commonly used for scripts that are executed from the command line and need to process input arguments.
Example:
import argparse
In this example:
argparse parses command-line arguments (name and age), and it automatically handles type conversion.
If you want to read input from a file (or multiple files), you can use the fileinput module. This is useful
when you want to process files line-by-line, instead of getting input interactively from the user.
Example:
import fileinput
In this example:
The program reads lines from a file (input.txt) and processes them.
The fileinput.input() method allows you to handle both command-line input and files.
If you are developing a GUI application, you might want to use a graphical interface to get user input. The
tkinter module is Python’s standard library for creating GUIs.
Example:
import tkinter as tk
def get_input():
user_input = entry.get()
print(f"You entered: {user_input}")
entry = tk.Entry(root)
entry.pack()
In this example:
A GUI window is created where the user can input text and click a button to submit the input.
The entry.get() method fetches the user input.
input() Standard method for reading user input as a string. name = input("Enter your name: ")
Used to convert string input to integers or floating- age = int(input("Enter your age:
int()/float()
point numbers. "))
sys.stdin For reading large chunks of data or input from files. input_text = sys.stdin.read()
fileinput For reading from files or multiple files. for line in fileinput.input()
Conclusion:
Ans- In Python, both the format() method and f-string (formatted string literals) are used for string
formatting. They allow you to embed variables or expressions inside strings, making it easier to create
dynamic and readable output.
The format() method was introduced in Python 2.7 and Python 3.0 as a way to format strings in a flexible
and powerful manner. It allows you to insert variables or expressions inside a string by using curly braces {}
as placeholders.
Syntax:
"string {} and {}".format(value1, value2)
Output:
You can pass values in a specific order or use keyword arguments to insert values at specific placeholders
in the string.
You can also refer to the arguments by their index inside the placeholders.
The f-string (formatted string literal) method was introduced in Python 3.6. It’s considered more concise
and efficient than the format() method.
Syntax:
f"string {expression}"
Output:
You can include more complex expressions directly within the curly braces.
x = 5
y = 10
result = f"The sum of {x} and {y} is {x + y}."
print(result) # Output: The sum of 5 and 10 is 15.
f-strings also support formatting specifiers for numbers, such as controlling the number of decimal places.
pi = 3.141592653589793
formatted_string = f"The value of pi is approximately {pi:.2f}."
print(formatted_string) # Output: The value of pi is approximately 3.14.
Slightly more verbose, requires calling More concise, no need for method call, inline
Ease of Use
.format() expressions
Performance Slower (due to method call overhead) Faster (since it's evaluated at runtime directly)
Support for
Supports indexing and keyword arguments Direct evaluation of expressions inside {}
Expressions
Easy to understand, especially for complex More readable and concise, especially for simple
Readability
formatting formatting
Flexible with complex formatting options Limited compared to format(), but simpler and
Flexibility
(e.g., padding) more intuitive
Using format():
name = "Alice"
age = 25
height = 1.75
Using f-String:
name = "Alice"
age = 25
height = 1.75
Summary:
format(): A flexible and older method for string formatting. It allows positional and keyword arguments,
and is great for complex formatting but is more verbose.
f-String: A more modern and concise approach to string formatting, introduced in Python 3.6. It’s faster and
easier to read, with direct support for inline expressions and formatting.
In general, if you're working in Python 3.6 or later, f-strings are the recommended approach due to their
readability, performance, and ease of use.
Ans- In Python, there are several ways to format strings, allowing you to insert variables or expressions
into strings in a readable and efficient manner. The main ways to format strings are:
1. String Concatenation
2. Using format() Method
3. f-String (Formatted String Literals)
4. Percent (%) Formatting
1. String Concatenation
This is the simplest way to format strings, where you combine strings using the + operator. However, it's
generally not recommended for complex string formatting because it can be hard to read and maintain.
Example:
name = "Alice"
age = 25
# String concatenation
formatted_string = "Hello, my name is " + name + " and I am " + str(age) + " years
old."
print(formatted_string)
Output:
Hello, my name is Alice and I am 25 years old.
The format() method was introduced in Python 2.7 and 3.0 as a way to format strings by placing
placeholders ({}) in the string and passing values to the format() method.
Syntax:
"string with {} placeholders".format(value1, value2, ...)
Output:
# Keyword arguments
formatted_string = "The {color} sky is {time}.".format(color="blue", time="day")
print(formatted_string) # Output: The blue sky is day.
f-Strings, or formatted string literals, were introduced in Python 3.6 and provide a more concise, readable,
and efficient way to format strings. You can include expressions directly inside the string with curly braces
{}.
Syntax:
f"string with {expression}"
The f prefix before the string tells Python to evaluate expressions inside the curly braces {} at runtime.
Output:
This is an older method of string formatting, inspired by the C programming language. It uses the % operator
to insert values into a string. While still functional, it's considered less flexible and less readable compared
to format() and f-Strings.
Syntax:
"string with % placeholders" % (value1, value2, ...)
Output:
Output:
String Simple cases with minimal Basic but inefficient for complex
"Hello " + name + "!"
Concatenation formatting. formatting.
Percent (%) "Hello, my name is %s." Legacy code or simple Less flexible, outdated in
Formatting % name formatting (old C-style). Python 3.x.
Conclusion:
f-strings are the preferred and modern way of formatting strings, offering both readability and
performance.
format() is a flexible option, useful for more complex formatting tasks or when dealing with both
positional and keyword arguments.
Percent (%) formatting is an older, less preferred method but can still be useful for simple cases or legacy
code.
String concatenation is the simplest, but should be avoided in favor of more efficient and readable methods
for larger or more complex formatting tasks.
17.explain the difference type of control close statement In python with example ?
Ans- In Python, control flow statements are used to control the execution flow of the program. These
statements enable you to specify conditions, repeat actions, and manage loops. Python provides various
control flow statements such as conditional statements, looping statements, and exception handling
statements.
if statement
The if statement is used to test a condition and execute a block of code if the condition is True.
Syntax:
if condition:
# code to execute if condition is True
Example:
x = 10
if x > 5:
print("x is greater than 5") # This will execute because 10 > 5
The elif statement allows checking multiple conditions sequentially. If the if condition is False, Python
will check the conditions in the elif statements.
Syntax:
if condition1:
# code to execute if condition1 is True
elif condition2:
# code to execute if condition2 is True
Example:
x = 10
if x < 5:
print("x is less than 5")
elif x == 10:
print("x is equal to 10") # This will execute because x == 10
else statement
The else statement executes a block of code if all preceding if and elif conditions are False.
Syntax:
if condition1:
# code to execute if condition1 is True
elif condition2:
# code to execute if condition2 is True
else:
# code to execute if all previous conditions are False
Example:
x = 2
if x > 5:
print("x is greater than 5")
elif x == 3:
print("x is equal to 3")
else:
print("x is less than 5 and not equal to 3") # This will execute
2. Looping Statements
Looping statements allow a block of code to be executed repeatedly based on a condition. The two main
types of loops in Python are for and while loops.
for loop
The for loop is used to iterate over a sequence (like a list, tuple, or string) or other iterable objects. It runs
for each item in the sequence.
Syntax:
for variable in sequence:
# code to execute for each item in the sequence
Example:
fruits = ["apple", "banana", "cherry"]
Output:
apple
banana
cherry
while loop
The while loop continues to execute a block of code as long as the given condition evaluates to True. It
checks the condition before every iteration.
Syntax:
while condition:
# code to execute as long as the condition is True
Example:
x = 0
while x < 5:
print(x)
x += 1 # Increment x to avoid an infinite loop
Output:
0
1
2
3
4
These statements allow you to modify the behavior of loops and control the flow of execution in a more
granular way.
break statement
The break statement is used to exit a loop prematurely, regardless of the condition.
Syntax:
for variable in sequence:
if some_condition:
break # Exit the loop
Example:
for i in range(10):
if i == 5:
break # Exit the loop when i equals 5
print(i)
Output:
0
1
2
3
4
continue statement
The continue statement is used to skip the rest of the code inside a loop for the current iteration and move
to the next iteration.
Syntax:
for variable in sequence:
if some_condition:
continue # Skip the rest of the loop and move to the next iteration
Example:
for i in range(5):
if i == 2:
continue # Skip the iteration when i equals 2
print(i)
Output:
0
1
3
4
pass statement
The pass statement is a placeholder that does nothing. It is often used when a statement is required
syntactically, but you don’t want to execute any code (for example, in a function or class definition that
hasn't been implemented yet).
Syntax:
if condition:
pass # Does nothing, just a placeholder
Example:
def some_function():
pass # Placeholder for code that will be written later
The try block lets you test a block of code for errors. The except block lets you handle the error if it
occurs.
Syntax:
try:
# code that might cause an error
except SomeException:
# code to handle the error
Example:
try:
x = 1 / 0 # This will cause a ZeroDivisionError
except ZeroDivisionError:
print("Cannot divide by zero")
Output:
else block
The else block is optional and runs if the code inside the try block did not raise an exception.
Syntax:
try:
# code that might cause an error
except SomeException:
# code to handle the error
else:
# code to execute if no error occurred
Example:
try:
x = 10 / 2 # This will not raise an exception
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Division was successful")
Output:
finally block
The finally block is always executed, regardless of whether an exception occurred or not. It’s typically
used for cleanup actions (like closing files or releasing resources).
Syntax:
try:
# code that might cause an error
except SomeException:
# code to handle the error
finally:
# code to execute no matter what
Example:
try:
x = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("This will always execute")
Output:
Executes a block of code if all preceding conditions are else: print("x is not greater
else
False. than 5")
Used to catch and handle exceptions that may occur try: x = 1 / 0; except
try/except
during execution. ZeroDivisionError:
else Executes if no exception was raised in the try block. else: print("No errors")
18.Explain the different type of dicision maxing control flow statement in python ?
Ans- In Python, decision-making control flow statements allow you to execute specific code based on
conditions. These statements enable your program to make decisions, handle multiple conditions, and
execute certain blocks of code based on logical choices. Python provides various decision-making
statements, including the if, elif, and else statements, which are used to control the flow of execution
based on conditions.
Let's explore the different types of decision-making control flow statements in Python in detail:
1. if Statement
The if statement is the most basic decision-making statement in Python. It allows you to test a condition
(expression) and execute a block of code only if that condition evaluates to True.
Syntax:
if condition:
# Code block to execute if condition is True
Example:
age = 18
Output:
2. if-else Statement
The if-else statement is used when you want to execute one block of code if the condition is True and
another block if the condition is False.
Syntax:
if condition:
# Code block to execute if condition is True
else:
# Code block to execute if condition is False
Example:
age = 16
Output:
3. if-elif-else Statement
The if-elif-else statement allows you to check multiple conditions. It works like an if statement,
followed by one or more elif (else if) blocks, and an optional else block. The elif blocks allow you to
check several conditions, and the else block will execute if none of the conditions are True.
Syntax:
if condition1:
# Code block to execute if condition1 is True
elif condition2:
# Code block to execute if condition2 is True
elif condition3:
# Code block to execute if condition3 is True
else:
# Code block to execute if all conditions are False
Example:
age = 25
Output:
4. Nested if Statements
You can also nest if statements inside other if or elif blocks to check more specific conditions within a
condition.
Syntax:
if condition1:
if condition2:
# Code block to execute if both condition1 and condition2 are True
else:
# Code block to execute if condition1 is True and condition2 is False
else:
# Code block to execute if condition1 is False
Example:
age = 30
has_voter_id = True
Output:
In this example, the outer if checks if the person is eligible to vote based on their age. If the person is
eligible, the inner if checks whether they have a voter ID.
Python also provides a shorthand syntax for simple decision-making. This is known as the ternary operator
or conditional expression. It allows you to assign values based on a condition, all in a single line.
Syntax:
x = value_if_true if condition else value_if_false
Example:
age = 20
status = "Adult" if age >= 18 else "Not Adult"
Output:
Adult
This is a compact way to assign values based on a condition without the need for multiple lines of code.
You can combine multiple conditions using logical operators like and, or, and not.
Syntax:
if condition1 and condition2:
# Code to execute if both conditions are True
Example:
age = 20
has_permission = True
Output:
In this example, both conditions age >= 18 and has_permission need to be True for the code inside the if
block to execute.
Output:
In this example, the program will print "You are allowed to proceed" because has_permission is True,
even though age is not greater than or equal to 18.
Summary of Decision-Making Statements in Python:
Executes one block of code if the condition is if x > 5: print("x is greater than 5")
if-else
True and another if False. else: print("x is 5 or less")
Conclusion:
Decision-making control flow statements (if, elif, else, etc.) are fundamental for controlling the logic of
your program in Python. These statements enable you to execute certain blocks of code based on conditions,
ensuring that the program reacts appropriately to different situations. Combining them with logical operators
further increases the flexibility and complexity of your decision-making logic.
Ans- A nested if statement in Python refers to an if statement inside another if statement. This
allows you to evaluate more complex conditions by checking multiple criteria in a hierarchical manner.
Essentially, a nested if enables you to create more specific decisions based on multiple layers of conditions.
Let’s consider a scenario where you are checking the age of a person and also checking if they have a
special permit to enter a restricted area.
Output:
You are allowed to enter the restricted area.
Explanation:
2. Nested if condition: Inside the first if block, it checks if the person has a permit (has_permit).
o If the person has a permit, it allows them to enter the restricted area.
o If the person does not have a permit, it informs them that a permit is required.
3. else block: If the first condition (age >= 18) is False, it means the person is underage, and they
are not allowed to enter the restricted area.
Let’s consider another example where we check the grade of a student and categorize them into A, B, or C
based on their score.
score = 85
Output:
Grade B+
Explanation:
Let’s look at a scenario where a student’s admission eligibility depends on both their age and their exam
score.
age = 17
exam_score = 75
Output:
You are not eligible for admission due to age.
Explanation:
Nested if statements allow you to perform multi-level checks and make decisions based on more than one
condition. This is helpful when you need to test several criteria before executing a block of code. However,
excessive nesting can lead to more complex and harder-to-maintain code, so it's often a good idea to
simplify the logic when possible (for example, by combining conditions with logical operators like and, or,
etc.).
Conclusion:
Nested if statements are used when you need to check multiple conditions sequentially.
Each if block can contain another if block, allowing for more specific decision-making.
You should avoid excessive nesting, as it can make your code harder to read and maintain. Consider
alternatives such as combining conditions or using functions to improve readability.
Ans- In Python, both for loops and while loops are used for repetitive tasks, but they differ in how they
work and when they are used. Here’s a detailed explanation of the differences between the two:
1. For Loop
The for loop is generally used when the number of iterations is known or can be determined beforehand. It
is typically used for iterating over a sequence (like a list, tuple, string, or range), and it automatically handles
the loop's termination when the sequence is exhausted.
Syntax:
for variable in iterable:
# Code block to execute
Key Features:
The for loop iterates over a sequence (like a list, tuple, range, etc.).
The number of iterations is determined by the sequence (fixed number of iterations).
It automatically ends when it reaches the end of the sequence.
Example:
# Iterate over a range of numbers from 0 to 4
for i in range(5):
print(i)
Output:
0
1
2
3
4
In this example, the loop iterates over the sequence generated by range(5), which gives the numbers 0 to 4.
The loop automatically terminates after completing 5 iterations.
2. While Loop
The while loop, on the other hand, is used when you want the loop to continue as long as a condition is
True. The number of iterations is not known beforehand, and the loop will keep running until the condition
becomes False.
Syntax:
while condition:
# Code block to execute
Key Features:
Example:
# Print numbers from 0 to 4 using a while loop
i = 0
while i < 5:
print(i)
i += 1
Output:
0
1
2
3
4
In this example, the loop will keep running as long as i is less than 5. The condition i < 5 is checked
before each iteration, and i is incremented inside the loop to eventually stop the loop.
When you know how many times you need When you don’t know beforehand how many iterations
When to Use to iterate, or you are iterating over a are needed, or when you want to loop based on a
sequence. dynamic condition.
Use a for loop when you know the number of iterations in advance or when you are working with a
sequence (like a list, string, or range).
o Example: Iterating over a list of names or a range of numbers.
Use a while loop when the number of iterations is not known, and you want to continue looping
based on some condition being met (e.g., a user input or reaching a threshold).
o Example: Waiting for user input, processing data until a certain condition is met, or monitoring an
event.
Output:
h
e
l
l
o
Output:
1
2
3
4
5
6
7
8
9
10
Conclusion:
Use a for loop when you are working with a known sequence or when the number of iterations is
predetermined.
Use a while loop when you want to continue looping based on a condition that can change dynamically and
is not necessarily based on a sequence.
Ans- In Python, the if statement is used to make decisions based on conditions. There are different
types of if statements, and they help you execute blocks of code conditionally, depending on whether a
condition evaluates to True or False.
1. Simple if Statement
The simplest form of the if statement checks whether a condition is True and executes a block of code if
the condition holds true.
Syntax:
if condition:
# Code block to execute if the condition is True
Example:
age = 20
Output:
Explanation:
2. if-else Statement
The if-else statement allows you to execute one block of code if the condition is True and another block if
the condition is False.
Syntax:
if condition:
# Code block to execute if condition is True
else:
# Code block to execute if condition is False
Example:
age = 16
Output:
Explanation:
3. if-elif-else Statement
The if-elif-else statement allows you to check multiple conditions in sequence. It is used when you have
several possible conditions and you want to execute different blocks of code based on those conditions.
Syntax:
if condition1:
# Code block to execute if condition1 is True
elif condition2:
# Code block to execute if condition1 is False and condition2 is True
elif condition3:
# Code block to execute if condition1 and condition2 are False, and condition3 is
True
else:
# Code block to execute if all conditions are False
Example:
score = 85
Output:
Grade B
Explanation:
The condition score >= 90 is checked first. Since score is 85, this condition is False.
Then, the elif score >= 70 condition is checked. Since score is 85, this condition is True, so the block
under this elif is executed, and the message "Grade B" is printed.
If none of the conditions were True, the else block would be executed.
4. Nested if Statements
A nested if statement is an if statement placed inside another if or elif block. It allows you to check
additional conditions only if the outer condition is True.
Syntax:
if condition1:
# Code block to execute if condition1 is True
if condition2:
# Code block to execute if condition2 is True
else:
# Code block to execute if condition2 is False
else:
# Code block to execute if condition1 is False
Example:
age = 20
has_permission = True
Output:
Explanation:
The outer if condition checks if age is greater than or equal to 18. Since age is 20, this condition is True.
The inner if condition then checks if has_permission is True. Since it is, the message "You are allowed to
enter the event." is printed.
A ternary operator (also called a conditional expression) allows you to evaluate a condition in a single line
of code. It’s a shorthand way of writing an if-else statement.
Syntax:
value_if_true if condition else value_if_false
Example:
age = 18
status = "Adult" if age >= 18 else "Not an Adult"
print(status)
Output:
Adult
Explanation:
The ternary operator checks if age >= 18. Since age is 18, the condition is True, so the expression
evaluates to "Adult", which is assigned to the status variable.
If the condition were False, it would have assigned "Not an Adult" to the status.
Type of
Description Example
Statement
Simple if Executes a block of code if the condition is True. if age >= 18: print("Adult")
if-elif- Checks multiple conditions and executes the block if score >= 90: ... elif score >=
else for the first True condition. 70: ... else: ...
Ternary A shorthand way of writing an if-else statement status = "Adult" if age >= 18 else
Operator in a single line. "Not Adult"
Conclusion:
Use the simple if statement when you need to execute a block of code based on a single condition.
Use the if-else statement when you have a clear choice between two options.
Use if-elif-else when you have multiple conditions to check.
Use nested if statements when you need to check additional conditions inside an already existing
condition.
Use the ternary operator for simple, concise conditional assignments in a single line.
Ans- In Python, functions are used to organize and modularize code. Functions allow you to define a
block of code that can be executed whenever it is called, making your code more efficient and easier to read.
Python supports different types of functions, depending on how they are defined and how they interact with
their arguments and return values. Below are the main types of functions in Python:
1. Built-in Functions
These are functions that Python provides out of the box. You can use them without defining them yourself.
They are part of Python’s standard library.
Example:
# Built-in function 'len' that returns the length of a string
word = "Hello"
print(len(word)) # Output: 5
2. User-defined Functions
These are functions that you create yourself to perform specific tasks. You define them using the def
keyword.
Syntax:
def function_name(parameters):
# Code block
return value
Example:
# A user-defined function that adds two numbers
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
These are functions that accept values (arguments) passed to them when they are called. Parameters are used
to provide input values to the function.
Example:
# A function that multiplies two numbers
def multiply(x, y):
return x * y
result = multiply(4, 5)
print(result) # Output: 20
In this case, x and y are parameters, and you pass the values 4 and 5 when calling the function.
A function can have parameters with default values. These default values are used if the function is called
without providing a value for the parameter.
Example:
# A function with a default parameter value
def greet(name="Guest"):
print(f"Hello, {name}!")
In this example, the name parameter has a default value of "Guest". If no argument is passed when calling
greet(), the default value is used.
In this example, *args collects all the positional arguments passed to the function into a tuple.
Output:
name: John
age: 22
major: Computer Science
Here, **kwargs collects all keyword arguments passed to the function into a dictionary.
A lambda function is a small, unnamed function defined using the lambda keyword. These are used for
simple tasks and are often passed as arguments to higher-order functions.
Syntax:
lambda arguments: expression
Example:
# Lambda function to add two numbers
add = lambda a, b: a + b
print(add(3, 4)) # Output: 7
Lambda functions are typically used when you need a short function for a specific task, and you don't want
to formally define a full function using def.
7. Recursive Functions
A recursive function is a function that calls itself in order to solve a problem. The base case is critical to
ensure that the recursion does not continue indefinitely.
Example:
# A recursive function to calculate the factorial of a number
def factorial(n):
if n == 0: # Base case
return 1
else:
return n * factorial(n-1) # Recursive call
A function can return multiple values, which are usually packed into a tuple. This is helpful when you need
to return more than one piece of information from the function.
Example:
# Function that returns multiple values
def get_student_info():
name = "Alice"
age = 22
major = "Mathematics"
return name, age, major
The function returns three values, which are unpacked into variables name, age, and major.
Functions with Default Functions with parameters that have def greet(name="Guest"):
Params default values. print(name)
Functions Returning Functions that return more than one value def get_student_info(): return
Multiple Values (usually as a tuple). name, age, major
Conclusion:
Python functions are versatile and can be defined in many different ways, depending on the needs of your
program.
Functions help organize code and improve readability, reusability, and maintainability.
You can use built-in functions or define your own, and Python offers various techniques like default
parameters, recursion, and lambda functions for flexibility in function design.
Ans- Sure! Let's go over each of these Python built-in functions, along with examples of how they work.
1. max() Function
The max() function returns the largest item in an iterable or the largest of two or more arguments.
Syntax:
max(iterable, *, key=None, default=None)
max(arg1, arg2, *args, key=None)
iterable: The iterable (like a list or tuple) whose largest element is to be found.
arg1, arg2, *args: The arguments that are compared to find the maximum.
Example:
# Using max() with a list
numbers = [10, 20, 4, 45, 99]
print(max(numbers)) # Output: 99
2. min() Function
The min() function returns the smallest item in an iterable or the smallest of two or more arguments.
Syntax:
min(iterable, *, key=None, default=None)
min(arg1, arg2, *args, key=None)
Example:
# Using min() with a list
numbers = [10, 20, 4, 45, 99]
print(min(numbers)) # Output: 4
3. len() Function
The len() function returns the number of items (length) in an object such as a string, list, tuple, etc.
Syntax:
len(s)
Example:
# Using len() with a string
word = "Hello"
print(len(word)) # Output: 5
# Using len() with a list
numbers = [1, 2, 3, 4]
print(len(numbers)) # Output: 4
4. abs() Function
The abs() function returns the absolute value of a number. The absolute value is the non-negative value of
the number, regardless of its sign.
Syntax:
abs(x)
Example:
# Using abs() with positive and negative numbers
print(abs(-5)) # Output: 5
print(abs(3)) # Output: 3
5. round() Function
The round() function returns a floating-point number rounded to a specified number of decimal places. By
default, it rounds to the nearest integer.
Syntax:
round(number, ndigits=None)
Example:
# Using round() with a number
print(round(3.14159, 2)) # Output: 3.14
6. pow() Function
The pow() function returns the value of x raised to the power of y (i.e., x**y), and it can also accept an
optional third argument z, which returns (x ** y) % z.
Syntax:
pow(x, y)
pow(x, y, z)
Example:
# Using pow() with two arguments (x raised to the power y)
print(pow(2, 3)) # Output: 8
# Using pow() with three arguments (x raised to the power y, then mod z)
print(pow(2, 3, 5)) # Output: 3 (because 2^3 % 5 = 8 % 5 = 3)
7. sum() Function
The sum() function returns the sum of all elements in an iterable (e.g., a list or tuple).
Syntax:
sum(iterable, start=0)
iterable: The iterable whose elements are to be summed.
start: An optional value that is added to the sum (default is 0).
Example:
# Using sum() with a list of numbers
numbers = [1, 2, 3, 4, 5]
print(sum(numbers)) # Output: 15
8. eval() Function
The eval() function parses the expression passed to it and executes Python code within the string. It is
often used to evaluate dynamically generated code. However, it should be used with caution, as it can
execute arbitrary and potentially harmful code.
Syntax:
eval(expression, globals=None, locals=None)
Example:
# Using eval() to evaluate a mathematical expression
expression = "2 + 3 * 4"
print(eval(expression)) # Output: 14
9. exec() Function
The exec() function executes Python code dynamically, which can include any valid Python statement (not
just expressions, like eval()).
Syntax:
exec(object, globals=None, locals=None)
Example:
# Using exec() to execute a simple statement
code = """
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
"""
exec(code)
Output:
Hello, Alice!
In this example, the string code contains a function definition and a function call. The exec() function
executes the string, and the function greet is defined and then called.
Summary of Functions:
len() Returns the number of items in an object (e.g., string, list). len("Hello") → 5
Returns the value of x raised to the power of y, optionally with a pow(2, 3) → 8, pow(2, 3, 5)
pow()
modulus. →3
Conclusion:
These built-in functions are essential tools in Python, providing a wide range of functionality, from basic
operations like max(), min(), and sum() to more advanced capabilities like eval() and exec(), which can
dynamically execute Python code. Always use eval() and exec() with caution, as they can execute
arbitrary code.