Python_Task_Assignment

Python_Task_Assignment

Task 1

We have declared a tuple containing five same elements as following:
T = (‘python’, ‘python’, ‘python’, ‘python’, ‘python’).
Re-write the same code in an optimal/simple way that fetches the same result ?.

# Tuple having names
my_tuple = ('python', ) * 5
print(my_tuple)

 ('python', 'python', 'python', 'python', 'python')

Task 2

Write code to print characters from a string that are present at an even index number. For example, if your input string is "python", the output characters will be (p,t,o).

# read a string
str = input("Enter a string\n")
# create a string with characters at multiples of 2
modified_string = str[::2]
print(modified_string)

pto

Task 3

Write a function that calculates the average of the elements of the list:elements = [5, 7, 4, 9, 2]

elements = [5,7,4,9,2]
# using sum() method
count = sum(elements)

# finding average
avg = count/len(elements)

print('sum = ', count)
print('average = ', avg)

 sum = 27 average = 5.4

Task 4

Write code to find if the given year is a leap year or not.

# Python program to check leap year or not

# If it is not divisible by 4, then it’s confirmed that it is not a leap year. If it is divisible by 4 but not 100 then it is a leap year. If it is divisible by 4, 100, and 400 then it is a leap year.


# Python program to check leap year or not
# If it is not divisible by 4, then it’s confirmed that it is not a leap year. If it is divisible by 4 but not 100 then it is a leap year. If it is divisible by 4, 100, and 400 then it is a leap year.
year = int(input("Enter the year: "))

if (year % 4) == 0:
  if (year % 100) == 0:
    if (year % 400) == 0:
      print(year,"is a leap year")
    else:
      print(year,"is not a leap year")
  else:
    print(year,"is a leap year")
else:
  print(year,"is not a leap year")

2021 is not a leap year

import calendar
year = 2020
if calendar.isleap(year):
  print("Leap Year")
else:
  print("Not a Leap Year")

Leap Year

Task 5

Given a list of numbers (integers), find the sum of second maximum and second minimum in the following list.l = [21, 6, 12, 57, 35, 61]

l = [21, 6, 12, 57, 35, 61]
Largest = find_len(l)
def find_len(l):
    length = len(l)
    l.sort()
    print("Largest element is:", l[length-1])
    print("Smallest element is:", l[0])
    print("Second Largest element is:", l[length-2])
    print("Second Smallest element is:", l[1])

Largest element is: 61 Smallest element is: 6 Second Largest element is: 57 Second Smallest element is: 12





Comments