Docs
Python
Unit 2

1. What is operator? Which operators used in Python ?

Operator is a symbol that represents an operation to be performed on one or more operands. Python provides a wide range of operators to perform various operations. Here is a list of commonly used operators in Python:

  1. Arithmetic Operators: + (Addition), - (Subtraction), * (Multiplication), / (Division), % (Modulo), ** (Exponentiation), // (Floor Division)
  2. Comparison Operators: == (Equal to), != (Not equal to), < (Less than), > (Greater than), <= (Less than or equal to), >= (Greater than or equal to)
  3. Assignment Operators: = (Assignment), += (Add and assign), -= (Subtract and assign), *= (Multiply and assign), /= (Divide and assign), %= (Modulo and assign), **= (Exponentiate and assign), //= (Floor divide and assign)
  4. Logical Operators: and (Logical AND), or (Logical OR), not (Logical NOT)
  5. Bitwise Operators: & (Bitwise AND), | (Bitwise OR), ^ (Bitwise XOR), ~ (Bitwise NOT), << (Left shift), >> (Right shift)
  6. Membership Operators: in (Membership test), not in (Negated membership test)
  7. Identity Operators: is (Object identity), is not (Negated object identity)

These operators can be used with different data types such as integers, floating-point numbers, strings, lists, tuples, and dictionaries to perform various operations.


2. What is meant by control flow of a program?

Control flow refers to the order in which statements are executed in a program. Python provides several control flow structures to enable the programmer to control the order in which statements are executed. Some of the commonly used control flow structures in Python include:

  1. Conditional statements (if-elif-else statements): These statements allow the program to execute certain statements based on the evaluation of a condition. If the condition is true, the program executes one block of statements, and if it is false, it executes a different block of statements.
  2. Loops (for and while loops): These structures enable the program to execute a block of statements repeatedly until a certain condition is met. For loops are used to iterate over a sequence (such as a list, tuple, or dictionary) a fixed number of times, while loops continue to execute until a certain condition is no longer true.
  3. Break and continue statements: These statements are used to control the execution of loops. The break statement is used to terminate a loop early, while the continue statement is used to skip to the next iteration of the loop.
  4. Exception handling (try-except statements): These statements enable the program to handle errors and exceptions that may occur during execution. The try block contains the statements that may raise an exception, while the except block specifies how to handle the exception if it occurs.

3. Define the terms:

  • Loop: A loop is a programming construct that allows a set of statements to be executed repeatedly while a certain condition is true. In Python, there are two types of loops: for loop and while loop.
  • Program: A program is a set of instructions or statements that tell a computer what to do. It can be written in various programming languages and can range from simple scripts to complex applications.
  • Operator: An operator is a symbol that represents a specific operation to be performed on one or more operands. In Python, operators are used to perform arithmetic, comparison, logical, and other types of operations.
  • Control flow: Control flow refers to the order in which the statements in a program are executed. In Python, control flow is determined by the use of control structures such as conditional statements, loops, and function calls. These structures allow the program to make decisions, perform repetitive tasks, and execute different sections of code based on various conditions.

4. What are the different loops available in Python?

Python provides two types of loops: the for loop and the while loop.

  1. For loop: A for loop in Python is used to iterate over a sequence, such as a list, tuple, or string, and execute a set of statements for each item in the sequence. The basic syntax of a for loop is:
vros.py
for variable in sequence:
    # statements to be executed for each item in sequence

In this syntax, the variable is set to each item in the sequence in turn, and the statements in the loop are executed for each item.

  1. While loop: A while loop in Python is used to repeatedly execute a set of statements as long as a certain condition is true. The basic syntax of a while loop is:
vros.py
while condition:
    # statements to be executed while the condition is true

In this syntax, the condition is a Boolean expression that is evaluated before each iteration of the loop. If the condition is true, the statements in the loop are executed, and the condition is checked again before the next iteration.

Both for and while loops can be used to iterate over a sequence of items, but while loops can also be used to repeatedly execute a set of statements based on a condition, without needing to iterate over a sequence. It's important to ensure that the condition in a while loop is eventually false, otherwise, the loop will run indefinitely.

here are some examples of the different loops available in Python:

  • For loop:
vros.py
 
# iterate over a list of numbers and print each one
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    print(num)
 
# iterate over a string and print each character
word = "Hello"
for char in word:
    print(char)
  • While loop:
vros.py
# print numbers from 1 to 5 using a while loop
i = 1
while i <= 5:
    print(i)
    i += 1
 
# ask the user for input until they enter a valid number
valid_input = False
while not valid_input:
    user_input = input("Enter a number between 1 and 10: ")
    if user_input.isdigit() and 1 <= int(user_input) <= 10:
        valid_input = True
    else:
        print("Invalid input, please try again")

In the first example, a for loop is used to iterate over a list of numbers and a string, and print each item. In the second example, a while loop is used to print numbers from 1 to 5 and to prompt the user for input until they enter a valid number.


5. What happens if a semicolon (;) is placed at the end of a Python statement?

In Python, the semicolon (;) is used to separate multiple statements on the same line. For example, instead of writing two separate lines like this:

vros.py
x = 1
y = 2

You can write them on a single line using a semicolon:

vros.py
x = 1; y = 2

However, placing a semicolon at the end of a single statement in Python is not required or recommended. It does not change the behavior of the statement or affect the program's execution in any way. Here is an example of a statement with a semicolon at the end:

vros.py
print("Hello, World!");

This statement will execute normally and print "Hello, World!" to the console, but the semicolon is unnecessary and is generally considered to be unpythonic style. In general, it's best to avoid using semicolons at the end of statements in Python.


6. Explain about different logical operators in Python with appropriate examples.

Python provides three logical operators: and, or, and not. These operators are used to combine two or more Boolean expressions and evaluate them as a single expression.

  1. and operator: The and operator returns True if both operands are True, and False otherwise. Here's an example:
vros.py
x = 5
y = 10
z = 15
result = (x < y) and (y < z)
print(result)  # Output: True

In this example, the and operator combines two Boolean expressions (x < y and y < z) and evaluates them as a single expression. Since both expressions are True, the result is True.

  1. or operator: The or operator returns True if either operand is True, and False otherwise. Here's an example:
vros.py
x = 5
y = 10
z = 15
result = (x > y) or (y < z)
print(result)  # Output: True

In this example, the or operator combines two Boolean expressions (x > y and y < z) and evaluates them as a single expression. Since the second expression (y < z) is True, the result is True.

  1. not operator: The not operator returns True if the operand is False, and False if the operand is True. Here's an example:
vros.py
x = 5
y = 10
z = 15
result = not(x > y)
print(result)  # Output: True

In this example, the not operator negates the Boolean expression x > y, which is False. Therefore, the result is True.


7. Explain about different relational operators in Python with examples.

Relational operators are used to compare values and determine the relationship between them. These operators return a boolean value of either True or False. Here are the different relational operators in Python along with examples:

  1. Equal to (==) Operator: The '==' operator is used to check if two values are equal or not. If the values are equal, it returns True; otherwise, it returns False.

Example:

vros.py
x = 5
y = 7
print(x == y) # Output: False
  1. Not equal to (!=) Operator: The '!=' operator is used to check if two values are not equal. If the values are not equal, it returns True; otherwise, it returns False.

Example:

vros.py
x = 5
y = 7
print(x != y) # Output: True
  1. Greater than (>) Operator: The '>' operator is used to check if the left operand is greater than the right operand. If the left operand is greater, it returns True; otherwise, it returns False.

Example:

vros.py
x = 5
y = 7
print(y > x) # Output: True
  1. Less than (<) Operator: The < operator is used to check if the left operand is less than the right operand. If the left operand is less, it returns True; otherwise, it returns False.

Example:

vros.py
x = 5
y = 7
print(x < y) # Output: True
  1. Greater than or equal to (>=) Operator: The >= operator is used to check if the left operand is greater than or equal to the right operand. If the left operand is greater than or equal to the right operand, it returns True; otherwise, it returns False.

Example:

vros.py
x = 5
y = 7
print(y >= x) # Output: True
  1. Less than or equal to (<=) Operator: The <= operator is used to check if the left operand is less than or equal to the right operand. If the left operand is less than or equal to the right operand, it returns True; otherwise, it returns False.

Example:

vros.py
x = 5
y = 7
print(x <= y) # Output: True

8. Explain about membership operators in Python.

Python provides two membership operators: in and not in. These operators are used to test whether a value is a member of a sequence, such as a string, list, or tuple.

  1. in operator: The in operator returns True if the value is found in the sequence, and False otherwise. Here's an example:
vros.py
x = "Hello, World"
result = "o" in x
print(result)  # Output: True

In this example, the in operator tests whether the character "o" is a member of the string "Hello, World". Since "o" is present in the string, the result is True.

  1. not in operator: The not in operator returns True if the value is not found in the sequence, and False otherwise. Here's an example:
vros.py
x = [1, 2, 3, 4, 5]
result = 6 not in x
print(result)  # Output: True

In this example, the not in operator tests whether the value 6 is a member of the list [1, 2, 3, 4, 5]. Since 6 is not present in the list, the result is True.


9. Explain about Identity operators in Python with appropriate examples.

Python provides two identity operators: is and is not. These operators are used to compare the memory location of two objects to check whether they are the same object or not.

  1. is operator: The is operator returns True if both operands refer to the same object in memory, and False otherwise. Here's an example:
vros.py
x = [1, 2, 3]
y = x
result = y is x
print(result)  # Output: True

In this example, the is operator compares the memory location of x and y, which both refer to the same list object. Therefore, the result is True.

  1. is not operator: The is not operator returns True if both operands do not refer to the same object in memory, and False if they refer to the same object. Here's an example:
vros.py
x = [1, 2, 3]
y = [1, 2, 3]
result = y is not x
print(result)  # Output: True

In this example, the is not operator compares the memory location of x and y, which refer to two different list objects with the same values. Therefore, the result is True.

Identity operators are used to compare objects based on their memory location, rather than their values. They can be useful in situations where you need to check whether two variables refer to the same object, or to test for object identity in more complex data structures like trees and graphs.


10. Explain about arithmetic operators in Python.

Arithmetic operators are used in Python to perform mathematical operations on numerical values. These operators are similar to the ones used in mathematics and include the following:

  1. Addition (+): This operator is used to add two or more numbers together.
  2. Subtraction (-): This operator is used to subtract one number from another.
  3. Multiplication (*): This operator is used to multiply two or more numbers together.
  4. Division (/): This operator is used to divide one number by another.
  5. Modulus (%): This operator is used to find the remainder of a division operation.
  6. Exponentiation (**): This operator is used to raise a number to a power.

Here is an example of using arithmetic operators in Python:

vros.py
a = 10
b = 5
c = a + b    # Addition
d = a - b    # Subtraction
e = a * b    # Multiplication
f = a / b    # Division
g = a % b    # Modulus
h = a ** b   # Exponentiation
 
print(c)     # Output: 15
print(d)     # Output: 5
print(e)     # Output: 50
print(f)     # Output: 2.0
print(g)     # Output: 0
print(h)     # Output: 100000

11. List different conditional statements in Python.

Conditional statements in Python are used to execute certain blocks of code based on certain conditions. The most common conditional statements in Python are:

  1. if statement: The if statement is used to execute a block of code if a certain condition is true.
  2. if-else statement: The if-else statement is used to execute a block of code if a condition is true, and another block of code if the condition is false.
  3. if-elif-else statement: The if-elif-else statement is used to execute one of several blocks of code depending on which condition is true.
  4. nested if statements: Nested if statements are used to test additional conditions if the previous condition is true.

Here is an example of using each of these conditional statements in Python:

vros.py
# if statement
x = 5
if x > 0:
    print("x is positive")
 
# if-else statement
y = -2
if y > 0:
    print("y is positive")
else:
    print("y is not positive")
 
# if-elif-else statement
z = 0
if z > 0:
    print("z is positive")
elif z < 0:
    print("z is negative")
else:
    print("z is zero")
 
# nested if statements
a = 10
if a > 0:
    if a < 100:
        print("a is a positive two-digit number")

Output:

vros.py
x is positive
y is not positive
z is zero
a is a positive two-digit number

12. What are the different nested loops available in Python?

In Python, there are different types of nested loops available to iterate over complex data structures like nested lists and dictionaries. Here are the common types of nested loops in Python:

  1. Nested for loop: A nested for loop is used to iterate over a list of lists, where each inner list represents a row of data. Here's an example:
vros.py
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
    for element in row:
        print(element, end=" ")
    print()

Output:

vros.py
1 2 3
4 5 6
7 8 9

In this example, we have a list of lists representing a matrix. We use a nested for loop to iterate over each row of the matrix and print out the elements of each row.

  1. Nested while loop: A nested while loop is used to iterate over a list of lists, where each inner list represents a row of data. Here's an example:
vros.py
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
i = 0
while i < len(matrix):
    j = 0
    while j < len(matrix[i]):
        print(matrix[i][j], end=" ")
        j += 1
    print()
    i += 1

Output:

vros.py
1 2 3
4 5 6
7 8 9

In this example, we have a list of lists representing a matrix. We use a nested while loop to iterate over each row of the matrix and print out the elements of each row.

  1. Nested for loop with if statement: A nested for loop with an if statement is used to iterate over a list of dictionaries, where each dictionary represents a row of data. Here's an example:
vros.py
students = [
    {"name": "Dhruv", "grade": 85},
    {"name": "Prathmesh", "grade": 92},
    {"name": "Radhikaa", "grade": 78}
]
for student in students:
    for key, value in student.items():
        if key == "name":
            print(f"{key}: {value}", end=" ")
    print()

Output:

vros.py
name: Dhruv
name: Prathmesh
name: Radhikaa

In this example, we have a list of dictionaries representing student data. We use a nested for loop to iterate over each student's data and print out their name.


13. What are the different loop control (manipulation) statements available in Python? Explain with suitable examples.

Python provides several loop control statements that allow you to manipulate the behavior of loops. The most commonly used loop control statements in Python are break, continue, and pass.

  1. break: The break statement is used to immediately terminate a loop before its normal completion. When a break statement is encountered inside a loop, the loop is exited immediately and the program continues with the statement following the loop. Here's an example:
vros.py
numbers = [1, 2, 3, 4, 5, 6]
 
for num in numbers:
    if num == 4:
        break
    print(num)
 
print("Loop ended")

In this example, the loop prints out the numbers 1, 2, and 3. When the loop reaches the value 4, the break statement is executed and the loop is terminated immediately. The program then continues with the statement following the loop, which in this case is the print("Loop ended") statement.

  1. **continue**: The continue statement is used to skip over a particular iteration of a loop and continue with the next iteration. When a continue statement is encountered inside a loop, the current iteration is immediately terminated and the loop moves on to the next iteration. Here's an example:
vros.py
numbers = [1, 2, 3, 4, 5, 6]
 
for num in numbers:
    if num % 2 == 0:
        continue
    print(num)
 
print("Loop ended")

In this example, the loop prints out only the odd numbers in the list (1, 3, and 5). When the loop encounters an even number, the continue statement is executed and the current iteration is skipped over. The loop then moves on to the next iteration.

  1. pass: The pass statement is used as a placeholder for code that has not been written yet. It does nothing and is typically used when you need to include an empty block of code to satisfy Python's syntax requirements. Here's an example:
vros.py
for i in range(5):
    # TODO: Write code here
    pass

In this example, the loop is designed to execute some code five times, but the specific code to be executed has not yet been written. The pass statement is used as a placeholder to satisfy Python's syntax requirements.

These loop control statements can be used to modify the behavior of loops in a wide range of scenarios, making your code more flexible and adaptable.


14. Explain if-else statement with an example.

The if-else statement is a conditional statement used in Python to execute different blocks of code based on whether a condition is true or false. Here's the basic syntax of the if-else statement:

vros.py
if condition:
    # code to be executed if condition is true
else:
    # code to be executed if condition is false

In this syntax, the if statement checks whether a condition is true or false. If the condition is true, the block of code indented under the if statement is executed. If the condition is false, the block of code indented under the else statement is executed.

Here's an example of the if-else statement in action:

vros.py
x = 10
if x < 5:
    print("x is less than 5")
else:
    print("x is greater than or equal to 5")

In this example, we have a variable x with a value of 10. The if statement checks whether x is less than 5, which is false. So the block of code under the else statement is executed, which prints out "x is greater than or equal to 5".

You can use the if-else statement to perform different operations based on different conditions in your program. For example, you can use the if-else statement to check whether a user has entered a valid password, or to determine whether a user has entered a valid input.


15. Explain continue statement with an example.

In Python, the continue statement is used inside loops to skip the current iteration and continue with the next iteration of the loop. When the continue statement is executed, it immediately jumps to the next iteration of the loop without executing any code that comes after it in the loop.

Here's an example to illustrate the use of the continue statement:

vros.py
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 
# Print all even numbers in the list
for number in numbers:
    if number % 2 == 1:
        # Skip odd numbers
        continue
    print(number)

In this example, we have a list of numbers from 1 to 10. We use a for loop to iterate over the list. Inside the loop, we use an if statement to check whether the current number is odd or even. If the current number is odd, we use the continue statement to skip it and jump to the next iteration of the loop. If the current number is even, we print it out.

The output of this program will be:

vros.py
2
4
6
8
10

As you can see, the continue statement skipped the odd numbers and printed out only the even numbers. This is a simple example, but the continue statement can be very useful when working with complex loops and conditionals.


16. Explain use of break statement in a loop with example.

In Python, the break statement is used inside loops to exit the loop immediately, even if the loop condition is still true. When the break statement is executed, the control flow of the program jumps out of the loop and continues with the code that comes after the loop.

Here's an example to illustrate the use of the break statement:

vros.py
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
 
# Print numbers until we find the first even number
for number in numbers:
    if number % 2 == 0:
        # Exit the loop when we find an even number
        break
    print(number)

In this example, we have a list of numbers from 1 to 10. We use a for loop to iterate over the list. Inside the loop, we use an if statement to check whether the current number is even or odd. If the current number is even, we use the break statement to exit the loop immediately. If the current number is odd, we print it out.

The output of this program will be:

vros.py
1

As you can see, the break statement exited the loop as soon as it found the first even number, which was 2. This is a simple example, but the break statement can be very useful when working with complex loops and conditionals, especially when you need to exit a loop based on a certain condition.


17. Predict output and justify your answer:

  1. -11%9
  2. 7.7//7
  3. (200/70)*10/5
  4. 5*12**
  • The output of the expression 11%9 in Python will be 7. This is because the modulo operator % returns the remainder of the division between the two operands, and in this case, -11 divided by 9 gives a quotient of -2 and a remainder of 7.
  • The output of the expression 7.7//7 in Python will be 1.0. This is because the double slash // operator performs integer division, which means that it divides the operands and rounds the result down to the nearest integer. In this case, 7.7 divided by 7 gives a quotient of 1 with a fractional part of 0.7, which is rounded down to 0, resulting in a final answer of 1.0.
  • The output of the expression (200/70)*10/5 in Python will be approximately 0.5714. This is because the expression is evaluated from left to right, following the order of operations. First, 200 divided by 70 gives a quotient of 2 with a remainder of 60. Then, multiplying by 10 gives 20 and dividing by 5 gives the final result of 4.
  • The expression 5\*1**2 is not a valid Python expression and will result in a syntax error. The correct way to express this expression would be (5\*1)**2, which evaluates to 25.

18. What is the difference between and is operator in python?

The and operator is a logical operator that returns True if both the left and the right operands evaluate to True, and False otherwise. It can be used to chain multiple conditions together.

Here's an example of using the and operator in Python:

vros.py
x = 5
y = 10
z = 15
 
if x < y and y < z:
    print("y is between x and z")
else:
    print("y is not between x and z")

In this example, the and operator is used to combine two conditions (x < y and y < z) and check if y is between x and z.

On the other hand, the is operator is used to test if two variables refer to the same object in memory. It returns True if both variables refer to the same object, and False otherwise.

Here's an example of using the is operator in Python:

vros.py
x = [1, 2, 3]
y = x
z = [1, 2, 3]
 
if x is y:
    print("x and y refer to the same object")
else:
    print("x and y do not refer to the same object")
 
if x is z:
    print("x and z refer to the same object")
else:
    print("x and z do not refer to the same object")

In this example, x and y refer to the same object in memory (a list [1, 2, 3]), so the first condition is true. However, x and z refer to two different objects with the same values, so the second condition is false.

So, to summarize, the and operator is used for combining multiple conditions, while the is operator is used for testing if two variables refer to the same object in memory.


19. List different operators in Python, in the order of their precedence.

Here are the different operators in Python, listed in order of their precedence (highest to lowest):

  1. * (exponentiation)
  2. , /, //, % (multiplication, division, floor division, modulus)
  3. +, -(addition, subtraction)
  4. <, <=, >, >=(comparison)
  5. ==, != (equality)
  6. not (logical NOT)
  7. and (logical AND)
  8. or (logical OR)

This means that when a Python expression contains multiple operators, they will be evaluated in order of precedence. For example, in the expression 2 + 3 * 4, the multiplication (*) operator has higher precedence than the addition (+) operator, so the multiplication will be performed first and the result will be added to 2. Therefore, the result of the expression will be 14.

If you want to change the order of evaluation, you can use parentheses to group sub-expressions together. For example, (2 + 3) * 4 would evaluate to 20, because the addition inside the parentheses is evaluated first.


20. Write a Python program to print factorial of a number. Take input from user.

vros.py
n = int(input("Enter a number: "))
 
# Check if the number is negative, zero, or one
if n < 0:
    print("Factorial is not defined for negative numbers!")
elif n == 0:
    print("Factorial of 0 is 1.")
elif n == 1:
    print("Factorial of 1 is 1.")
else:
    # Initialize the factorial to be 1
    factorial = 1
    # Calculate the factorial using a for loop
    for i in range(1, n+1):
        factorial *= i
    print("Factorial of", n, "is", factorial)

In this program, we first take input from the user for a number. We then check if the number is negative, zero, or one. If the number is negative, we print an error message because the factorial is not defined for negative numbers. If the number is 0 or 1, we print the factorial as 1.

If the number is greater than 1, we initialize the factorial to be 1 and use a for loop to calculate the factorial. Inside the loop, we multiply the current value of the factorial by the loop index variable i. After the loop completes, we print the final value of the factorial.

The output of this program will depend on the input number. For example, if the user inputs 5, the program will output:

vros.py
Factorial of 5 is 120

If the user inputs 0, the program will output:

vros.py
Factorial of 0 is 1.

21 Write a Python program to calculate area of triangle and circle and print the result.

vros.py
import math
 
# Calculate the area of a triangle
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
triangle_area = 0.5 * base * height
print("The area of the triangle is:", triangle_area)
 
# Calculate the area of a circle
radius = float(input("Enter the radius of the circle: "))
circle_area = math.pi * radius**2
print("The area of the circle is:", circle_area)

In this program, we first import the math module, which we need to calculate the area of the circle using the value of pi.

We then take input from the user for the base and height of the triangle and use these values to calculate the area of the triangle using the formula 0.5 * base * height. We store the result in the triangle_area variable and print it to the console.

Next, we take input from the user for the radius of the circle and use this value to calculate the area of the circle using the formula pi \* radius**2, where ** is the exponent operator. We store the result in the circle_area variable and print it to the console.

The output of this program will depend on the user inputs. For example, if the user enters a base of 4 and a height of 5 for the triangle and a radius of 3 for the circle, the program will output:

vros.py
The area of the triangle is: 10.0
The area of the circle is: 28.274333882308138

22. Write a Python program to check whether a string is palindrome.

vros.py
string = input("Enter a string: ")
 
# Remove all whitespace and convert to lowercase
string = string.replace(" ", "").lower()
 
# Reverse the string
reverse_string = string[::-1]
 
# Check if the original string is equal to the reversed string
if string == reverse_string:
    print("The string is a palindrome!")
else:
    print("The string is not a palindrome.")

In this program, we first take input from the user for a string. We then remove all whitespace and convert the string to lowercase using the replace() and lower() string methods, respectively.

We then use slicing to reverse the string and store the result in the reverse_string variable. Finally, we check if the original string is equal to the reversed string using an if statement. If they are equal, we print a message saying that the string is a palindrome. If they are not equal, we print a message saying that the string is not a palindrome.

The output of this program will depend on the input string. For example, if the user inputs "racecar", the program will output:

vros.py
The string is a palindrome!

23. Write a Python program to print Fibonacci series up to n terms.

vros.py
n = int(input("Enter the number of terms: "))
 
# Initialize the first two terms
a, b = 0, 1
 
# Check if the number of terms is valid
if n <= 0:
    print("Invalid input! Please enter a positive integer.")
elif n == 1:
    print("Fibonacci series up to", n, "term:")
    print(a)
else:
    print("Fibonacci series up to", n, "terms:")
    for i in range(n):
        print(a, end=" ")
        c = a + b
        # Update the values of a and b for the next iteration
        a, b = b, c

In this program, we first take input from the user for the number of terms they want to print in the Fibonacci series. We then initialize the first two terms of the series to be 0 and 1, respectively.

We then check if the number of terms is valid. If it is not a positive integer, we print an error message. If the number of terms is 1, we simply print the first term of the series, which is 0. If the number of terms is greater than 1, we use a for loop to iterate over the range of values from 0 to n-1. Inside the loop, we print the current value of a, which is the current term in the series. We then update the values of a and b for the next iteration by setting a to the value of b and b to the sum of the previous values of a and b.

The output of this program will be a list of Fibonacci numbers up to the specified number of terms. For example, if the user inputs 10, the program will output:

vros.py
Fibonacci series up to 10 terms:
0 1 1 2 3 5 8 13 21 34

25. Write a Python program to find the best of two test average marks out of three test's marks accepted from the user.

Here's a Python program that prompts the user to enter their marks for three tests and then calculates the best of two average marks:

vros.py
# Prompt the user to enter their marks for three tests
test1 = float(input("Enter marks for test 1: "))
test2 = float(input("Enter marks for test 2: "))
test3 = float(input("Enter marks for test 3: "))
 
# Calculate the average marks for each pair of tests
average1 = (test1 + test2) / 2
average2 = (test2 + test3) / 2
average3 = (test1 + test3) / 2
 
# Find the best of the two average marks
best_average = max(average1, average2, average3)
 
# Print the best average mark
print("The best of two average marks is:", best_average)

Here's an example output of the program:

vros.py
Enter marks for test 1: 85
Enter marks for test 2: 78
Enter marks for test 3: 92
The best of two average marks is: 88.5

In this example, the best of two average marks is calculated from the average of tests 1 and 2 (81.5) and the average of tests 2 and 3 (85), which gives a final result of 88.5.