Python Ready Programme – Basics 2022 – All in One – 60+ 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.

#The script is trying to print out the type of the last character of updated string.
#A: One more bracket is needed to close the print function
print(type("Hey".replace("ey","i")[-1])

#Please fix the script so that it returns the user submited first name for the first %s
#and the second name for the second %s

firstname = input("Enter first name: ")
secondname = input("Enter second name: ")
print("Your first name is %s and your second name is %s" % firstname, secondname)

#Print out the last name of the second employee
d = {"employees":[{"firstName": "John", "lastName": "Doe"},
{"firstName": "Anna", "lastName": "Smith"},
{"firstName": "Peter", "lastName": "Jones"}],
"owners":[{"firstName": "Jack", "lastName": "Petter"},
{"firstName": "Jessy", "lastName": "Petter"}]}

print(d['employees'][1]['lastName'])

from pprint import pprint

d = {"employees":[{"firstName": "John", "lastName": "Doe"},
{"firstName": "Anna", "lastName": "Smith"},
{"firstName": "Peter", "lastName": "Jones"}],
"owners":[{"firstName": "Jack", "lastName": "Petter"},
{"firstName": "Jessy", "lastName": "Petter"}]}

d['employees'][1]['lastName'] = "Smooth"

pprint(d)

from pprint import pprint

d = {"employees":[{"firstName": "John", "lastName": "Doe"},
{"firstName": "Anna", "lastName": "Smith"},
{"firstName": "Peter", "lastName": "Jones"}],
"owners":[{"firstName": "Jack", "lastName": "Petter"},
{"firstName": "Jessy", "lastName": "Petter"}]}

d["employees"].append(dict(firstName = "Albert", lastName = "Bert"))

pprint(d)

#Store the dict to a json file

import json

d = {"employees":[{"firstName": "John", "lastName": "Doe"},
{"firstName": "Anna", "lastName": "Smith"},
{"firstName": "Peter", "lastName": "Jones"}],
"owners":[{"firstName": "Jack", "lastName": "Petter"},
{"firstName": "Jessy", "lastName": "Petter"}]}

with open("company1.json", "w") as file:
json.dump(d, file, indent=4, sort_keys=True)

#Get the file in the attachment and produce the printed output
import json
from pprint import pprint

with open("company1.json","r") as file:
d = json.load(file)

#d = json.load("company1.json")

pprint(d)

import json

with open("company1.json", "r+") as file:
d = json.loads(file.read())
d["employees"].append(dict(firstName = "Albert", lastName = "Bert"))
file.seek(0)
json.dump(d, file, indent=4, sort_keys=True)
file.truncate()

#Print out three lines saying for instance item 1 has index 0, and so on.
a = [1, 2, 3]

for index, item in enumerate(a):
print("Item %s has index %s" % (item, index))

#Create a program that prints Hello every 2 seconds
import time

while True:
print("Hello")
time.sleep(2)

#Create a program that prints Hello repeteadly after 1 second first, then after 2, 3, 4 increasing the interval by one
import time

i = 0
while True:
print("Hello")
i = i + 1
time.sleep(i)

#Create a program that once executed the programs prints Hello instantly first, then it prints it after 1 second, then after 2, 3, and then the program prints out the message "End of the Loop" and stops.
import time

i = 0
while True:
print("Hello")
i = i + 1
if i > 3:
print("End of loop")
break
time.sleep(i)

#The following code prints Hello, checks if 2 is greater than 1 and then breaks the loop because 2 is actually greater than 1. THerefore Hi is not printed out. Please replace break with something else so that Hello and Hi are printed out repeatedly.


while True:
print("Hello")
if 2 > 1:
break
print("Hi")

#The following code prints Hello, checks if 2 is greater than 1 and then breaks the loop because 2 is actually greater than 1. Therefore Hi is not printed out. Please replace break with something else so that Hello is printed out repeatedly and Hi is never printed.


while True:
print("Hello")
if 2 > 1:
continue
print("Hi")

#Create a function that takes a word from user and translates it using a dictionary of three words
d = dict(weather = "clima", earth = "terra", rain = "chuva")
def vocabulary(word):
return d[word]

word = input("Enter word: ")
print(vocabulary(word))

#Like the previous exercise, but returning a message when the word is not in the dict.
d = dict(weather = "clima", earth = "terra", rain = "chuva")
def vocabulary(word):
try:
return d[word]
except KeyError:
return "That word does not exist."

word = input("Enter word: ")
print(vocabulary(word))

#Like the previous exercise, but considering user may enter different letter cases
d = dict(weather = "clima", earth = "terra", rain = "chuva")
def vocabulary(word):
try:
return d[word]
except KeyError:
return "That word does not exist."

word = input("Enter word: ").lower()
print(vocabulary(word))

#Name the file datetime.py and fix the error
import requests
print(__name__)

r = requests.get("http://www.pythonhow.com")
print(r.text[:100])

print(__name__)

#Print out the text of this file www.pythonhow.com/data/universe.txt. Please don't manually download the file. Let Python do all the work.
import requests

response = requests.get("http://www.pythonhow.com/data/universe.txt")
text = response.text
print(text)

#Count how many a the text file has
import requests

response = requests.get("http://www.pythonhow.com/data/universe.txt")
text = response.text
count_a = text.count("a")
print(count_a)

#Create a script that let the user type in a search term and opens and search on the browser for that term on Google

import webbrowser

query = input("Enter your Google query: ")
url = "https://www.google.com/?gws_rd=cr,ssl&ei=NCZFWIOJN8yMsgHCyLV4&fg=1#q=%s" % str(query)
webbrowser.open_new(url)

#Python 2.x:
#print 'string' * (number of iterations)
print '-' * 3


#Python 3.x:
#print ('string' * (number of iterations))
print('-' * 3)

#Concatenate the two txt files into one file
import pandas

data1 = pandas.read_csv("http://www.pythonhow.com/data/sampledata.txt")
data2 = pandas.read_csv("sampledata_x_2.txt")
data12 = pandas.concat([data1, data2])
data12.to_csv("sampledata12.txt", index=None)

print(data12)

#Plot the data in the file provided through the URL http://www.pythonhow.com/data/sampledata.txt
import pandas
import pylab as plt

data = pandas.read_csv("http://www.pythonhow.com/data/sampledata.txt")
data.plot(x='x', y='y', kind='scatter')
plt.show()

"""

from bokeh.plotting import figure
from bokeh.io import output_file, show
import pandas

output_file("bokeh_plot.html")
data = pandas.read_csv("http://www.pythonhow.com/data/sampledata.txt")
f = figure()
f.circle(x=data["x"], y=data["y"])

show(f)
"""

# Please print the script in the expected output

from datetime import datetime

print(datetime.now().strftime("Today is %A, %B %d, %Y"))

#When writing web apps, you may need to generate default random passwords for users.
#Create a program that generates a password of 6 random alphanumeric characters in the range abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?

import random

characters = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"
chosen = random.sample(characters, 6)
password = "".join(chosen)
print(password)


#Video question -Easy

#Create a script that lets the user submit a password until they have satisfied three conditions:
#1. Password contains at least one number
#2. Contains one uppercase letter
#3. It is at least 5 chars long
#Print out message "Passowrd is not fine" if the user didn't create a correct password

while True:
psw = input("Enter new password: ")
if any(i.isdigit() for i in psw) and any(i.isupper() for i in psw) and len(psw) >= 5:
print("Password is fine")
break
else:
print("Passowrd is not fine")

#Create a script that lets the user create a password until they have satisfied three conditions:
#Password contains at least one number, one uppercase letter and it is at least 5 chars long
#Give the exact reason why the user has not created a correct password
while True:
notes = []
psw = input("Enter password: ")
if not any(i.isdigit() for i in psw):
notes.append("You need at least one number")
if not any(i.isupper() for i in psw):
notes.append("You need at least one uppercase letter")
if len(psw) < 5:
notes.append("You need at least 5 characters")
if len(notes) == 0:
print("Password is fine")
break
else:
print("Please check the following: ")
for note in notes:
print(note)

#Video question -Experienced
#Video solution -Experienced

while True:
usr = input("Enter username: ")
with open("users.txt", "r") as file:
users = file.readlines()
users = [i.strip("\n") for i in users]
if usr in users:
print("Username exists")
continue
else:
print("Username is fine")
break

while True:
notes = []
psw = input("Enter password: ")
if not any(i.isdigit() for i in psw):
notes.append("You need at least one number")
if not any(i.isupper() for i in psw):
notes.append("You need at least one uppercase letter")
if len(psw) < 5:
notes.append("You need at least 5 characters")
if len(notes) == 0:
print("Password is fine")
break
else:
print("Please check the following: ")
for note in notes:
print(note)

#Use Python to calculate the distance (in AU units) between Jupiter and Sun on January 1, 1230.
#A: I didn't know this so I did some internet research and reveal that ephem is used for astronomical clculations.
#The ephem library was installed with pip, and for Windows a precompiled library from http://www.lfd.uci.edu/~gohlke/pythonlibs/#pyephem was installed with pip
#Try to find your own version from that page

import ephem
jupiter = ephem.Jupiter()
jupiter.compute('1230/1/1')
distance_au_units = jupiter.sun_distance
distance_km = distance_au_units * 149597870.691
print(distance_km)

#Write a script that detects and prints out your monitor resolution
from screeninfo import get_monitors
print(get_monitors())

width=get_monitors()[0].width
height=get_monitors()[0].height

print("Width: %s, Height: %s" % (width, height))

import pyglet
window = pyglet.window.Window()
label = pyglet.text.Label('Hello, world',
font_name='Times New Roman',
font_size=36,
x=window.width//2, y=window.height//2,
anchor_x='center', anchor_y='center')

@window.event
def on_draw():
window.clear()
label.draw()

pyglet.app.run()

with open("countries_raw.txt", "r") as file:
content = file.readlines()

content = [i.strip("\n") for i in content if "\n" in i]

content = [i for i in content if i !=""]
content = [i for i in content if i !="Top of Page"]

content = [i for i in content if len(i) != 1]
print(content)

with open("countries_clean.txt", "w") as file:
for i in content:
file.write(i+"\n")

Keep the below files in the same directory then execute the above script

countries_raw

countries_clean

#Create a script that checks a list against countries_clean.txt
#and creates a list with items that were in that file

checklist = ["Portugal", "Germany", "Munster", "Spain"]

with open("countries_clean.txt", "r") as file:
content = file.readlines()

content = [i.rstrip('\n') for i in content]
checked = [i for i in content if i in checklist]

print(checked)

 

Keep the below files in the same directory then execute the above script

countries_clean

#Add the missing items to the file

checklist = ["Portugal", "Germany", "Spain"]
checklist = [i + "\n" for i in checklist]

with open("countries_missing.txt", "r") as file:
content = file.readlines()
print(checklist + content)

updated_list = sorted(checklist + content)

with open("countries_missing_fixed.txt", "w") as file:
for i in updated_list:
file.write(i)

 

Keep the below files in the same directory then execute the above script

countries_missing

countries_missing countries_missing_fixed

#Create a script that uses countries_by_area.txt file as data sourcea and prints out the top 5 most densely populated countries

import pandas

data = pandas.read_csv("countries_by_area.txt")
data["density"] = data["population_2013"] / data["area_sqkm"]
data = data.sort_values(by="density", ascending=False)

for index, row in data[:5].iterrows():
print(row["country"])

Keep the below files in the same directory then execute the above script

countries_by_area

#Please download the database file database.db. The file contains a table with 50 country names along with their area in square km and population.
#Please use Python to print out those countries that have an area of greater than 2,000,000.
import sqlite3

conn = sqlite3.connect("database.db")
cur = conn.cursor()
cur.execute("SELECT country FROM countries WHERE area >= 2000000")
rows = cur.fetchall()
conn.close()
print(rows)

for i in rows:
print(i[0])

#Please download the database file database.db and use Python to access the database table rows that have an area of 2,000,000 or greater. Then export those rows to a CSV file
import sqlite3
import pandas

conn = sqlite3.connect("database.db")
cur = conn.cursor()
cur.execute("SELECT * FROM countries WHERE area >= 2000000")
rows = cur.fetchall()
conn.close()

print(rows)

df = pandas.DataFrame.from_records(rows)
df.columns =["Rank", "Country", "Area", "Population"]
print(df)
df.to_csv("countries_big_area.csv", index=False)

 

Download and unzip the below file before executing the above python script

database.db

#Please download the database file database.db and and the ten_more_countries.txt file. Then, add the rows of the text file to the database file.
import sqlite3
import pandas

data = pandas.read_csv("ten_more_countries.txt")

conn = sqlite3.connect("database.db")
cur = conn.cursor()
for index, row in data.iterrows():
print(row["Country"], row["Area"])
cur.execute("INSERT INTO countries VALUES (NULL,?,?,NULL)",(row["Country"], row["Area"]))
conn.commit()
conn.close()

 

 

Download and keep the below files in the same directory before execute the above python script

ten_more_countries

database

#Count files with a .py extension inside the root1 directory]
import glob
file_list=glob.glob1("files","*.py")
print(len(file_list))

#Count files with a .py extension in root1 directory and its subdirectories
#This solution works for the previous exercise as well with one file in a directory
import glob

file_list = glob.glob("subdirs/**/*.py", recursive=True)
print(len(file_list))

#Clean each line by removing s from https and adding a slash

with open("urls.txt", "r") as file:
lines = file.readlines()

print(lines)

with open("urls_corrected.txt", "w") as file:
for line in lines:
line_remove_s = line.replace("s", "", 1)
print(line_remove_s)
line_remove_s_add_slash = line_remove_s[:6] + "/" + line_remove_s[6:]
print(line_remove_s_add_slash)
file.write(line_remove_s_add_slash)

#Create a program that asks the user to input values separated by commas and those values will be stored in a separate line each in a text file

line = input("Enter values: ")

line_list = line.split(",")

with open("user_data_commas.txt", "a+") as file:
for i in line_list:
file.write(i + "\n")

Download the below file before execute the above python script

user_data_commas

#Create a program that asks the user to submit text repeatedly
#The program closes when the user submits CLOSE

file = open("user_data.txt", 'a+')

while True:
line = input("Write a value: ")
if line == "CLOSE":
file.close()
break
else:
file.write(line + "\n")

 

Download the below file before execute the above python script

user_data

#Create a program that asks the user to submit text through a GUI

file = open("user_data_save_close.txt", 'a+')

while True:
line = input("Write a value: ")
if line == "SAVE":
file.close()
file = open("user_data_save_close.txt", 'a+')
elif line == "CLOSE":
file.close()
break
else:
file.write(line + "\n")

Download the below file before execute the above python script

user_data_save_close

#Create a program that asks the user to submit text through a GUI

from tkinter import *

window = Tk()

file = open("user_gui.txt", "a+")

def add():
file.write(user_value.get() + "\n")
entry.delete(0, END)

def save():
global file
file.close()
file = open("user_gui.txt", "a+")

def close():
file.close
window.destroy()

user_value = StringVar()
entry = Entry(window, textvariable=user_value)
entry.grid(row=0, column=0)

button_add = Button(window, text="Add line", command=add)
button_add.grid(row=0, column=1)

button_save = Button(window, text="Save changes", command=save)
button_save.grid(row=0, column=2)

button_close = Button(window, text="Save and Close", command=close)
button_close.grid(row=0,column=3)

window.mainloop()

 

Download the below file before execute the above python script

user_gui

#Create a program that asks the user to submit text a web app
from flask import Flask, render_template_string, request
app = Flask(__name__)
html = """
<div class="form">
<form action="{{url_for('sent')}}" method="POST">
<input title="Your email address will be safe with us." placeholder="Enter a line" type="text" name="line" required> <br>
<button class="go-button" type="submit"> Submit </button>
</form>
</div>
"""
@app.route("/")
def index():
return render_template_string(html)
@app.route("/sent", methods=['GET', 'POST'])
def sent():
line = None
if request.method == 'POST':
line = request.form['line']
with open("user_input_flask.txt", "a+") as file:
file.write(line + "\n")
return render_template_string(html)
if __name__ == "__main__":
app.run(debug=True)

 

Download the below file before execute the above python script

user_input_flask

#Please create a web app that let's users submit a username and password
#The app checks if the username exists and the password satisfies three conditions as in exercise 81
from flask import Flask, render_template_string, request

app = Flask(__name__)

html = """
<div class="form">
<form action="{{url_for('sent')}}" method="POST">
<input title="Your email address will be safe with us." placeholder="Enter username" type="text" name="username" required> <br>
<input title="Your email address will be safe with us." placeholder="Enter password" type="text" name="password" required> <br>
{{message|safe}}
<button class="go-button" type="submit"> Submit </button>
</form>
</div>
"""

@app.route("/")
def index():
return render_template_string(html)

@app.route("/sent", methods=['GET', 'POST'])
def sent():
line = None
if request.method == 'POST':
while True:
usr = request.form['username']
with open("users.txt", "r") as file:
users = file.readlines()
users = [i.strip("\n") for i in users]
if usr in users:
return render_template_string(html, message="Username exists!"+"<br>")
continue
else:
print("Username is fine!")
break
while True:
notes = []
psw = request.form['password']
if not any(i.isdigit() for i in psw):
notes.append("You need at least one number")
if not any(i.isupper() for i in psw):
notes.append("You need at least one uppercase letter")
if len(psw) < 5:
notes.append("You need at least 5 characters")
if len(notes) == 0:
print("Password is fine"+"<br>")
break
else:
return render_template_string(html, message="Please check password!")
return render_template_string(html, message="Success"+"<br>")
if __name__ == "__main__":
app.run(debug=True)

 

Download the below file before execute the above python script

users

Leave a Comment