Learn Python By Example
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.
1. Printing 'hello world' to a variable.
name = input("Enter your name : ")
3. Print the entered name by the user to the terminal with the text before it : hello name entered by user'
4. Import the library json
5. Declare a string with an initial value 'hi'
6. Declare an empty string in python.
name = str() # using contructor
name = ""
num = input("Enter a number: ")
num = int(num)
OR
num = int(input("Enter a number: "))
8. Declare a list of numbers.
9. Declare a list of numbers from 0-9.
my_list = [item for item in range(10)]
name = input("Enter your name : ")
print(f"Number of characters : {len(name)}")
11. Initialize a dict with random user data.
user_data = {
"name": "henry",
"age": 30,
"employeed": True
}
12. Unpack the tuple into x and y co-ordinates and print it.
pt = (1.2, 3.6)
x, y = pt
print(f"x : {x}")
print(f"y : {y}")
13. Given a tuple of x, y, z co-ordinates, unpack the x co-ordinate and the rest in another tuple and print the x co-ordinate.
pt = (1,2,3)
x, *other = pt
print(f"x : {x}")
14. Generate a random number between 0 and 1000 using the random module and print it to the console.
import random
num = random.randint(0, 1000)
print(f"num : {num}")
15. Given a python dict, convert it to a json object using the json library.
import json
data = {"name": "dan", "age": 33}
json_data = json.dumps(data)
16. Reverse a python list.
scores = [3,5,2,3,6,1]
rev_scores = scores[::-1]
17. define a python function.
18. Given a string, split it on every occurence of ,
line = 'here is a comma, here is another comma,'
rv = [item for item in line.split(",") if item]
19. Check if a string ends with txt
file_name = "data.csv"
rv = file_name.endswith("txt")
print(f"rv : {rv}")
20. Given a float value ( num = 1.022 ), print it with accuracy of 2 decimal points.
num = 1.022
rv = format(num, "0.2f")
21. Define infinity.
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
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.
26. Write a function that takes any number of keyword arguments.
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}")