Python UseCases 2022 – All in One – 50+ Exercises

Python Ready programs 2022

If you want to learn Python through the below real-time scripts, make use of it. Students love these basic beginners python scripts as a comprehensive real-world guide to Python and building programs with Python. 

Who these real-time scripts are for:

  • Students who are starting a python career from the scratch.
  • Students who like to explore Data, AI, ML automation with hands-on.
  • Professionals who are looking to change their career to python.
  • People who are looking to create python related Machine learning, Deep Learning, Data Science automation.
  • Professionals who are new to Python.
  • Professionals who want to gain solid Python Skills.
  • Professionals who want to learn Python by doing Projects, Quizzes, Coding Exercises, Tests, and Exams.
  • Professionals who want to learn Python for Machine Learning, Deep Learning, Data Science, and Software Development.
  • Any professionals who want to learn real Python.

#A: 3
a = 1
a = 2
a = 3
print(a)

a = 1
_a = 2
_a2 = 3
2a = 4

#The script generates an error. Please add the appropriate code that adds variables a and b without an error.
#A: The script generates an error saying that an integer object cannot convert to string implicitly.
#Please try to convert the integer to a string explicitly then or the string to an integer.
a = "1"
b = 2
print(a + b)

a = 1
b = 2
print(a == b)
print(b == c)

#Complete the script so that it prints out the second letter of the list
letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
print(letters[1])

#Complete the script so that it prints out a list containing letters d, e, f.
letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
print(letters[3:6])

#Complete the script so that it prints out a list containing the first three elements of list letters
letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
print(letters[:3])

#Complete the script so that it prints out the letter i using negative indexing
letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
print(letters[-2])

#Complete the script so that it prints out a list containing the last three elements of list letters
letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
print(letters[-3:])

#Complete the script so that it prints out a list containing letters a, c, e, g, and i so the at a step of two
letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
print(letters[::2])

#Create a script that generates a list of numbers from 1 to 20. Do not create a list manually.
my_range = range(1, 21)
print(list(my_range))

#Create a script that generates a list whose items are products of the original list items multiplied by 10
my_range = range(1, 21)
print([10 * x for x in my_range])

#Create a script that converts all items of the range to strings
my_range = range(1, 21)
print(map(str, my_range))
for i in map:
print(i)

#Write a script that remove duplicates from a list
a = ["1", 1, "1", 2]
a = list(set(a))
print(a)

#If you want to keep the order, you need OrderedDict
from collections import OrderedDict
a = ["1", 1, "1", 2]
a = list(OrderedDict.fromkeys(a))
print(a)

#Create a dictionary of two keys, a and b and two values 1 and 2 for keys a and b respectively.
d = {"a": 1, "b": 2}

#Print out the value of key b
d = {"a": 1, "b": 2}
print(d["b"])

#Calculate the sum of value of key a and value of key b and print it out
d = {"a": 1, "b": 2}
print(d["b"] + d["a"])

d = {"Name": "John", "Surname": "Smith"}
print(d["Smith"])

#Add a c key with a value of 3 to the dictionary and print out the updated dictinary
d = {"a": 1, "b": 2}
d["c"] = 3
print(d)

#Find the sum of all values
d = {"a": 1, "b": 2, "c": 3}
print(sum(d.values()))

#Filter out values of equal or greater than 2
#Note that for Python 2 you will have to use iteritems
d = {"a": 1, "b": 2, "c": 3}
d = dict((key, value) for key, value in d.items() if value <= 1)
print(d)

#Create a dictionary of keys a, b, c where each key has as value a list from 1 to 10, 11 to 20, and 21 to 30 respectively and print out

from pprint import pprint

d = dict(a = list(range(1, 11)), b = list(range(11, 21)), c = list(range(21, 31)))
pprint(d)

#Video question so that user sees the pretty print

#Access the third value of key b.
from pprint import pprint
d = dict(a = list(range(1, 11)), b = list(range(11, 21)), c = list(range(21, 31)))

pprint(d['b'][2])

#Complete the script so it prints out the expected output

d = dict(a = list(range(1, 11)), b = list(range(11, 21)), c = list(range(21, 31)))

print(d.items())

for key, value in d.items():
print(key, "has value", value)

#Make a script that prints out letters of English alphabet from a to z
import string

for letter in string.ascii_lowercase:
print(letter)

#Make a script that prints out numbers from 1 to 10

for i in range(1,11):
print(i)

#Write a function that calculates acceleration given the formula:
#a = (v2 - v1) / t2 - t1

def acceleration(v1, v2, t1, t2):
a = float(v2 - v1) / float((t2 - t1))
return a

print(acceleration(0,10,0,20))

#Why is the error and how to fix it?
#A: A TypeError menas you are using the wrong type to make an operation. Change print(a+b) to return a+b

def foo(a, b):
print(a + b)

x = foo(2, 3) * 10

#Write a function that calculates liquid formula taken from http://www.1728.org/spherprt.gif
#When writing the function consider that r is always 10.

from math import pi

def volume(h, r = 10):
v = ((4 * pi * r**3) / 3) - (pi * h**2 * (3*r - h) / 3)
return v

print(volume(2))

#Why do you get an error and how would you fix it?

def foo(a=2, b):
return a + b

print(foo(3, 4))

#Why is the error and how to fix it?

def foo(a=1, b=2):
return a + b

print(type(foo()))

x = foo() - 1

#What will the script output
#A: It will output the last value of c which is 3
c = 1
def foo():
return c
c = 3
print(foo())

#What will the script output?

c = 1
def foo():
c = 2
return c
c = 3
print(foo())

#The script throws an error (when global c is not there). Fix it so that the script prints the value assigned to c inside the function
#A: Add "global c" before "c=1".
#C: Worth mentioning that if you remove foo(), variable c will come as undifined because the function has not been run
def foo():
#global c
c = 1
return c
foo()
print(c)

#Create a function that takes a string and returns the number of words
def count_words(string):
string_list = string.split(" ")
return len(string_list)

print(count_words("Hey there it's me!"))

#Create a function that takes a text file and returns the number of words
def count_words(filepath):
with open(filepath, 'r') as file:
strng = file.read()
strng_list = strng.split(" ")
return len(strng_list)

print(count_words("words1.txt"))

#Create a function like in the previous exercise, but taking into consideration that commas without space can separate words.
def count_words(filepath):
with open(filepath, 'r') as file:
string = file.read()
string = string.replace(",", " ")
string_list = string.split(" ")
return len(string_list)

print(count_words("words2.txt"))

#Other solution using regular expressions
import re

def count_words_re(filepath):
with open(filepath, 'r') as file:
string = file.read()
string_list = re.split(",| ", string)
return len(string_list)

print(count_words_re("words2.txt"))

 

create words2.txt file  with the following text

Wanna loud Come to cloudnloud

#This script is supposed to print out the square root of 9, but there's an error.
#A: THe math module had not been imported yet
math.sqrt(9)

#The script is supposed to print out the cosine of 90
import math
print(math.cosine(1))

#Try to find the cause of the error and give a correct example
#A: pow(2,3)
import math
print(math.pow(2))

#FromScratch - Create a script that generates a file where all letters of English alphabet are listed one in each line
#TO BE USED AS FIRST LECTURE EXAMPLE
#SOLUTION WOULD BE LIKE: Think of the program as a machine that gets some input and produces some output.
#In this case the input would be alphabet letters and the output a file with the alphabet letters. And between we need to use every tool that we can to make that happen.

import string

with open("letters.txt", "w") as file:
for letter in string.ascii_lowercase:
file.write(letter + "\n")

#Print out in each line the sum of homologous items from the two sequences

a = [1, 2, 3]
b = (4, 5, 6)

for i, j in zip(a, b):
print(i + j)

#Create a script that generates a file where all letters of English alphabet are listed two in each line

import string

with open("letters.txt", "w") as file:
for letter1, letter2 in zip(string.ascii_lowercase[0::2], string.ascii_letters[1::2]):
file.write(letter1 + letter2 + "\n")

#FromScratch - Create a script that generates a file where all letters of English alphabet are listed three in each line

import string

letters = string.ascii_lowercase + " "

slice1 = letters[0::3]
slice2 = letters[1::3]
slice3 = letters[2::3]

with open("letters.txt", "w") as file:
for s1, s2, s3 in zip(slice1, slice2, slice3):
print(s1, s2, s3)
file.write(s1 + s2 + s3 + "\n")

import string, itertools

with open("letters_a2.txt", "w") as file:
for letter1, letter2, letter3 in itertools.zip_longest(string.ascii_lowercase[0::3], string.ascii_lowercase[1::3], string.ascii_lowercase[2::3]):
file.write(letter1 + letter2 + letter3 + "\n")

 

letters_a2.txt file 

abc
def
ghi
jkl
mno
pqr
stu
vwx

#Create a script that generates 26 text files, each containing one letter of English alphabet as a name and as text inside.

import string, os

if not os.path.exists("letters"):
os.makedirs("letters")
for letter in string.ascii_lowercase:
with open("letters/" + letter + ".txt", "w") as file:
file.write(letter + "\n")

#Write a script that extracts letters from the 26 text files and put the letters in a list
import glob

letters = []
file_list = glob.glob("letters/*.txt")
print(file_list)
for filename in file_list:
with open(filename, "r") as file:
letters.append(file.read().strip("\n"))

print(letters)

 

26 letter files -- Keep all text files in the same directory.Download the below file.

letters

#Write a script that extracts letters from files if letters are contained in "python" and puts the letters in a list
import glob

letters = []
file_list = glob.iglob("letters/*.txt")
check = "python"

for filename in file_list:
with open(filename,"r") as file:
letter = file.read().strip("\n")
if letter in check:
letters.append(letter)

print(letters)

 

26 letter files -- Keep all text files in the same directory.Download the below file.

letters

1 Comment

Leave a Comment