Cia Ii (PSPP - 24ucs301 Answerkey)
Cia Ii (PSPP - 24ucs301 Answerkey)
ANSWER KEY
Python provides a variety of built-in data types to handle different kinds of data. Here's a
comprehensive list of Python data types:
1. Numeric Types
2. Sequence Types
3. Text Type
4. Set Types
5. Mapping Type
6. Boolean Type
7. Binary Types
8. None Type
9. Callable and Iterator Types
10. Custom Types
11. Special Data Types (via Libraries)
Step 1: Start
Step 2: Input the three numbers: a, b, c.
Step 3:If a > b and a > c, then:
Output a as the largest number.
Step 4:Else if b > c, then:
Output b as the largest number.
Step 5:Else:
Output c as the largest number.
Step 6:End
Interpreter
Interactive Mode
Interactive mode is a feature provided by interpreters that allows users to execute commands one
at a time and see the output immediately. It provides a quick and convenient way to test code
snippets, experiment with features, or learn a programming language.
How It Works:
1. You type a statement or expression directly into the interpreter prompt.
2. The interpreter executes it and displays the result immediately.
Examples:
o Python: The Python Shell or REPL (Read-Eval-Print Loop).
o JavaScript: Browsers' developer console.
o SQL: Database management systems' interactive prompt.
Key Features:
Immediate feedback on each command.
A Boolean value represents one of two possible states: True or False. These values are
fundamental in computer science and are primarily used in decision-making, logical operations,
and control flow.
Boolean Expressions
A Boolean expression is an expression that evaluates to a Boolean value: either True or False.
These expressions often involve:
1. Comparison Expressions:
o 5 > 3 evaluates to True.
o 10 == 15 evaluates to False.
2. Logical Expressions:
o (5 > 3) and (10 < 20) evaluates to True.
o not (5 == 3) evaluates to True.
3. Combined Expressions:
o (x > 10) or (y <= 5) evaluates to True if either x > 10 or y <= 5.
6. Difference between local variable and global variable.
Aspect
A variable declared inside a
A variable declared outside all functions,
Definition function or block, accessible only
accessible throughout the program.
within that function or block.
Limited to the function or block in Available globally across the entire
Scope
which it is defined. program, including all functions.
Created when the function is called
Exists for the entire duration of the
Lifetime and destroyed when the function
program’s execution.
exits.
Not accessible outside the
Accessibility function/block in which it is Accessible from any part of the program.
defined.
In some languages (e.g., Python), the
Keyword No special keyword is required to
global keyword may be needed to modify
Requirement declare it.
a global variable inside a function.
Used for temporary storage of data
Used to share data between multiple
Usage Purpose and encapsulation within a specific
functions or parts of a program.
task.
Less prone to accidental
Prone to unintended modifications, which
Risk modification by other parts of the
can lead to bugs in larger programs.
program.
A string is a sequence of characters used to represent text in programming. Strings are enclosed
in quotes, either single quotes (' ') or double quotes (" "), depending on the programming
language. In some languages, strings can also be enclosed in triple quotes (e.g., Python) for
multi-line strings.
Example:
1. Immutable: Strings cannot be changed after they are created (common in most
languages, like Python and Java).
2. Indexed: Strings are indexed, meaning each character can be accessed using its position
(0-based indexing in most languages).
o Example: "Python"[0] gives 'P'.
3. Iterables: Strings can be iterated over, character by character.
Here is a list of commonly used string functions, with explanations and examples (Python is used
for illustration):
1. len()
text = "Hello"
print(len(text)) # Output: 5
2. lower()
3. upper()
4. strip()
5. replace(old, new)
Description: Returns the index of the first occurrence of the substring. Returns -1 if not
found.
Example:
print("Hello".find("e")) # Output: 1
7. split(delimiter)
Description: Splits the string into a list of substrings based on the specified delimiter.
Example:
8. join(iterable)
Description: Joins elements of an iterable (e.g., list) into a string, with the calling string
as a delimiter.
Example:
9. startswith(prefix) / endswith(suffix)
Description: Checks if the string starts or ends with the specified prefix or suffix.
Example:
10. isalpha()
11. isdigit()
12. isalnum()
Description: Returns True if the string contains only alphanumeric characters (letters and
digits).
Example:
print("Hello123".isalnum()) # Output: True
13. capitalize()
14. title()
15. count(substring)
print("banana".count("a")) # Output: 3
17. format()
18. zfill(width)
Description: Pads the string on the left with zeros to make it of the specified width.
Example:
Function Description
len() Get string length.
lower(), upper() Convert to lowercase/uppercase.
Function Description
strip() Remove leading/trailing spaces.
replace() Replace substring.
split(), join() Split string or join iterables into a string.
find() Find index of a substring.
startswith(), endswith() Check prefix or suffix.
isalpha(), isdigit(), isalnum() Validate string contents.
capitalize() Capitalize the first letter.
title() Capitalize the first letter of each word.
count() Count occurrences of a substring.
isupper(), islower() Check for uppercase/lowercase letters.
format() Format strings with placeholders.
zfill() Pad with leading zeros.
Operators in Python are special symbols or keywords used to perform operations on operands (values or
variables). Below is a detailed list of operator types:
1. Arithmetic Operators
3. Logical Operators
4. Bitwise Operators
5. Assignment Operators
7. Identity Operators
Operator precedence determines the order in which operators are evaluated in an expression.
Operators with higher precedence are evaluated first.
Tower of Hanoi
The Tower of Hanoi is a classic mathematical puzzle that involves moving a set of disks from
one peg to another, following specific rules. The puzzle was invented by the French
mathematician Édouard Lucas in 1883.
1. There are three pegs: Source (A), Auxiliary (B), and Destination (C).
2. A set of disks of different sizes is placed on the Source peg in decreasing order of size
(largest at the bottom, smallest at the top).
3. The goal is to move all the disks from the Source peg to the Destination peg.
4. Rules to follow while moving disks:
o Only one disk can be moved at a time.
o A disk can only be placed on top of a larger disk or on an empty peg.
o All moves must be performed using the Auxiliary peg.
Recursive Algorithm
The minimum number of moves required to solve the Tower of Hanoi problem with n disks is:
Moves= 2n-1.
For example:
8(b). Explain simple strategies for developing algorithm (Recursion & iteration) with example.
When developing an algorithm, two fundamental strategies to solve problems are recursion and
iteration. Both approaches achieve the same goal but differ in how they process the problem.
1. Recursion
Definition:
Recursion is a problem-solving strategy where a function calls itself to break down a larger
problem into smaller, similar subproblems until a base case is reached.
1. Base Case: The condition under which the recursion stops (avoids infinite recursion).
2. Recursive Case: The part where the function calls itself to solve smaller subproblems.
Example 1: Factorial
Recursive Implementation:
def factorial(n):
if n == 0:
# Base case
return 1
else:
return n * factorial(n - 1)
# Recursive case
print(factorial(5))
# Output: 120
How It Works:
Recursive Implementation:
def fibonacci(n):
if n == 0: # Base case
return 0
return 1
else:
print(fibonacci(6)) # Output: 8
2. Iteration
Definition:
Iteration is a problem-solving strategy that uses loops to repeatedly perform a set of instructions
until a condition is met.
Example 1: Factorial
Iterative Implementation:
def factorial_iterative(n):
result = 1
result *= i
return result
Iterative Implementation:
def fibonacci_iterative(n):
if n == 0:
return 0
elif n == 1:
return 1
a, b = 0, 1
a, b = b, a + b
return b
print(fibonacci_iterative(6)) # Output: 8
Recursive Approach
def sum_recursive(n):
if n == 0: # Base case
return 0
else:
print(sum_recursive(5)) # Output: 15
Iterative Approach
def sum_iterative(n):
total = 0
total += i
return total
print(sum_iterative(5)) # Output: 15
Conclusion
Recursion is elegant and useful for problems with naturally recursive structures but can
be inefficient due to stack overhead.
Iteration is generally more efficient and preferred for performance-critical tasks.
Choose the strategy that best fits the problem and constraints!
Conditional statements in Python allow the execution of specific blocks of code based on certain
conditions. These are essential for decision-making in programs.
1. if Statement
2. if-else Statement
3. if-elif-else Statement
4. Nested Conditional Statements
5. match Statement (Python 3.10 and later)
1. if Statement
The if statement executes a block of code only if a specified condition evaluates to True.
Syntax:
if condition:
Example:
x = 10
if x > 5:
2. if-else Statement
The if-else statement provides an alternative block of code to execute if the condition evaluates to
False.
Syntax:
if condition:
else:
Example:
x=3
if x > 5:
else:
3.if-elif-else Statement
The if-elif-else statement is used when multiple conditions need to be checked. The elif (short for "else if")
is used to test additional conditions after the initial if.
Syntax:
if condition1:
elif condition2:
else:
# Code to execute if none of the conditions are True
Example:
x = 15
if x < 10:
else:
print("x is 20 or more")
Conditional statements can be nested, meaning an if or if-else statement can exist inside another.
if condition1:
if condition2:
else:
else:
Example:
x = 10
y = 20
if x > 5:
if y > 15:
print("x is greater than 5 and y is greater than 15")
else:
else:
5. match Statement
The match statement, introduced in Python 3.10, provides a cleaner way to perform pattern matching,
similar to a switch statement in other languages.
match variable:
case pattern1:
case pattern2:
case _:
Example:
day = "Monday"
match day:
case "Monday":
case "Friday":
case _:
age = 18
print("Child")
print("Teenager")
else:
print("Adult")
# Output: Adult
In Python, looping and unconditional statements are used to control the flow of execution within
a program. They are essential for implementing repetitive tasks and breaking or skipping
operations under specific conditions.
1. Looping Statements
Looping statements allow you to execute a block of code repeatedly based on a condition.
1. for Loop
2. while Loop
1.1. for Loop
The for loop is used to iterate over a sequence (e.g., list, tuple, string, or range).
Syntax:
Example:
print(fruit)
# Output:
# apple
# banana
# cherry
print(i)
# Output:
#0
#1
#2
#3
#4
Syntax:
while condition:
# Code block to execute
Example:
count = 0
print(count)
count += 1
# Output:
#0
#1
#2
#3
#4
3.Unconditional Statements :
Unconditional statements alter the normal flow of loops or skip specific parts of code. Python
provides the following:
1. break Statement
2. continue Statement
3. pass Statement
The break statement terminates the loop prematurely, regardless of the loop condition.
for i in range(10):
if i == 5:
break
print(i)
# Output:
#0
#1
#2
#3
#4
The continue statement skips the current iteration and proceeds to the next iteration of the loop.
for i in range(5):
if i == 2:
continue
print(i)
# Output:
#0
#1
#3
#4
Example:
for i in range(5):
if i == 2:
continue
print(i)
# Output:
#0
#1
#3
#4
The pass statement is a placeholder that does nothing. It is often used when a block of code is
syntactically required but you don't want to implement it yet.
for i in range(5):
if i == 2:
pass # Placeholder for future code
print(i)
# Output:
#0
#1
#2
#3
#4
Statement Purpose
break Exits the loop entirely.
continue Skips the rest of the current iteration and moves to the next iteration.
Does nothing; used as a placeholder or for maintaining syntactical structure in the
pass
program.
Example:
n = 10
for i in range(n):
if i % 2 == 0:
if i > 7:
print(i)
# Output:
#1
#3
#5
#7
Infinite Loops
An infinite loop occurs when the loop's terminating condition is never met. This can be useful
but should be handled carefully.
Example:
while True:
In Summary
Looping Statements:
o for: Iterates over sequences.
o while: Repeats code while a condition is True.
Unconditional Statements:
o break: Terminates a loop.
o continue: Skips to the next iteration.
o pass: Does nothing (placeholder).
A fruitful function in Python is a function that returns a value when called. Unlike a void
function (which performs an action but doesn't return a value), fruitful functions are designed to
compute and return results that can be used in further computations.
1. return Statement:
o A fruitful function must include a return statement to pass a value back to the
caller.
o The return statement can return any type of value (e.g., number, string, list, or even
another function).
2. Reusable Output:
o The returned value can be assigned to a variable, used in expressions, or passed as
arguments to other functions.
3. Custom Logic:
o Fruitful functions can include custom logic to perform calculations, process data,
or generate results.
A fruitful function in Python is a function that returns a value when called. Unlike a void
function (which performs an action but doesn't return a value), fruitful functions are designed to
compute and return results that can be used in further computations.
1. return Statement:
o A fruitful function must include a return statement to pass a value back to the
caller.
o The return statement can return any type of value (e.g., number, string, list, or even
another function).
2. Reusable Output:
o The returned value can be assigned to a variable, used in expressions, or passed as
arguments to other functions.
3. Custom Logic:
o Fruitful functions can include custom logic to perform calculations, process data,
or generate results.
Syntax
def function_name(parameters):
# Perform operations
return value
return a + b
result = add(5, 3)
print(result) # Output: 8
Computing a Factorial
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
def is_even(num):
return num % 2 == 0
sum_ = a + b
difference = a - b
result = calculate(10, 5)
def check_number(num):
if num > 0:
return "Positive"
return "Negative"
else:
return "Zero"
Conclusion
Fruitful functions are essential in Python programming for computations and logical operations
that produce reusable results. They are an integral part of creating efficient, modular, and
readable code.