Skip to content

Learn Python By Example 3

Python Solved Questions

Disclaimer : This is a blog post for people learning python. The idea is to show one way of solving a problem and getting away with the task in hand.

21. Define infinity.

inf = float('inf')

22. Given a list of items, return a random item from the list using the random module.

import random

data = ['one', 'two', 'three', 'four']
rv= random.choices(data)
print(f"rv : {rv}")

23. Define a class in Python

class A:
    pass

24. Write code to change the string representation of a class.

class A:
    def __str__(self): 
        return "className : A"

25. Write a function that takes any number of positional arguments.

def f(*args):
    pass

26. Write a function that takes any number of keyword arguments.

def f(**kwargs):
    pass

27. Write a function that takes any number of positional and keyword arguments.

def f(*args, **kwargs):
    pass

28. Write a python function with the type of the arguments.

def f(quantity: int, price: float, items: dict): 
    pass

29. sleep for 3 seconds before executing the function.

from time import sleep

def f():
    print(f'sleeping for 3 seconds')
    sleep(3)
    pass

30. Find the time taken to run a function.

from time import sleep, time
def f():

    before = time()

    sleep(3) # simulating some work

    after = time()

    time_taken = after - before
    print(f"time_taken : {time_taken}")