Learn Python By Example 2
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.
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")