Python Basics-II


Q.Write python code to find the second largest number 

# function to find the second largest number in a list

def second_largest(numbers):

    # sort the list in descending order

    numbers.sort(reverse=True)

    # return the second element in the sorted list

    return numbers[1]


# test the function with a sample list

numbers = [4, 2, 9, 7, 5, 1]

print("Second largest number:", second_largest(numbers))

In this code, we define a function called second_largest() that takes a list of numbers as an argument. The function first sorts the list in descending order using the sort() method and the reverse parameter set to True. It then returns the second element in the sorted list, which is the second largest number. To test the function, we create a sample list of numbers and pass it to the function, printing the result.


Q.To check a Year is Leap Year or not 

def is_leap_year(year):
    # if year is divisible by 4 it is a leap year
    if year % 4 == 0:
        # if year is divisible by 100 it is not a leap year
        if year % 100 == 0:
            # if year is divisible by 400 it is a leap year
            if year % 400 == 0:
                return True
            else:
                return False
        else:
            return True
    else:
        return False

year = 2000
if is_leap_year(year):
    print(year, "is a leap year")
else:
    print(year, "is not a leap year")

In this code, we define a function called is_leap_year() that takes a year as an argument and returns True if the year is a leap year or False if it is not. The function first checks if the year is divisible by 4, which is a requirement for a leap year. If the year is divisible by 4, it then checks if it is divisible by 100. If it is divisible by 100, it checks if it is divisible by 400. If it is divisible by 400, it returns True, otherwise it returns False. If the year is not divisible by 4, it returns False. To test the function, we pass a year to the function and check the output. If the function returns True the year is a leap year otherwise not.

No comments:

Post a Comment