Fundamental algorithm
Fundamental algorithm
1. Inclusion of lowercase letters (a-z): Ensures the password isn't entirely
numeric or uppercase.
2. Inclusion of digits (0-9): Adds complexity, making it harder for attackers to
guess using simple dictionary attacks.
3. Inclusion of uppercase letters (A-Z): Enhances complexity and resists
brute-force attacks more effectively.
4. Inclusion of special characters ($, #, @): Makes the password resistant to
common password cracking techniques by adding non-alphanumeric
characters.
5. Length restrictions (6-12 characters): Ensures the password isn't too short
(prone to brute force) or excessively long (unnecessary complexity).
print("PASSWORD VALIDATION")
passwd = input("Enter your password: ")
#Conditions
if len(passwd) < 12 and len(passwd) > 6:
print("VALID PASSWORD IN TERMS OF LENGTH")
else:
print("INVALID PASSWORD IN TERMS OF LENGTH")
special = "$#@"
has_lower = False
has_upper = False
has_digits = False
has_special = False
for char in passwd:
if char.islower():
has_lower = True
elif char.isupper():
has_upper = True
elif char.isdigit():
has_digit = True
elif char in special:
has_special = True
if has_lower and has_upper and has_digit and has_special:
print("VALID PASSWORD IN TERMS OF CHARACTERS")
else:
print("INVALID PASSWORD IN TERMS OF CHARACTERS")
5. Examine the role of continue and break statements in controlling program
flow. Discuss how these statements can alter the behaviour of loops in different
scenarios. Then, write a Python program that checks whether a number is
prime, prompting the user for input.
● continue Statement
○ The continue statement is used to skip the current iteration of the
loop and proceed directly to the next iteration.
○ Effect on Loop Behavior:
■ When continue is encountered, the remaining code in the
current iteration is not executed.
■ The loop jumps back to evaluate its condition and, if true,
proceeds to the next iteration.
○ Common Use Cases:
■ Skipping unwanted iterations based on a condition.
■ Filtering out specific values or scenarios in a loop
● break Statement
○ The break statement is used to terminate the loop entirely,
regardless of the loop condition.
○ Effect on Loop Behavior:
■ When a break is encountered, the loop stops execution
immediately.
■ The program flow continues with the first statement following
the loop.
○ Common Use Cases:
■ Exiting a loop early when a condition is met.
■ Preventing unnecessary iterations when the desired result is
already achieved.
for i in range(2,num-1):
if num%i == 0:
break
else:
break
● if Statement
1. The if statement allows you to test a condition and execute a block
of code if the condition is true.
2. Example:
age = 18
● if-else Statement
1. The if-else statement is used when you have two possible
outcomes. If the condition is true, one block of code is executed;
otherwise, another block is executed.
2. Example:
age = 16
else:
marks = 75
print("Grade: A")
print("Grade: B")
print("Grade: C")
else:
print("Grade: D")
● Nested if Statements
1. A nested if statement occurs when one if statement is placed inside
another. This is useful when you need to check multiple conditions
that depend on the outcome of a previous condition.
2. Example:
age = 25
income = 30000
else:
else:
print("Not eligible for loan")
x = 5
y = 10
a = 5
b = 2
if a > 10 or b > 1:
● for Loop
1. The for loop is used to iterate over a sequence (e.g., a list, tuple,
string, or range) or any iterable object. It executes the loop body for
each element in the sequence.
2. Example:
print(fruit)
● while Loop
1. The while loop executes a block of code repeatedly as long as the
specified condition is True.
2. Example:
count = 5
print(count)
count -= 1
1. break:
if i == 5:
break
print(i)
2. continue:
if i % 2 == 0:
continue
print(i)
3. pass:
❖ The pass statement does nothing. It’s a placeholder for code that is yet to be
written.
❖ Example:
for i in range(5):
if i == 3:
pass # Placeholder
else:
print(i)
● Nested Loops
1. A loop inside another loop is called a nested loop. Both for and while loops
can be nested.
2. Example:
● Infinite Loops
1. An infinite loop runs indefinitely if the condition never becomes False. Use it
with caution.
2. Example:
while True:
user_input = input("Enter 'exit' to quit: ")
if user_input.lower() == "exit":
break
10. Identify a Python program that asks the user to input a number n. The
program should generate and display the Fibonacci sequence up to the n-th
term. Ensure the program can handle edge cases, such as when the user enters
a number less than or equal to 0
def fibonacci(n):
# Handle edge cases
if n <= 0:
return "Please enter a number greater than 0."
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
# Generate Fibonacci sequence for n > 2
fib_sequence = [0, 1]
for i in range(2, n):
next_term = fib_sequence[i - 1] + fib_sequence[i - 2]
fib_sequence.append(next_term)
return fib_sequence
n = int(input("Enter a number n: "))
result = fibonacci(n)
if isinstance(result, list):
print("Fibonacci sequence up to the", n, "th term:", result)
else:
print(result)
11. Analyse a Python program that iterates through a list of integers and
performs the following actions using iteration statements: Use a for loop to
print each number. Use a while loop to print numbers until a specific condition
is met Use break to exit the loop when a specific number (e.g., 5) is
encountered. Use continue to skip printing even numbers. Use pass to handle a
specific case where you don't want to perform any action.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 1. Use a for loop to print each number
print("Using for loop:")
for num in numbers:
print(num)
# 2. Use a while loop to print numbers until a specific condition is
met (e.g., until number 6 is encountered)
print("\nUsing while loop (printing until 6):")
i = 0
while i < len(numbers):
print(numbers[i])
if numbers[i] == 6:
break
i += 1
# 3. Use break to exit the loop when a specific number (5) is
encountered
print("\nUsing break (exit at number 5):")
for num in numbers:
if num == 5:
break
print(num)
# 4. Use continue to skip printing even numbers
print("\nUsing continue (skip even numbers):")
for num in numbers:
if num % 2 == 0:
continue
print(num)
# 5. Use pass to handle a case where no action is performed
print("\nUsing pass (skip number 3 but don't print anything):")
for num in numbers:
if num == 3:
pass
else:
print(num)
12. Develop a Python program to swap the values of two variables using
arithmetic operations instead of a temporary third variable
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
a = a + b
b = a - b
a = a - b
print("New first number after swapping:", a)
print("New second number after swapping:", b)
13. What are transfer statements in Python? Explain their purpose, types, and
how they are used in control flow with appropriate examples for each type.
if i == 5:
print(i)
if i % 2 == 0:
print(i)
return a + b
result = add_numbers(5, 3)
print(result)
if i == 3:
else:
print(i)
● break allows for early termination of loops, which is helpful when a condition
is met and further iteration is unnecessary.
● continue allows skipping over specific iterations in a loop based on
conditions, which can optimize performance or avoid unwanted
computations.
● return is used to exit a function immediately, returning a value to the calling
point.
● pass is useful as a placeholder in situations where code structure requires a
statement, but no action is needed.
1. Simplicity: The for loop is more concise and readable, especially when the
number of iterations is known in advance (from 1 to n). You don’t need to
manually increment the counter or check the condition.
2. Automatic Iteration: The range() function automatically generates the
sequence of numbers, removing the need for manual control over the
iteration (like updating the counter in a while loop).
3. Less Error-Prone: Since the for loop handles the iteration automatically,
there’s less chance of errors like forgetting to increment the counter or
forgetting to break the loop when the condition is met.
4. Efficiency: The for loop, especially with range(), is optimized for cases
where the number of iterations is predetermined.
Error 1: Expected colon after the if statement which signifies the start of a new
code block.
Error 2: The number variable was initially storing a string input because of input()
function, but a decimal value was intended to be stored. Thus, we needed to add
the float() function before it.
Error 3: There is supposed to be no indentation before calling the function as it
has to be outside the function block to be able to call it.
22. Write the output of the given code and explain the purpose of continue
statement in both the example. (4M)
# First Example
for letter in 'Welcome’:
if letter == 'c’:
continue
print ('Current Letter :', letter)
# Second Example
var = 10
While var> 0:
print('Current variable value :', var)
var = var -1
if var == 5:
continue print ("End!”)
Output of first example:
Current Letter : W
Current Letter : e
Current Letter : l
Current Letter : o
Current Letter : m
Current Letter : e
23. Create a Python program for an open-air theatre that calculates ticket
prices based on age, vehicle and time of day. Tickets for children (age < 10) are
€6 for two-wheeler and €8 for four wheeler, adults (age >= 10) are €10 for
two-wheeler and €12 for four-wheeler, senior citizens (age >= 60) are €9 for any
vehicle. For evening shows (after 5 PM), there’s an additional €2 surcharge.
print("OPEN AIR THEATRE TICKET PRICING")
print("Kindly give the following data: ")
age = int(input("Enter your age: "))
time = float(input("Enter the time in 24-hour format: "))
vehicle = int(input("Enter the vehicle preference (2/4): "))
surcharge = 2 if time >= 17 else 0
if age < 10:
if vehicle == 2:
price = 6
elif vehicle == 4:
price = 8
else:
print("Invalid Vehicle Preference!")
exit()
elif age >= 10 and age < 60:
if vehicle == 2:
price = 10
elif vehicle == 4:
price = 12
else:
print("Invalid Vehicle Preference!")
exit()
else:
price = 9
● For Loop:
1. A for loop is generally used when the number of iterations is known
or defined. It automatically handles the iteration and termination
based on the given range or iterable.
2. Flow of Execution:
a. The for loop begins by evaluating the range or iterable
(range(1, 6) in this case).
b. It initializes i to 1, executes the body of the loop, then
increments i.
c. The loop continues until the value of i exceeds 5.
d. No explicit condition checking or updating of i is needed by
the programmer.
● While Loop:
1. A while loop is used when the number of iterations is not known, and
the loop should continue based on a condition that is checked before
each iteration.
2. Flow of Execution:
a. The while loop starts by checking the condition (i <= 5).
b. If the condition is true, the body of the loop is executed
(printing the value of i).
c. The value of i is manually updated after each iteration (i +=
1).
d. The loop continues until the condition becomes false.
25. Explain the syntax of the range function. The following for-loop is written to
print the numbers using the range function. Are these loops correct? Justify
your answer
1. Divide the Decimal Number by 2: Write down the quotient and remainder.
2. Record the Remainders: The remainder is either 0 or 1.
3. Repeat Division: Continue dividing the quotient by 2 until it becomes 0.
4. Write the Binary Representation: The binary representation is the
remainders read from bottom to top.
binary_representation = bin(decimal_number)
binary_representation = binary_representation[2:]