Header Ads Widget

Basic Programs Of Python For Interviews | Top 10 Interview Based Python Programs For Freshers

 

Top 10 Interview Based  Python Programs  For Freshers

1.Python Program  for sum of squares of first n Natural numbers. 

answer : def squares sum (n):
                sm = 0
          for i in range (1,n+1):
           sm = sm + (i*1)
           return sm
   n = 4
   print (squaresum(n))



   output: 30


Top 10 Interview Based  Python Programs  For Freshers

2.Python Program to check Binary palindrome Number. 

answer ;   def  binary palindrome(num):
                  binary = bin(num):
                  binary = binary[2 :]
                  return binary = = binary[-1:1-1]
         if_ _name_ _ = "_ _main_ _"
                  num=g 
                  print binary palindrome(num)



OUT PUT: TRUE



3. Python program for nth fibonacci Number:

Answer: def fibonacci (n):
                 if n<0:
                      raise value error("Input must be non-negative")
                 if n <= 1:
                      return n
                 prev, curr = 0,1
                 for i in range(2, n+1):
                      prev , curr  , prev + curr
                 return curr


#Example usage:
= 6
print (fibonacci(n))

 OUTPUT: 8

               
                      In this code, we define a function called 'fibonacci' that takes an integer  argument 'n'. The function first checks that 'n' is non-negative, and then handles the base cases where 'n' is 0 or 1(returning 'n' itself). For larger values 'n', the function uses recursion to compute the value of the' 'n-th Fibonacci number by adding together the values of the previous two Fibonacci numbers.

To use the function, you can call it with the desired value of 'n' and print the result. In this example, we set 'n' to 6 and print the result, which should be 8 (since the 6th Fibonacci number is 8).
               



4. Python program to find minimum sum of factors.

Answer:   def min_sum_of_factors(n):
    factors = []
    for i in range(1, n+1):
        if n % i == 0:
            factors.append(i)
    min_sum = float('inf')
    for i in range(1, 2**len(factors)):
        subset_sum = 0
        for j in range(len(factors)):
            if (i >> j) & 1:
                subset_sum += factors[j]
        min_sum = min(min_sum, subset_sum)
    return min_sum

# Example usage:
n = 12
print(min_sum_of_factors(n))

  # Output: 7


                       In this code, we define a function called min_sum_of_factors that takes an integer argument n. The function first finds all of the factors of ,n, by iterating through the numbers from 1 up to 'n' and appending the ones that divide n evenly to a list called factors.

Next, the function uses a binary counter to iterate through all possible subsets of the factors. For each subset, it calculates the sum of its elements and keeps track of the minimum sum seen so far.

Finally, the function returns the minimum sum of factors found.

To use the function, you can call it with the desired value of n and print the result. In this example, we set 'n' to 12 and print the result, which should be 7 (since the factors of 12 are 1, 2, 3, 4, 6, and 12, and the minimum sum of factors is achieved by taking the subset {2, 3, 4}).




5. Python program for minimum of two numbers.

Answer: def maximum (a,b):
                if a > = b:
                     return a
                else
                     return b
                a = 2
                b = 4
                print (maximum (a,b))

output: 4



6.Python program for finding Simple Intrest.

Answer: # Input the principal amount, rate of interest, and time period
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of interest: "))
time = float(input("Enter the time period (in years): "))

# Calculate the simple interest
simple_interest = (principal * rate * time) / 100

# Print the result
print("The simple interest for a principal amount of Rs.", principal, "at a rate of", rate, "percent per year for a time period of", time, "years is Rs.", simple_interest).


              
    #Explanation:

1. The program prompts the user to input the principal amount, rate of interest, and time period using the input() function, and stores these values in the variables principal, rate, and time, respectively.

2. The formula for calculating simple interest is (P * R * T) / 100, where P is the principal amount, R is the rate of interest, and T is the time period in years. The program uses this formula to calculate the simple interest and stores the result in the variable simple_interest.

3. The program then uses the print() function to output the result in a formatted string, which includes the input values and the calculated simple interest.

Note that the float() function is used to convert the user input from a string to a floating-point number, which allows the program to handle decimal values as well as integers.



7. Python program to print all prime Numbers in an Interval.

Answer:  # Function to check if a number is prime or not
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

# Input interval from user
start = int(input("Enter the start of the interval: "))
end = int(input("Enter the end of the interval: "))

# Print all the prime numbers within the interval
print("Prime numbers between", start, "and", end, "are:")
for num in range(start, end + 1):
    if is_prime(num):
        print(num)


       Here's how the program works:

1. The is_prime function checks if a number is prime or not. It returns False if the number is less than 2, or if it is divisible by any number between 2 and the square root of the number (inclusive). Otherwise, it returns True.

2. The program prompts the user to enter the start and end of the interval.

3. The program then loops through each number in the interval using the range function.

4. For each number, the program calls the is_prime function to check if it is prime.

5. If the number is prime, the program prints it out.

6. The program repeats steps 4-5 for each number in the interval.

7. Once all the prime numbers in the interval have been printed, the program exits.



8. Python program for finding compound Intrest.

Anwer: # function to calculate compound interest
def compound_intrest(principal, rate, time):
    # formula for calculating compound interest
    amount = principal * (1 + (rate / 100)) ** time
    # calculate the compound interest
    compound_intrest = amount - principal
    # return the compound interest
    return compound_intrest

# get user input for principal, rate, and time
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the intrest rate (in percentage): "))
time = float(input("Enter the time period (in years): "))

# call the compound_intrest function and print the result
result = compound_intrest(principal, rate, time)
print(f"Compound intrest for Principal {principal}, Rate {rate}% and Time {time} years is {result:.2f}")          


                   This program works the same way as the previous one, but it prompts the user for input instead of using hardcoded values. The float function is used to convert the user input from strings to floats so that it can be used in calculations.

Note that when getting user input for the interest rate, you should prompt the user for the rate in percentage form, like "Enter the interest rate (in percentage):", rather than just "Enter the interest rate:", so that the user knows to enter the rate as a percentage.



9. Python program for finding area of  Circle.
 
Answer: # Take radius as input from the user
radius = float(input("Enter the radius of the circle: "))

# Compute the area of the circle using the formula A = pi*r^2
pi = 3.14159
area = pi * (radius ** 2)

# Print the result
print("The area of the circle is:", area)


            In this program, we take the radius of the circle as input from the user using the input function. We then compute the area of the circle using the formula A = pi*r^2, where pi is the mathematical constant pi (approximately 3.14159) and r is the radius of the circle. Finally, we print the result using the print function.



10. Python program for finding sum of odd factor of a Number. 

ANSWER:  # Take input from the user
n = int(input("Enter a number: "))

# Initialize the sum to 0
sum = 0

# Loop through all the factors of the number
for i in range(1, n+1):
    if n % i == 0: # i is a factor of n
        if i % 2 != 0: # i is odd
            sum += i # add i to the sum

# Print the result
print("The sum of the odd factors of", n, "is:", sum)


            In this program, we first take the input number from the user using the input function and convert it to an integer using the int function. We then initialize a variable sum to 0.

Next, we loop through all the factors of the number using a for loop. For each factor i, we check if it is odd by checking if i % 2 != 0. If i is odd, we add it to the sum variable.

Finally, we print the result using the print function.

Note that we use the range function to loop through all the factors of the number. We start the range from 1 and go up to n+1 because we want to include n as a factor.

            

Post a Comment

0 Comments