Skip to main content

Command Palette

Search for a command to run...

Python Programs For Interview

Python programs that are commonly asked in interviews. These programs cover various concepts and problem-solving skills. Remember to understand the lo

Updated
•7 min read•View as Markdown
Python Programs For Interview
  1. Python Program to check for Leap year.

     num = int(input("Enter a year: "))
     if num % 4 == 0:
         if num % 100 == 0:
             if num % 400 == 0:
                 print(f'{num} is not leap year')
             else:
                 print(f'{num} is leap year')
     else:
          print(f'{num} is not leap year')
    

    A leap year is a year that is divisible by 4, except for years that are both divisible by 100 and not divisible by 400.

    The program prompts the user to enter a year, and then it performs the necessary calculations to determine whether it is a leap year or not. The result is then printed accordingly.

    Here's a step-by-step explanation of the code:

    1. User Input: The code prompts the user to enter a year, which is stored in the variable num.

    2. Checking Leap Year Conditions: The code uses nested if statements to check the leap year conditions:

      • First, it checks if the year is divisible by 4 (num % 4 == 0).

      • If it is divisible by 4, it checks the next condition to see if the year is divisible by 100 and not divisible by 400 (num % 100 == 0 and num % 400 != 0).

      • If the year satisfies both conditions, it means it's not a leap year, and it prints "{num} is not a leap year."

      • If the year is divisible by 4 but not divisible by 100, or it's divisible by 100 but also divisible by 400, it means it's a leap year, and it prints "{num} is a leap year."

    3. Output: The program prints whether the entered year is a leap year or not based on the conditions described above.

    The code looks correct and should accurately determine whether a given year is a leap year or not. If the year satisfies the leap year conditions, it will be identified as a leap year, and if not, it will be recognized as a non-leap year.

  2. Python Programs for Fibonacci Series.

def fab_series(n):
    a, b = 1, 1  # Initialize a and b to start the Fibonacci sequence from 1
    for _ in range(n):
        yield a
        a, b = b, a + b

# Testing the generator function
n = 12  # Replace with the number of Fibonacci numbers you want
fib_generator = fab_series(n)

print(f"The first {n} Fibonacci numbers are:")
for num in fib_generator:
    print(num, end=" ")
# OUTPUT
#The first 12 Fibonacci numbers are:
#0 1 1 2 3 5 8 13 21 34 55 89

Here's a step-by-step explanation of the code:

  1. def fab_series(n):: This line defines a Python function called fab_series that takes a single argument n. This function will generate the first n Fibonacci numbers.

    1. a, b = 1, 1: Inside the fab_series function, two variables a and b are initialized to 1. These variables will be used to keep track of the current and next numbers in the Fibonacci sequence. Starting them both at 1 ensures that the Fibonacci sequence starts with 1, 1 (or you can say that it starts from the first two Fibonacci numbers, as per this code).

    2. for _ in range(n):: This line sets up a loop that will run n times, where n is the number of Fibonacci numbers you want to generate. The loop variable _ is not used in the loop, as it's commonly used when you don't need the loop variable itself, only the iteration count.

    3. yield a: This line inside the loop yields the current value of a, which represents the current number in the Fibonacci sequence. It's important to note that the yield keyword turns this function into a generator function, allowing it to yield values one at a time without generating all the Fibonacci numbers at once.

    4. a, b = b, a + b: After yielding the current value a, this line updates the values of a and b to calculate the next Fibonacci number. It does so by swapping the values of a and b and setting a to the sum of the old a and b. This is a common way to generate the Fibonacci sequence, where each number is the sum of the two preceding numbers.

    5. n = 12: This line sets the variable n to 12, indicating that you want to generate the first 12 Fibonacci numbers.

    6. fib_generator = fab_series(n): This line creates a generator object called fib_generator by calling the fab_series function with the argument n. This generator will produce the first 12 Fibonacci numbers when iterated.

    7. Printing the Fibonacci numbers: The code then uses a for loop to iterate through the fib_generator and prints each number, separated by a space. This loop effectively consumes the generator, yielding and printing the first 12 Fibonacci numbers.

    8. Finally, it prints the desired output, which is the first 12 Fibonacci numbers.

def fab(n):
    if n <= 0:
        return "Input should be a positive integer."
    elif n == 1:
        return 0
    elif n == 2:
        return 1
    else:
        return fab(n - 1) + fab(n - 2)

# Testing the function
n = 12
result = fab(n)
print(f"The {n}th Fibonacci number is {result}")
# The 12th Fibonacci number is 89
  1. def fab(n):: This line defines a Python function called fab that calculates the nth Fibonacci number. The function takes one argument, n, which represents the position of the Fibonacci number to be calculated.

  2. if n <= 0:: This is a conditional statement that checks if n is less than or equal to 0. If n is non-positive (less than or equal to 0), the function returns a string indicating that the input should be a positive integer. This serves as a check to ensure that the input is valid.

  3. elif n == 1:: If n is equal to 1, this branch of the conditional statement returns 0. This is because, by convention, the first Fibonacci number is often considered to be 0.

  4. elif n == 2:: If n is equal to 2, this branch returns 1. This is because the second Fibonacci number is typically considered to be 1.

  5. else:: If n is greater than 2, this part of the conditional statement calculates the nth Fibonacci number. It uses a recursive approach to calculate the nth Fibonacci number by summing the (n-1)th and (n-2)th Fibonacci numbers. This recursive approach continues until n becomes 1 or 2, at which point the base cases are reached, and the function returns 0 or 1, respectively.

  6. n = 12: This line sets the variable n to 12, indicating that you want to calculate the 12th Fibonacci number.

  7. result = fab(n): This line calls the fab function with the argument n and stores the result in the result variable. It calculates the 12th Fibonacci number using the recursive function.

  8. print(f"The {n}th Fibonacci number is {result}"): Finally, this line prints the calculated result, indicating that it's the 12th Fibonacci number.

  1. Python Programs to check Perfect Number.

     number = int(input("Enter a number:"))
     sum = 0
     print(f'divisor  of {number} is :',end="" )
     for i in range(1,number):
         if number % i == 0:
             print(i, end= ",")
             sum += i
     print("\n")
     if sum == number:
         print(f'{number} is perfect number')
     else:
         print(f'{number} is not perfect number')
    

    Here's a step-by-step explanation of the code:

    1. User Input: The code prompts the user to enter a number, which is stored in the variable number.

    2. Finding Divisors: The code uses a for loop to iterate from 1 to number - 1. In each iteration, it checks if the current value of i is a divisor of number (number % i == 0). If i is a divisor, it is a proper divisor, and the code prints it as one of the divisors of the input number.

    3. Calculating Sum of Divisors: While finding the divisors, the code also calculates the sum of all the proper divisors and stores it in the variable sum.

    4. Checking for Perfect Number: After finding all the divisors and computing their sum, the code compares the sum with the input number. If the sum is equal to the input number, it means the input number is a perfect number. Otherwise, it's not a perfect number.

    5. Output: The program prints the divisors of the input number and then determines whether the number is a perfect number or not based on the sum of its divisors.

    The code appears to be correct, and it should accurately determine whether a given number is a perfect number or not. If the number satisfies the condition of a perfect number (sum of divisors equals the number itself), it will be recognized as a perfect number. Otherwise, it will be identified as not a perfect number.

H

Thank you for sharing these Python programs that cover various concepts and problem-solving skills.