Practice Python Exercise 3

  • #### Take a list, say for example this one:

    #### a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] and write a program that prints out all the elements of the list that are less than 5.

Extras:

  • Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out this new list.
  • Write this in one line of Python.
  • Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user.

In [8]:
#Main Problem
def main():
    my_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
    
    for i in my_list:
        if i < 5:
           print(i)
if __name__ == '__main__': main()


1
1
2
3

In [9]:
#Extras 1 Problem
def main():
    my_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
    lessthan_five = []
    for i in my_list:
        if i < 5:
           lessthan_five.append(i)
    print(lessthan_five)
    
if __name__ == '__main__': main()


[1, 1, 2, 3]

In [14]:
#Extras 2 Problem
def main():
    
    my_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
    lessthan_five = []
    
    for i in my_list:
        
        if i < 5:
           lessthan_five.append(i)
        
    print("Extras 1 :",lessthan_five)
    
    lessthan_five=[i for i in my_list if i <5]
    
    print("Extras 2 Single line :",lessthan_five)
    
if __name__ == '__main__': main()


Extras 1 : [1, 1, 2, 3]
Extras 2 Single line : [1, 1, 2, 3]

In [22]:
#Extras 3 Problem
def main():
    
    my_list = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
    lessthan_five = []
    
    for i in my_list:
        
        if i < 5:
           lessthan_five.append(i)
        
    print("Extras 1 :",lessthan_five)
    #Extras 2-Starts
    lessthan_five=[i for i in my_list if i <5]
    print("Extras 2 Single line :",lessthan_five)
    
    #Extras 3-Starts
    num = int(input("Enter a number"))
    lessthan_num=[i for i in my_list if i < num]
    print("List contains numbers less than {} : {}".format(num,lessthan_num))
    
    
if __name__ == '__main__': main()


Extras 1 : [1, 1, 2, 3]
Extras 2 Single line : [1, 1, 2, 3]
Enter a number0
List contains numbers less than 0 : []

In [ ]: