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.
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