0% found this document useful (0 votes)
27 views147 pages

50 Days of Python

The document is a guide titled '50 Days of Python' by Benjamin Bennett Alexander, designed to help users master Python through daily challenges. It includes a variety of programming tasks that cover fundamental concepts, encouraging problem-solving and critical thinking. The book features over 80 challenges, structured to be completed over 50 days, with extra challenges for deeper learning.

Uploaded by

prithvirajpati64
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views147 pages

50 Days of Python

The document is a guide titled '50 Days of Python' by Benjamin Bennett Alexander, designed to help users master Python through daily challenges. It includes a variety of programming tasks that cover fundamental concepts, encouraging problem-solving and critical thinking. The book features over 80 challenges, structured to be completed over 50 days, with extra challenges for deeper learning.

Uploaded by

prithvirajpati64
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

50 DAYS OF

PYTHON
A challenge a Day
Benjamin Bennett Alexander

"Python" and the Python Logoare trademarks of the Python Software Foundation.

1| Page
Copyright © 2022 by Benjamin Bennett Alexander
All rights are reserved. No part of this publication may be
reproduced, stored in a retrieval system, or transmitted in any form
or by any means, electronic, mechanical, photocopying, recording, or
otherwise, without the prior permission of the publisher.
Every effort has been made in the preparation of this book to ensure
the accuracy of the information presented. However, we do not
warrant or represent its completeness or accuracy.

2| Page
Feedback and Reviews
Iwelcomeandappreciate your feedback and reviews. Please
consider writing a review on the platform you purchased this book
from. Please send your queries to:
benjaminbennettalexander@[Link].

3|Page
Table of Contents
FeedbackandReviews ................................................................ 3
Table of Contents ........................................................................... 4
Introduction .................................................................................... 8
Day 1: Division and Square-root ........................................... 10
Extra Challenge: Longest Value .................................................. 10
Day 2: Strings to Integers ......................................................... 11
Extra Challenge: Duplicate Names............................................. 11
Day 3: Register Check ................................................................ 12
Extra Challenge: Lowercase Names ........................................... 12
Day 4: Only Floats ....................................................................... 13
Extra Challenge: Index of the Longest Word ............................ 13
Day 5: My Discount ..................................................................... 14
Extra Challenge: Tuple of Student Sex ...................................... 14
Day 6: User Name Generator ................................................. 15
Extra Challenge: Zero Both Ends ............................................... 15
Day 7: A String Range ................................................................ 16
Extra Challenge: Dictionary of Names ....................................... 16
Day 8: Odd and Even .................................................................. 17
Extra Challenge: List of Prime Numbers ................................... 17
Day 9: Biggest Odd Number .................................................... 18
Extra Challenge: Zeros to the End .............................................. 18
Day 10: Hide my Password ...................................................... 19

4| Page
Extra Challenge: A Thousand Separator .................................. 19
Day 11: Are They Equal? ............................................................ 20
Extra Challenge: Swap Values ..................................................... 20
Day 12: Count the Dots .............................................................. 21
Extra Challenge: Your Age in Minutes ....................................... 21
Day 13: Pay Your Tax.................................................................. 22
Extra Challenge: Pyramid of Snakes .......................................... 22
Day 14: Flatten the List .............................................................. 23
Extra Challenge: Teacher’s Salary .............................................. 23
Day 15: Same in Reverse ........................................................... 24
Extra Challenge: What’s My Age? .............................................. 24
Day 16: Sum the List ................................................................... 25
Extra Challenge: Unpack A Nest ................................................. 25
Day 17: User Name Generator ................................................ 26
Extra Challenge: Sort by Length ................................................. 26
Day 18: Any Number of Arguments ..................................... 27
Extra Challenge: Add and Reverse ............................................. 27
Day 19: Words and Elements .................................................. 28
Day 20: Capitalize First Letter ............................................... 29
Extra Challenge: Reversed List ................................................... 29
Day 21: List of Tuples ................................................................. 30
Extra Challenge: Even Number or Average .............................. 30
Day 22: Add Under_Score ....................................................... 31
Day 23: Simple Calculator ....................................................... 32
Extra Challenge: Multiply Words ............................................... 32
5| Page
Day 24: Average Calories ......................................................... 33
Extra Challenge: Create a Nested List ....................................... 33
Day 25: All the Same................................................................... 34
Extra Challenge: Reverse a String .............................................. 34
Day 26: Sort Words .................................................................... 35
Extra Challenge: Length of Words ............................................. 35
Day 27: Unique Numbers ......................................................... 36
Extra Challenge: Difference of Two Lists .................................. 36
Day 28: Return Indexes ............................................................ 37
Extra Challenge: Largest Number .............................................. 37
Day 29: Middle Figure ............................................................... 38
Day 30: Most Repeated Name ................................................ 39
Extra Challenge: Sort by Last Name .......................................... 39
Day 31: Longest Word ................................................................ 40
Extra Challenge: Create User ...................................................... 40
Day 32: Password Validator .................................................... 41
Extra Challenge: Valid Email ...................................................... 41
Day 33: List Intersection .......................................................... 42
Extra Challenge: Set or List ......................................................... 42
Day 34: Just Digits ...................................................................... 43
Day 35: Pangram.......................................................................... 44
Day 36: Count String .................................................................. 45
Extra Challenge: Sum a Nested Dictionary ............................... 45
Day 37: Count the Vowels ......................................................... 46
Day 38: Guess a Number .......................................................... 47
6| Page
Extra Challenge: Find Missing Numbers .................................. 47
Day 39: Password Generator .................................................. 48
Day 40: Pig Latin ......................................................................... 49
Day 41: Only Words with Vowels .......................................... 50
Extra Challenge: Class of Cars .................................................... 50
Day 42: Spelling Checker ......................................................... 51
Extra Challenge: Set Alarm ......................................................... 51
Day 43: Student Marks .............................................................. 52
Day 44: Save Emails ................................................................... 53
Day 45: Words & Special Characters ................................... 54
Day 46: Create a DataFrame ................................................... 55
Extra Challenge: Website Data with Pandas ............................. 55
Day 47: Save a JSON ................................................................... 57
Day 48: Binary Search ............................................................... 58
Day 49: Create a Database ....................................................... 59
Day 50: Create a Flask App ...................................................... 60
Answers to the Challenges ....................................................... 62
Other Books by Author ........................................................... 145

7| Page
Introduction
Welcome to the world of Python challenges! Just like in life,
challenges are the building blocks of a strong character. They push
us to grow, learn, and become better. This book is designed to
provide you with an exciting opportunity to master the key concepts
and fundamentals of Python through solving a series of captivating
challenges. With over 80 challenges waiting for you, embark on this
50-day journey to become a Python expert.
Why Solve challenges?
As a programmer, your ultimate goal is to solve problems efficiently.
By tackling challenges, you not only solidify your knowledge but also
develop the invaluable skill of problem- solving. Each challenge will
train your mind to think critically and find innovative solutions to
real-life programming scenarios.
How to Use this Book?
To make the most of thisbook, embrace the challenge and resist the
temptation to immediately seek the answers. Take your time and
dedicate a day to solveeach problem. Some challenges may seem
easy, while others willpush your limits. Remember, there can be
multiple solutions to aproblem, and your unique approach is just as
valid as the one presented in the book.
Throughout this book,you will encounter a wide range of Python
fundamentals. Fromcreating password generators to working with
modules, translatingstrings, manipulating dictionaries, handling
CSV and JSON files,and even building a website - you'll be
immersed in a diversesetof tasks. Get ready to dive in and embark
on an exhilarating learning journey.

8| Page
Conclusion
With the promise of over 80 engaging challenges covering various
Python concepts, this book is your gateway to mastering the
fundamentals. Take one step at a time, challenge by challenge, and
watch your Python skills flourish. Remember, it's not about how
quickly you finish, but the knowledge and experience you gain
along the way. So, without further ado, let the adventure begin!

9| Page
Day 1: and Square-root
Division
Writea function called divide_or_square that takes one
argument (a number) and returns the square root of the number if
it is divisible by 5, or its remainder if it is not divisible by 5. For
example, if you pass 10 as an argument, then your function should
return 3.16 as the square root.
Extra Challenge: Longest Value
Write a function called longest_value that takes a dictionary as
an argument and returns the first longest value of the dictionary.
For example, the following dictionary should return "apple" as the
longest value.
fruits = {'fruit': 'apple', 'color': 'green'}

10 | Page
Day 2: Strings to Integers
Write afunction called convert_add that takes a list of strings
as an argument, converts them to integers, and sums the list. For
example, ["1", "3", "5"] should be converted to [1, 3, 5] and
summed to 9.

Extra Challenge: Duplicate Names


Write a function called check_duplicates that takes a list of
strings as an argument. The function should check if the list has
any duplicates. If there are duplicates, the function should
return a list of duplicates. If there are no duplicates, the
function should return "no duplicates." For example, the list of
fruits below should return ["apple", "banana"], and the list
of names should return "no duplicates."
fruits = ['apple', 'orange', 'banana', 'apple', 'banana'] names =
['Yoda', 'Moses', 'Joshua', 'Mark']

11 | Page
Day 3: Register Check
Writea function called register_check that checks how many
students are in school. The function takes a dictionary as an
argument. If the student is in school, the dictionary says "yes." If the
student is not in school, the dictionary says "no." Your function
should return the number of students in school. Using the dictionary
below, your function should return 3.

Extra Challenge: Lowercase Names


names = ["kerry", "dickson", "John", "Mary",

"carol", "Rose", "adam"]

You are given a list of names above. This list is made up of names
win lowercase and uppercase letters. Your task is to write a code
that will return a tuple of all the names in the list that only have
lowercase letters. Your tuple should have names sorted
alphabetically in descending order. Using the list above, your code
should return:
('kerry', 'dickson', 'carol', 'adam')

12 | Page
Day 4: Only Floats
Write a function called only_floats, which has two parameters, a
and b, and returns 2 if both arguments are floats, 1 if only one
argument is a float, and 0 if neither argument is a float. If you
pass (12.1, 23) as an argument, your function should return 1.

Extra Challenge: Index of the Longest Word


Write a function called word_index that takes one argument, a
list of strings, and returns the index of the longest word in the list.
If there is no longest word (if all the strings are of the same length),
the function should return zero (0). For example, the first list below
should return 2.

words1 = ["Hate", "remorse", "vengeance"]


And this list below, should return zero (0)
words2 = ["Love", "Hate"]

13 | Page
Day 5: My Discount
Createafunction called my_discount. The function takes no
arguments but asks the user to input the price and the discount
(percentage) of the product. Once the user inputs the price and
discount, it calculates the price after the discount. The function
should return the price after the discount. For example, if the user
enters 150 as the price and 15% as the discount, your function
should return 127.5.
Extra Challenge: Tuple of Student Sex

You work for a school, and your boss wants to know how many
female and male students are enrolled in the school. The school has
saved the students on a list. Your task is to write a code that will
count how many males and females are in the list. Here is a list
below:

students = ['Male', 'Female', 'female', 'male', 'male', 'male',


'female', 'male', 'Female', 'Male', 'Female', 'Male',
'female']

Your code should return a list of tuples. The list above should
return: [("Male", 7), ("female", 6)]

14 | Page
Day 6: User Name Generator
Writea function called user_name that generates a username
from the user’s email. The code should ask the user to input an
email, and the code should return everything before the @ sign
as their user name. For example, if someone enters
ben@[Link], the code should return ben as their user
name.

Extra Challenge: Zero Both Ends


Write a function called zeroed code that takes a list of
numbers as an argument. The code should zero (0) the first
and last number in the list. For example, if the input is [2, 5,
7, 8, 9], your code should return [0, 5, 7, 8, 0].

15 | Page
Day 7: A String Range
Write afunction called string_range that takes a single number
and returns a string of its range. The string characters should be
separated by dots(.). For example, if you pass 6 as an argument,
your function should return "[Link].4.5."

Extra Challenge: Dictionary of Names


You are given a list of names, and you are asked to write a code that
returns all the names that start with "S." Your code should return
a dictionary of all the names that start with S and how many times
they appear in the dictionary. Here is a list below:
names = ["Joseph", "Nathan", "Sasha", "Kelly",

"Muhammad", "Jabulani", "Sera", "Patel", "Sera"]

Your code should return: {"Sasha": 1, "Sera": 2}

16 | Page
Day 8: Odd and Even
Write a function called odd_even that has one parameter and
takes a list of numbers as an argument. The function returns the
difference between the largest even number in the list and the
smallest odd number in the list. For example, if you pass [1, 2,
4, 6] as an argument, the function should return 6 - 1= 5.
Extra Challenge: List of Prime Numbers

Write a function called prime_numbers. This function asks the


user to enter a number (an integer) as an argument and returns a
list of all the prime numbers within its range. For example, if the
user enters 10, your code should return [2, 3, 5, 7] as prime
numbers.

17 | Page
Day 9: Biggest Odd Number
Createa function called biggest_odd that takes a string of
numbers as an argument and returns the biggest odd number in the
string. For example, if you pass ‘23569’ as an argument, your
function should return 9. Use list comprehension.

Extra Challenge: Zeros to the End


Write a function called zeros_last. This function takes a list as an
argument. If a list has zeros (0), it will move them to the end of the
list and maintain the order of the other numbers in the list. If there
are no zeros in the list, the function should return the original list,
sorted in ascending order. For example, if you pass [1, 4, 6, 0, 7, 0,
9] as an argument, your code should return [1, 4, 6, 9, 0, 0]. If
you pass [2, 1, 4, 7, 6] as your argument, your code should return
[1, 2, 4, 6, 7].

18 | Page
Day 10: Hide my Password
Writeafunction called hide_password that takes no parameters.
The function takes an input (a password) from a user and returns a
hidden password. For example, if the user enters "hello" as a
password, the function should return "****" as a password and tell
the user that the password is 4 characters long.
Extra Challenge: A Thousand Separator
Your new company has a list of figures saved in a database. The
issue is that these numbers have no separator. The numbers are
saved in a list in the following format:
[1000000, 2356989, 2354672, 9878098]. You have been

asked to write a code that will convert each of the


numbers in the list into a string. Your code should then add a
comma to each number as a thousand separator for
readability. When you run your code on the above list, your output
should be:
['1,000,000', '2,356,989', '2,354,672', '9,878,098’]
Write a function called convert_numbers that will take
one argument, the list of numbers above.

19 | Page
Day 11: Are They Equal?
Writeafunction called equal_strings. The function takes
two strings as arguments and compares them. If the strings
are equal (if they have the same characters and have equal
length), it should return True; if they are not, it should
return False. For example, "love" and "evol" should return
True.
Extra Challenge: Swap Values

Write a function called swap_values. This function takes a


list of numbers and swaps the first element with the last
element. For example, if you pass [2, 4, 67, 7] as a
parameter, your function should return.
[7, 4, 67, 2].

20 | Page
Day 12: Count the Dots
Writeafunction called count_dots. This function takes a string
separated by dots as a parameter and counts how many dots are in
the string. For example, "h.e.l.p." should return 4 dots, and
"[Link]." should return 2 dots.

Extra Challenge: Your Age in Minutes


Write a function called age_in_minutes that tells a user how
old they are in minutes. Your code should ask the user to enter
their year of birth, and it should return their age in minutes (by
subtracting their year of birth from the current year). Here are
things to look out for:

a. The user can only input a 4-digit year of birth. For example,
1930 is a valid year. However, entering any number longer
or shorter than 4 digits, should render the input invalid.
Notify the user that they must enter a four-digit number.
b. If a user enters a year before 1900, your code should tell
the user that the input is invalid. If the user enters the year
after the current year, the code should tell the user to input
a valid year.
The code should run until the user inputs a valid year. Your
function should return the user's age in minutes. For example, if
someone enters 1930 as their year of birth, your function should
return:
You are 48, 355, 200 minutes old.

21 | Page
Day 13: Pay Your Tax
Write a function called your_vat. The function has no
parameters. The function asks the user to input the price of an
item and VAT (VAT should be a percentage). The function should
return the price of the item plus VAT. If the price is 220 and the
VAT is 15%, your code should return a VAT-inclusive price of 253.
Check to see if your code can handle ValueError and negative
inputs from the user. Ensure the code runs until valid numbers are
entered. (Hint: Your code should include a while loop.)

Extra Challenge: Pyramid of Snakes

Write a function called python_snakes that takes a number as


an argument and creates the pyramid shape using the number’s
range. (Hint: Use the loops and emoji libraries for snake emojis.)
If you pass 7 as an argument, your code should print the
following:

22 | Page
Day 14: Flatten the List
Writea function called flat_list that takes one argument, a nested
list. The function converts the nested list into a one-dimensional
list. For example, [[2, 4, 5, 6]] should return [2, 4, 5, 6].

Extra Challenge: Teacher’s Salary


A school has asked you to write a program that will calculate
teachers' salaries. The program should ask the user to enter the
teacher’s name, the number of periods taught in a month, and
the rate per period. The monthly salary is calculated by
multiplying the number of periods by the monthly rate. The
current monthly rate per period is $20. If a teacher has more than
100 periods in a month, everything above 100 is overtime.
Overtime is $25 per period. For example, if a teacher has taught
105 periods, their gross monthly salary should be $2,125. Write a
function called "your_salary" that calculates a teacher’s gross
salary. The function should return the teacher’s name, periods
taught, and gross salary. Here is how you should format your
output: Teacher: John Kelly, Periods: 105 Gross salary:2,125

23 | Page
Day 15: Same in Reverse
Write a functioncalled same_in_reverse that takes a string and
checks if the string reads the same in reverse. If it is the same, the
code should return True if not, it should return False. For
example, "dad" should return True, because it reads the same in
reverse.
Extra Challenge: What’s My Age?

Write a function called your_age. This function asks a student to


enter their name, and then it returns their age. For example, if a
user enters Peter as their name, your function should return, "Hi,
Peter, you are 27 years old." This function reads data from the
database (dictionary below). If the name is not in the dictionary,
your code should tell the user that their name is not in the
dictionary and ask them for their age. Your code should then add
the name and age to the dictionary named "names_age" below.
Once added, your code should return to the user, "Hi, (name),
you are (age) years old." Remember to convert the input from
the user to lowercase letters.

names_age = {"jane": 23, "kerry": 45, "tim": 34, "peter": 27}

24 | Page
Day 16: Sum the List
Writea function called sum_list with one parameter that takes a
nested list of integers as an argument and returns the sum of the
integers. For example, if you pass [[2, 4, 5, 6], [2, 3, 5, 6]] as an
argument, your function should return a sum of 33.
Extra Challenge: Unpack A Nest
nested_list = [[12, 34, 56, 67], [34, 68, 78]]
Write a code that generates a list of the following numbers from
the nested list above: 34, 67, 78. Your output should be another
list: [34, 67, 78]. The list output should not have duplicates.

25 | Page
Day Name
User 17: Generator
Writea function called user_name, that creates a username for
the user. The function should ask a user to input their name. The
function should then reverse the name and attach a randomly
issued number between 0 and 9 at the end of the name. The
function should return the username.
Extra Challenge: Sort by Length
names = [ "Peter", "Jon", "Andrew"]
Write a function called sort_length that takes a list of strings as
an argument and sorts the strings in ascending order according to
their length. For example, the list above should return:
['Jon', 'Peter', 'Andrew']
Do not use the built-in sort functions.

26 | Page
Day 18: Any Number of Arguments
Write a function called any_number that can receive any
number of positional arguments (integers and floats) and return
the average of those integers. If you pass 12, 90, 12 and 34 as
arguments, your function should return 37.0 as the average. If you
pass 12 and 90, your function should return 51.0 as the average.

Extra Challenge: Add and Reverse


Write a function called add_reverse. This function takes two
lists as arguments, adds each corresponding number, and
reverses the outcome. For example, if you pass [10, 12, 34]
and [12, 56, 78], your code should return [112, 22, 68]. If the
two lists are not of equal length, the code should return a
message that "the lists are not of equal length."

27 | Page
Day 19:
Words and Elements
Write two functions. Thefirst functionis calledcount_words
which takes a string of words as argument and counts how many
words are in the string.
The second function, called count_elements takes a string of
words and counts how many elements are in the string. Do not
count the whitespaces. The first function will return the number of
words in a string, and the second one will return the number of
elements (less whitespace). If you pass "I love learning," the

count_words function should return 3 words and


count_elements should return 13 elements.

28 | Page
Day 20: Capitalize First Letter
Writeafunction called capitalize. This function takes a string as
an argument and capitalizes the first letter of each word. For
example, "i like learning" becomes "I Like Learning."

Extra Challenge: Reversed List


str1 = 'leArning is hard, bUt if You appLy youRself ' \
'you can achieVe success'

You are given a string of words. Some of the words in the string
contain uppercase letters. Write a code that will return all the
words that have an uppercase letter. Your code should return a
list of the words. Each word in the list should be reversed. Here
is how your output should look:
['gninrAel', 'tUb', 'uoY', 'yLppa', 'flesRuoy', 'eVeihca']

29 | Page
Day 21: List of Tuples
Write a function called make_tuples that takes two equal lists
and combines them into a list of tuples. Your code should check
that the input lists are of the same length. For example, if list a is
[1, 2, 3, 4] and list b is [5, 6, 7, 8], your function should return
[(1, 5), (2, 6), (3, 7), (4, 8)]. If the lists are not of equal length,
your function should raise a ValueError.

Extra Challenge: Even Number or Average

Write a function called even_or_average that asks a user to


input five numbers. Once the user is done, the code should
return the largest even number in the inputted numbers. If
there is no even number in the list, the code should return the
average of all the five numbers.

30 | Page
Day 22: Add Under_Score
Create three functions. The first, called add_hash takes a string
and adds a hash (#) between the words. The second function,
called add_underscore removes the hash (#) and replaces it
with an underscore ("_"). The third function,
called
remove_underscore, removes the underscore and replaces it
with nothing. If you pass "Python" as an argument for the three
functions, and you call them at the same time like:
print(remove_underscore(add_underscore(add_hash('Python'))))
it should return "Python".

31 | Page
Day 23: Simple Calculator
Createasimple calculator. The calculator should be able to perform the
following basic math operations: add, subtract, divide, and
multiply. The calculator should take input from users. The calculator
should be able to handle ZeroDivisionError, NameError, and
ValueError.

Extra Challenge: Multiply Words


s = "love live and laugh"

Write a function called multiply_words that takes a string as an


argument and multiplies the length of each word in the string by the
length of other words in the string. For example, the string above
should return 240: love (4), live (4), and (3), laugh (5).
However, your function should only multiply words with all
lowercase letters. If a word has one uppercase letter, it should be
ignored. For example, the following string: s = "Hate war love
Peace" should return 12 – war (3) love (4). Hate and Peace will
be ignored because they have at least one uppercase letter.

32 | Page
Day 24: Average Calories
Write a function called average_calories that calculates the
average calorie intake of a user. The function should ask the user to
input their calorie intake for any number of days, and once they hit
"done," it should calculate and return the average intake.

Extra Challenge: Create a Nested List


Write a function called nested_lists that takes any number of lists
and creates a 2-dimensional nested list of lists. Your code must
check that the inputs are of the list data type. For example, if you
pass the following lists as arguments: [1, 2, 3, 5], [1, 2, 3, 4], [1,
3, 4, 5].
Your code should return: [[1, 2, 3, 5], [1, 2, 3, 4], [1, 3, 4, 5]]

If you pass:
(1,2,3,5), [1, 2, 3, 4], [1, 3, 4, 5] as arguments,
yourfunctionshould return "Invalid arguments. Please
check
your arguments."

33 | Page
Day 25: All the Same
Writea function called all_the_same that takes one argument, a
string, a list, or a tuple, and checks if all the elements are the same.
Use the instance function to check that the input data is either a
string, a list, or a tuple, or else raise a TypeError that says that
"Input must be a string, a list, or a tuple." If the elements are
the same, the function should return True. If not, it should return
False. For example, ["Mary", "Mary", "Mary"] should return
True.

Extra Challenge: Reverse a String


str1 = "the love is real"
Write a function called read_backwards that takes a string as
an argument and reverses it. The string above, for example, should
return: "real is love the."

34 | Page
Day 26: Sort Words
Write a function called sort_words that takes a string of words
as an argument, removes the whitespaces, and returns a list of
letters sorted in alphabetical order. Letters will be separated by
commas. All letters should appear once in the list. This means that
you sort and remove duplicates. For example, "love life" should
return as ['e, f, i, l, o, v'].

Extra Challenge: Length of Words

s = 'Hi my name is Richard'


Write a function called string_length that takes a string of words
(words and spaces) as an argument. This function should return the
length of all the words in the string. Return the results in the form
of a dictionary. The string above should return:
{'Hi': 2, 'my': 2, 'name': 4, 'is': 2, 'Richard': 7}

35 | Page
Day 27: Unique Numbers
Write a function called unique_numbers that takes a list of
numbers as an argument. Your function is going to find all the
unique numbers in the list. It will then sum up the unique
numbers. You will calculate the difference between the sum of
all the numbers in the original list and the sum of the
unique numbers in the list. If the difference is an even
number, your function should return the original list. If the
difference is an odd number, your function should return a
list with only unique numbers . For example, [1, 2, 4, 5,
6, 7, 8, 8] should return [1, 2, 4, 5, 6, 7, 8, 8].

Extra Challenge: Difference of Two Lists

Write a function called difference that takes two lists as


arguments. This function should return all the elements
that are in list a but not in list b and all the elements in list
b but not in list a. For example:
list1 = [1, 2, 4, 5, 6]
list2 = [1, 2, 5, 7, 9]
should return:
[4, 6, 7, 9]
Use list comprehension in your function.

36 | Page
Day 28: Return Indexes
Write a function called index_position. This function takes a
string as a parameter and returns the positions, or indexes, of all
lowercase letters in the string. For example, "LovE" should
return [1, 2].

Extra Challenge: Largest Number

Write a function called largest_number that takes a list of


integers as an argument and re-arranges the individual digits to
create the largest number possible. For example, if you pass the
following as an argument, list1 = [3, 67, 87, 9, 2]. Your code
should return the number in this exact format: 9, 877, 632 as the
largest number.

37 | Page
Day 29: Middle Figure
Writea function called middle_figure that has two
parameters, a and b. The two parameters are strings. The
function joins the two strings and finds the middle element. If
the combined string has a middle element, the function
should return the element; otherwise, it should return "no
middle figure." Use "make love" as an argument for a, and
"not wars" as an argument for b. Your function should
return "e" as the middle element. Whitespaces should be
removed.

38 | Page
Day 30: Most Repeated Name
Write a function called repeated_name that finds the most
repeated name in the following list. Your function should return a
tuple of the name and how many times it appears. The list below
should return: ("Peter", 3).

Extra Challenge: Sort by Last Name

You work for a local school in your area. The school has a list of
names of students saved in a list format. The school has asked you
to write a program that takes a list of names and sorts them
alphabetically. The names should be sorted by last name. Here is a
list of names:
["Beyoncé Knowles", "Alicia Keys", "Katie Perry",
"Chris Brown", "Tom Cruise”]

Your code should not just sort them alphabetically; it should also
switch the names (the last name must be the first). Here is how
your code output should look:
['Brown Chris', 'Cruise Tom', 'Keys Alicia', 'Perry
Katie', 'Knowles Beyoncé']
Write a function calledsorted_names.

39 | Page
Day 31: Longest Word
Write a function that has one parameter and takes a list of words
as an argument. The function returns the longest word from the
list. Name the function longest_word. The function should
return the longest word and the number of letters in that word.
For example, if you pass ['Java', 'JavaScript', 'Python'], your
function should return [10, JavaScript] as the longest word.

Extra Challenge: Create User


Write a function called create_user. This function asks the user
to enter their name, age, and password. The function saves this
information in a dictionary. For example, if the user enters Peter
as his name, 18 as his age, and "love" as his password, the function
should save the information as: {"name": "Peter", "age": "18",
"password": "love"}.

Once the information is saved, the function should print to the


user, "User saved. Please login"
The function should then ask the user to re-enter their name and
password. If the name and password match what is saved in the
dictionary, the function should return "Logged
in
successfully." If the name and password do not match what is
saved in the dictionary, the function should print "Wrong
password or user name, please try again". The function
should keep running until the user enters the correct logging
details.

40 | Page
Day 32: Password Validator
Write a function called password_validator. The function asks
the user to enter a password. A valid password should have at least
one uppercase letter, one lowercase letter, and one
number. It should not be less than 8 characters long. When the
user enters a password, the function should check if the password is
valid. If the password is valid, the function should return the valid
password. If the password is not valid, the function should inform
the user of the errors in the password and prompt the user to enter
another password. The code should only stop once the user enters a
valid password.

Extra Challenge: Valid Email

emails = [ "ben@[Link]", "john@[Link]", "kenny@[Link]", "@[Link]

Write a function called email_validator that takes a list of emails


and checks if the emails are valid. Only valid emails are returned by
the function. A valid email address will have the following: the @
symbol (if the @ sign is at the beginning of the name, the email is
invalid). If there is more than one @ sign, the email is invalid. All
valid emails must end with a dot com (.com); otherwise, the email
is invalid. For example, the list of emails above should output the
following as valid emails:
['ben@[Link]', 'kenny@[Link]']
If no emails in the list are valid, the function should return "All
emails are invalid."

41 | Page
Day 33: List Intersection
Write a functioncalled inter_section that takes two lists and
finds the intersection (the elements that are present in both
lists). The function should return a tuple of intersections with the
number at index 0 switched with the number at index -1. Use
list comprehension in your solution. Use the lists below. Your
function should return (80, 65, 30).
list1 = [20, 30, 60, 65, 75, 80, 85] list2 = [ 42, 30, 80,
65, 68, 88, 95]

Extra Challenge: Set or List


You want to implement code that will search for a number in a
range. You have a decision to make as to whether to store the
number in a set or a list. Your decision will be based on time.
You have to pick a data type that executes faster.
You have a range, and you can either store it in a set or a list,
depending on which one executes faster when you are searching
for a number in the range. See below:
a = range(10000000)
x = set(a)
y = list(a)
Let’s say you are looking for the number 9999999 in the range
above. Search for this number in the list "x" and the set "y." Your
challenge is to find which code executes faster. You will select the
one that executes the fastest between lists and sets. Run the two
searches and time them.

42 | Page
Day 34: Just Digits
Inthis challenge, copy the text below and save it as a CSV file.
Save it in the same folder as your Python file. Save it as
[Link]. Write a function called just_digits that reads the
text from the CSV file and returns only digit elements from the file.
Your function should return 1991, 2, 200, 3, 2008 as a list of
strings.

“Python was releasedin1991 for the first time. Python


2 was released in 2000andintroduced new features,
such as list
comprehensionsand
collection acycle-detecting garbage
system (in additiontoreference counting). Python 3 was release
in 2008 and wasamajorrevision of the language that is not
completely backward-compatible.”
Source: Wikipedia

43 | Page
Day 35: Pangram
Write a function called check_pangram that takes a string and
checks if it is a pangram. A pangram is a sentence that
contains all the letters of the alphabet. If it is a pangram, the
function should return True, otherwise, it should return False.
The following sentence is a pangram, so it should return True:

'the quick brown fox jumps over a lazy dog'

Extra Challenge: Find my Position


Write a function called find_index that takes two arguments; a
list of integers, and an integer. The function should return the
indexes of the integers in the list. If the integer is not in the list,
the function should convert all the numbers in the list into the
given integer.
For example, if the list is [1, 2, 4, 6, 7, 7] and the integer is 7,
your code should return [4, 5] as the indexes of 7 in the list. If the
list is [1, 2, 4, 6, 7, 7] and the integer is 8, your code should
return [8, 8, 8, 8, 8, 8] because 8 is not in the list.

44 | Page
Day 36: Count String
Writea functioncalled count that takes one argument, a string,
and returns a dictionary of how many times each element appears
in the string. For example, 'hello' should return:
{'h':1,'e': 1,'l':2, 'o':1}.
Extra Challenge: Sum a Nested Dictionary

You have a nested dictionary below. Write a function called


sum_nested_dict, that takes one argument, a dictionary, and
returns the sum of all the values in the dictionary. The nested
dictionary below, should return 15.

45 | Page
Day 37: Count the Vowels
Create a function called count_the_vowels. The function takes
one argument, a string, and returns the number of vowels in the
string. If the data type of the input is not of the string type, the
function should return "invalid input." If the argument has no
vowels, your function should return "The string has no
vowels." If a vowel appears in a string more than once, it should
be counted as one. For example, "hello" should return two (2)
vowels; "saas" should return one (1) vowel; and "sly" should
return: "The string has no vowels." Your code should count
lowercase and uppercase vowels.

46 | Page
Day 38: Guess a Number
Write a function called guess_a_number. The function should
ask a user to guess a randomly generated number. If the user
guesses a higher number, the code should tell them that the guess
is too high; if the user guesses a low number, the code should tell
them that their guess is too low. The user should get a maximum of
three (3) guesses. When the user guesses right, the code should
declare them a winner. After three wrong guesses, the code should
declare them losers.

Extra Challenge: Find Missing Numbers


list1 = [1, 2, 3, 5, 6, 7, 9, 11, 12, 23, 14, 15, 17,
18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 31]

Write a function called missing_numbers that takes a list of


sequence of numbers as argument, and finds the missing
numbers in the sequence. The list above should return:
[4, 8, 10, 13, 16, 29, 30]

47 | Page
Day 39: Generator
Password
Createa function called generate_password that generates
any length of password for the user. The password should have a
random mix of uppercase letters, lowercase letters, numbers, and
punctuation symbols. The function should ask the user how
strong they want the password to be. The user should pick from
weak, strong, or very strong. If the user picks "weak," the
function should generate a 5-character long password. If the
user picks "strong," generate an 8-character password, and if
they pick "very strong," generate a 12-character password.

48 | Page
Day 40: Pig Latin
Write afunction called translate that takes the following
words and translates them into Pig Latin.

Here are the rules:


1. If a word starts with a vowel (a, e, i, o, u) add "yay" at
the end. For example, "eat" will become "eatyay"
2. If a word starts with anything other than a vowel, move
the first letter to the end and add 'ay' to the end. For
example, "day" will become "ayday."
Your code should return:
iyay ovelay ythonpay

49 | Page
Day 41: Only Words with Vowels
Create afunction called words_with_vowels. This function
takes a string of words and returns a list of only the words that have
vowels in them. "You have no rhythm," for example, should
return ["you," "have," "no"].
Extra Challenge: Class of Cars

Create three classes for three car brands: Ford, BMW, and
Tesla. The instance attributes of the car's objects will be model,
color, year, transmission, and whether the car is electric or not
(a Boolean value). Consider using inheritance in your answer.
You will create one object for each car brand:
bmw1 : model: x6, Color: silver, Year: 2018, Transmission: Auto, Electric: False
tesla1: model: S, Color: beige, Year: 2017, Transmission: Auto, Electric: True
ford1 : model: focus,Color:white,Year:2020,Transmission:Auto,Electric:False

You will create an instance method called print_cars that will


be able to print out objects of the class. For example, if you call the
method on the ford1 object of the Ford class, your function should
be able to print out car info in this exact format:
car_model= focus
Color = White
Year = 2020
Transmission = Auto
Electric = False

50 | Page
Day 42: Spelling Checker
Write a function called spelling_checker. This code asks the
user to input a word, and if the user inputs the wrong spelling, it
should suggest the correct spelling by asking the user if they
meant to type that word. If the user says no, it should ask the
user to enter the word again. If the user says yes, it should
return the correct word. If the word entered by the user is
correctly spelled, the function should return the correct word.
Use the module textblob.
Extra Challenge: Set Alarm

Write a function called set_alarm that sets an alarm clock for


the user. The function should ask the user to enter the time they
want the alarm to go off. The user should enter the time in hours
and minutes. The function should ensure that the user enters
valid inputs for hour and minutes. The function should run until
the user enters valid input. Once the user enters valid inputs, the
function should then print out the time when the alarm will go off.
When it's alarm time, the code should let off a sound. Use the
winsound module for sound.

51 | Page
Day 43: Student Marks
Write a function called student_marks that records the marks
achieved by students in a test. The function should ask the user to
input the name of the student and then ask the user to input the
marks achieved by the student. The information should be stored
in a dictionary. The name is the key, and the mark is a value.
When the user enters "done," the function should return a
dictionary of the names and values entered or an empty dictionary
if no values are entered. Your code should ensure that:
¶ If a name contains punctuation characters (!"#$%&'()*+,-
./:;<=>?@[\]^_`{|}~) or numbers(digits) your code
should raise a NameError and ask the user to enter a
valid name.
¶ If the a user enters invalid values for value, your code
should handle the ValueError.
¶ Your code should run until a valid values are inputted.

52 | Page
Day 44: Save Emails
Create a function called save_emails. This function takes no
arguments but asks the user to input an email, and it saves the
emails in a CSV file. The user can input as many emails as they
want. Once they hit "done," the function saves the emails and
closes the file. Create another function called open_emails.
This function opens and reads the content of the CSV file. Each
email requires its own line. Here is an example of how the
emails must be saved:
jj@[Link] kate@[Link] and not like this:
jj@[Link]@[Link]

53 | Page
Day 45: Words & Special Characters
Writeafunction called analyse_string that takes a string as an
argument and returns the number of special characters
(#$%&'()*+,-./:;<=>?@[\]^_`{|}~), numeric characters, and
total characters (the length of the string minus the whitespaces)
in the string. Return everything in a dictionary format:
{"special_char": "number," "numeric_char": "number,"
"total characters": "number"} Use the string below as an
argument: "Python has a string format operator %. This
functions analogously to printf format strings in C, e.g.
"spam=%s eggs=%d" % ("blah", 2) evaluates to "spam=blah
eggs=2".

Source Wikipedia.

54 | Page
Day 46: Create a DataFrame
Create a DataFrame using [Link] are going to create code to
put the following into a DataFrame. You will use the information
in the table below. Basically, you are going to recreate this table
using pandas. Use the information in the table to recreate the
table.

year Title genre


200 Brothers Drama
9 Spider-Man Sci-fi
200 WatchMen Drama
2 Inception Sci-fi
200 Avatar Fantasy
9
201
Extra Challenge: Website Data with Pandas
0
Create a code that extracts data from a website. You will extract a
200 from the website. And from that table, you will extract
table
9
columns about the data types in Python and their mutability. You
will extract information from the following website:
[Link]
The following table (next page) is what you will extract from the
website.

55 | Page
Once you extract this table, you will write a code that will
extract the data types and their mutability (Two columns).
Here is how your output should look:

56 | Page
Day 47: Save a JSON
Writeafunctioncalled save_json. This function takes a
dictionary as an argument and saves it on a file in JSON format.
Write another function called read_json that opens the file
that you just saved and reads its content. Use the function
below as an argument.

57 | Page
Day 48: Binary Search
Writea function called search_binary that searches for the
number 22 in the following list and returns its index. The
function should take two parameters: the list and the item that
is being searched for. Use binary search (iterative method).

58 | Page
Day 49: Create a Database
Forthis challenge, you are going to create a database using
Python’s SQLite. You will import SQLite into your script. Create
a database called [Link]. In that database, you are going to
create a table called "movies." In that table, you are going to save
the following movies:

year title genre


200 Brothers Drama
9 Spider Man Sci-fi
200 WatchMen Drama
2 Inception Sci-fi
200 Avatar Fantasy
9
201
a) Once you create a table, run a SQL query to see all the
0 movies in your table.
b) Run another SQL query to select only the movie Brothers
200
from the list.
9 c) Run another SQL query to select all movies that were
released in 2009 from your table.
d) Run another query to select movies in the fantasy and
drama genres.
e) Run a query to delete all the contents of your table.

59 | Page
Day 50: Create a Flask App
In this challenge, you will getto create an appusing Flask. Flask is a
Python web framework. Learning to build websites with Flask is a
very important skill to have if you want to get into web development.
You will build an app using Python, HTML, and CSS. I
recommend using Visual Studio code for this challenge. You can
still use whatever editor or IDE you are comfortable with. You are
going to create an app with two pages, the home page and the
about page. Your website will have a navigation bar, so you can
move between the home page and the about page. It will have a
background image. The image in the project is by Hasan Albari
from Pexels. Below is what you should make:

Home Page

60 | Page
About Page

Flask does not come with Python, so you will have to install it on
your machine and import it into your script. If you have never
made a website before, this challenge will require some research. I
suggest using a virtual environment for your project. Good luck. I
believe in you.

61 | Page
Answers

62 | Page
Answers to the Challenges
Day 1
Inthischallenge, we use conditionalstatements to create two
conditions. If any one of those conditions is true, that block of
code will be executed. The if statement checks if the number is
divisible by 5, and if it is, we calculate the square root of the
number. The else statement will execute only if the number is
not divisible by 5. In that case, the else block will return the
remainder of the division.

Extra Challenge: Longest Value


We use the max() function to return the maximum value of the
dictionary values. The max function has a key parameter. Since we
are looking for the first longest value, we pass len to the key
parameter. If we do not pass len to the key parameter, it will return
green as the longest value, which is lexicographically larger than
apple.

63 |Page
Day 2
In this challenge, we use typecasting to convert the strings in
the list into integers using the int() function. Once they are
converted, we use the built-in sum function to sum the integers
in list b.

If you do not want to use the built-in sum() function, you can
create a second for loop in the function that will iterate
through list2 of integers. We add all the elements of list2 to
the variable count.

64 | Page
Extra Challenge: Duplicate Names
Below, we use a for loop and conditional statements to iterate over a
list and check if there are items in the list that appear more than once.
We count how many times each item appears in the list using the
count() method. Once we find an item that appears more than once,
we first check if the item is in the duplicates list; if not, we append
the item to the duplicates list. We write another if-statement to
check if the duplicate list is empty or not. If it is not empty, we return
the duplicates list; if it is empty, then it means that we do not have
duplicates in the list, so we return "No duplicates."

65 | Page
Day 3
First, we create a count variable and assign it a value of
zero (0). To count the "yes" values in the dictionary, we
need to access the dictionary values ([Link]) using a
for loop. The for loop loops through the dictionary
looking for "yes" values. Every value is added to the
count variable.

Another way to go about it


In this method below, we use the dictionary items() method
to access the values.

66 | Page
Extra Challenge: Lowercase names
For this challenge,weare going to use two built-in functions: the
sorted function and the tuple function. The sorted() function will
sort the list in descending order. To sort a list in descending order,
set reverse to True. The tuple() function will convert the sorted list
into a tuple.

67 | Page
Day 4
In this challenge, we use the type() function and conditional
statements. The type() function is used to check the data type
of the arguments passed to the function. We also use the
comparative operators "and", and "or" to check whether both
arguments are floats, or if only one of them is a float.

Extra Challenge: Index of the Longest Word


The first thing we do, ischeck if all the stringsin the list are of the
same length. If so, we return 0. If they are not, we search for the
longest word using the len() and max() functions. Once we find it,
we search for its index using the index() method.

68 | Page
Day 5
In this code, our function takes no arguments. We ask the user for
input using the input() function. Since the input is in string
format, we must first convert it to integer data type using the int()
function before we can calculate the discount. The output in this
code assumes an input price of 150 and a discount of 15%.

Extra Challenge: Tuple of Student Sex

The first thing to do for this challenge is to ensure that we convert all
the strings into lowercase letters, using the lower() method. So, we
create a new list with names converted into lowercase. Then we
search for males and females in the list. We use the count method
to count how many times each item appears in the new_list. We
then combine the sex and the number of times it appears in the list
into a tuple (sex, new_list.count(sex). We then append the tuples
to the student count [Link] that we use the break statement
after append, to ensure that we only iterate through the list once.

69 | Page
70 | Page
Day 6
The split() function splits the email at the "@" element. Once the
email is split, we can use indexing to access the elements of the
email. The part that we want to use for the user name is sitting at
index 0, which is why we use [0] in our code to access it.

Extra Challenge: Zero Both Ends

This challenge requires a little slicing. Just access the first and last
elements in the list and replace them with zeros.

71 | Page
Day 7
Inthis code, using list comprehension, we create a list from the
range. However, to use the join() method on the list, we must ensure
that our list elements are in string format. We use the str() function to
convert x into a string before calling the join() function to join the
string with dots.

Extra Challenge: Dictionary of Names


In this challenge, we are asked to create a dictionary of names that start
with "S." So, first, we need to find all the names in the list that start
with "S," and then we need to return these results in a dictionary. The
easiest way to find the names is to use the startwith() method. This
method will return all names that start with "S." In the code below, we
create an empty dictionary, then search for all the elements that start
with "S." Using the dictionary method (update), we update the empty
dictionary with the results of our search.

72 | Page
Second Method Another method would be to use the Counter class
from the collections
module. The Counter class keeps track of elements and their counts
and stores the results in a dictionary. It returns the name of the
element as a key and its count as a value. See the code below:

73 | Page
Day 8
Inthis challenge, we use the modulus operator to find even and odd
numbers in the list. Then we use the max() and min() functions to
return the maximum number and minimum number, respectively.

Extra Challenge: List of Prime Numbers


A prime number is a number that has two factors, 1 and itself. Prime
numbers start from 2. For this challenge we use the range() function
to find range of the number.

74 | Page
Day 9
Usinglistcomprehension, we use a for loop and an if
statement to return a list of odd numbers. Here, you get to use
the modulus operator (%). The modulus operator returns the
remainder of a division. A number is odd if it returns a
remainder when divided by 2. In this code, we use the if
statement to return only numbers that are not divisible by 2. The
max() function will return the biggest odd number in the list.

Extra Challenge: Zeros to the End


This challenge is about understanding indexing. The first step is
to identify non-zero numbers in the list. Once we identify them,
we move them to the backof the list while incrementing the index
by 1. We then fill the remaining spots with the zeros on the list.

75 | Page
76 | Page
Day 10
Inthis challenge, we get to use the input() function to get
information from a user. We then use the len() function to get the
length of the password. We use the multiplication operator to
multiply each element of the string with ‘*’.

Extra Challenge: A thousand Separator


The easiest way to do this is to use the format method.

77 | Page
Day 11
Tocompare the two strings, we first need to sort them. We use the
sorted() function to sort the two strings. Then we use the "=="
operator to compare the two strings.

Extra Challenge: Swap Values


The easiest way to solve this challenge would be to create separate
variables for the numbers that you want to swap. Use list slicing to
get the values. So we assign the first number in the list to the
"first_number" variable and the last number in the list to the
"last_number" variable. We then assign the last number to index
0 and the first number to index 1.

78 | Page
Day 12
We usethe split() method to split the word at the dots. Once
the word is split, we use the len() function to count the dots.

Extra Challenge: Your Age in Minutes


Remember to import the datetime module for this challenge.
To keep the code running until a valid year is entered, use the
while loop. We will use the int() function to convert the input
from user to integer.

79 | Page
Day 13
Inthis challenge, you get to use typecasting, the input() function,
and the try and except blocks to handle errors. We use the if
statement to check that the inputs from the user are non-
negative. If the inputs are non-negative number, we calculate the
total price and return it. The input from the user is always in
string format, so we use the int() function to convert it into an
integer. The except block ensures that we handle the
ValueError. We have added the while loop to ensure that the
code runs until valid numbers are entered.

80 | Page
Extra Challenge: Pyramid of Snakes
Withthis challenge, we use loops to createa pyramid of snakes. We
imported the emoji library to get the snake emoji. For each iteration, we
calculate the number of spaces to print before the snake emojis using the
formula range(n , i, -1). We add the emojis using range(0, i + 1) to
create the pyramid shape. See the code below:

81 | Page
Day 14
Notice howwe use nested for loops in the code below? The first for
loop accesses the outer list, and the inner for loop accesses the inner
list. Once we access the elements of the inner list, we append them to
list 1. With this small code, we have flattened the list.

Extra Challenge: Teacher’s Salary


The output below assumes that the user inputs the following: name:
John Kelly, periods: 105, and rate: $20.

82 | Page
Day 15
Thischallenge tests your skill to use negative string slicing, if
statements, and operators in Python. The [::1] operator
reverses the string, and the == operator compares the original
string to the reversed string.

Extra Challenge: What’s My Age?


This challenge is about working with dictionaries. Since all the
keys in the dictionary are lowercase, we convert the input from
the user to lowercase. Then, we iterate over the dictionary to
see if the input name exists in our database. Once we find it, we
use the get() method to access the dictionary value (which is
the age of the person). If the name is not in the dictionary, we
use the while loop to update the dictionary with the new
information from the user. Once we update the dictionary, we
return the updated information to the user. See the code below:

83 | Page
84 | Page
Day 16
In this exercise, we use the for loop to flatten the nested lists.
We have created a variable called counta. Every number on
the list is added to the count. By the end of the iteration, all
the numbers will have been added to the counter.

Extra Challenge: Unpack a Nest


For this challenge, we need to write a nested loop to access the
inner list of the nested list. We then create a new list of all the
numbers that we need from the list.

85 | Page
Day 17
Inthis exercise, you get to use the random module. Every time
you call the function, the random module issues a random
number between 0 and 10. This number is added to the end of
the name using the + sign. We use slicing [::-1] to reverse the
name. Another way around it would have been to use the
reverse() method to reverse the name.

Extra Challenge: Sort by Length


For this challenge, we find the longest word and then swap it
with the shorter words. The shorter words come first, and the
longer words come later.

86 | Page
Day 18
In this challenge, you get to learn about *args. You can use any
word you want as a parameter as long as you use the * operator
at the beginning of the word. However, it's a common convention
to use args. The *args simply tells the function that we are not
sure how many arguments we will need, so the function lets us
add as many positional arguments as possible. In the example
below, we add two numbers as arguments. However, we can add
as many numbers as we want, and the function will work just
fine. The *args make functions more flexible.

In this function, we have added more arguments.

87 | Page
Extra Challenge: Add and Reverse
This challenge is best solved using the range() function. The
first step is to check if the lists are of equal length; we use the
len() function for that. Once we confirm that the lists are of
equal length, we use the range function to get the index of each
element in the list. We then add the results and append them
to the empty list we created. We then apply the list method,
reverse() to our new list to reverse the content of the list.

88 | Page
Day 19
Thesplit() function splits the string into smaller strings. By
default, the split() function uses any white spaces to split a
string. Once the string is split, we use the for loop to iterate
through the strings and append them to the words variable. The
len() function counts how many items are on our list.

Second function

Since the len() function counts white spaces as elements, we


use the replace() method to remove white spaces from the
string before using the len() function.

89 | Page
Day 20
The enumerate() function returns the element and its index while
iterating through the string. The capitalize() method will capitalize
the first letter of a string. In this code, we use the islower() method
to check which word in our string has lowercase letters. We then use
the capitalize() method to capitalize these words and append them
to a list. We then use the join() method to join the elements in our
output list into a single string.

Extra Challenge: Reversed List


For this challenge, we import the string module to get a list of
uppercase letters (string.ascii_uppercase). We check if any of the
words in the string have uppercase letters, and if they do, we append
the words to the upper_names list. We then use reverse ([::-1]) to
reverse the words in the list.

90 | Page
Day 21
Theeasiest way to deal with this problem is to use the built-in
zip() function in Python. First we use the conditional statement
to check the length of the two lists. If they are not of equal
length, we raise a ValueError. The zip() function combines the
two lists into pairs of tuples. We use the list() function to create
a list, and the tuple() function to put the numbers in tuples.

Another way is to use a for loop statement and the range


function. We will iterate over the range object and retrieve the
index of the lists. We will use the index to access the values of
lists a and b, and append them to the list_of_tuples.

91 | Page
Extra Challenge: Even Number or Average
Inthis challenge, we create twoemptylists. In the first list (avg_num),
we append all the numbers from the user; in the other list, we only
input even numbers (even_number). The code then checks the even
numbers list to see if it is empty; if it is empty, the code goes to the
avg_number list and calculates the average.

92 | Page
Day 22
Forthis challenge, you have to use the string() method and join()
method to add the hash (#). Then you use another string method,
replace(), to replace the hash with an underscore (_), and we also
use the replace() method to replace the underscore with nothing.

93 | Page
Day 23
Thisisa simple calculator that performs simple arithmetic operations.
We have used the operator module for the math operations. We have
added the try and except blocks to ensure that we handle some
exceptions. There are so many ways you can make a calculator. You
may have made it different or even better.

94 | Page
Extra Challenge: Multiply Words
Inthis function below, wefirst split the input string into individual words
using the split() method. Then, we iterate over each word in the words
list. If a word contains all lowercase letters (checked using islower()),
we append the length to the words_len variable. Finally, we use
prod() method to multiply the lengths in the words_len list.

Another way
If you do not want to usethe prod method from the math module, you
can multiply the lengthsofeach word by the words_len variable. See
code below:

95 | Page
96 | Page
Day 24
This simple average calorie calculator will run until the user
enters "done," then it will calculate the average calories. The
input from the user is added to the scores variable. We use
the sum() function and the len() function to calculate the
average calories in the "scores" list. The while loop is what
keeps the function running until something happens that
makes it break out of the loop. Once we hit "done," the loop is
halted by the break statement.

97 | Page
Extra Challenge: Create a Nested List The first thing is
that we pass *args as a parameter to
ensure that our function can take any number of positional
arguments. Then we use a for loop to check if the
arguments are of list data type. If they are not we will return
"Invalid arguments . Please check your arguments". We
create an empty list (list1) to append the lists to. We use
the for loop and the range() function to keep track of the
number lists passed as arguments. We use another for
loop to iterate through the lists and append them to the
empty list.

98 | Page
Day 25
Below the all_the_same function takes one argument, data, which
can be a string, list, or tuple. Inside the function, we first check if
the data is an instance of either a string, list, or tuple using the
isinstance() function. If it's not one of those types, we raise a
TypeError.
If data is a string, list, or tuple, we use a list comprehension and the
all() function to check if all the elements in data are equal to the first
element (data[0]). The all() function returns True if all elements in
the iterable are True, and False otherwise.

Extra Challenge: Reverse a String


In this challenge, we split the string on whitespaces using the split
method. We append the strings to the empty list (list x) and reverse
the words using [::-1]. We then get the words from the list and join
them using the join method.

99 | Page
Day 26
In this challenge, we use the replace() method to remove the
white spaces between the words. Once the spaces are removed,
we use the for loop to iterate through the string and append
the items to the list1 variable. We use the not-in operator on
list1 to ensure that we do not add duplicates to the list. We use
the join() method to add commas between the string elements.

Extra Challenge: Length of Words


This challenge requires that we create a dictionary of word
lengths. The word will be the key, and the length of the word is
the value. Below, we use the split() function to split the string
into a list of strings. We then iterate through the list and update
our empty dictionary(dict1) with the words (key) and length of
the words (value). See the code below:

100 | Page
101 | Page
Day 27
For this challenge, once we append the unique numbers to list2, we use
the sum() function to sum the numbers in list1, and list2. We use the
modulus operator (%) to check if the difference between the two
numbers is an even number or an odd number. If it is an even number,
we return list1, otherwise we return list2.

Extra Challenge: Difference of Two Lists


We use two list-comprehension statements: one to find items in arr1
that are not in arr2, and another to find items in arr2 that are not in
arr1.

102 | Page
Day 28
Usingthe enumerate() function, we can retrieve the item index or
position. The isupper() method returns True if a letter in the string is
capitalized. Once we find the capitalized letter, we want its index to be
appended to the idex list.

Extra Challenge: Largest Number


This challenge requires that we use some string methods, such as
strip and replace, to convert the number into an integer. Here is
the full code below:

103 | Page
Day 29
The first step in this challenge is to concatenate the two strings
and find the length of the new string using the len() function.
Remember to remove whitespace between the substrings. To
find the middle element, we use the floor division (//). The floor
division will round off to the nearest integer, which is 4. The
element sitting in position 4, or index 4, is the middle element.
Only strings with odd lengths will return a middle element.

104 | Page
Day 30
The collections module has a Counter() class that we can use to
find the most common element of a list. We use it here, and it
returns Peter, which appears in the list three times.

Extra Challenge: Sort by Last Name


Below, we take a list of names, and split each name into a list of
words, and then sort the list based on the last name using the
sorted() function with a custom key function x. The sorted
names are then appended to a new list list3 by joining the last
name with the first name in the desired format.

105 | Page
Day 31
Inthis challenge, we use the append() method to append the
strings and their length to list b. If you print list b you will get a
nested list of each word and its length. The max() function finds
the longest word in list b.

Extra Challenge: Create User


In this challenge, we create an empty dictionary and use the
update method to update it with information from the user. We
then use a while loop to ensure the code runs until the correct
user details are entered.

106 | Page
Day 32
Inthis code, we use the while loop to ensure that the code runs
until a valid password is entered. All errors in the input password
are appended to the errors list. The any() function checks if
any of the characters in the password satisfy a given condition. If
a condition is not satisfied, an error is raised.

107 | Page
Extra Challenge: Valid Email
Thiscode allows the user toenterapassword and validates it against
specific criteria, which is the presence of uppercase and lowercase
letters, digits, and a minimum length. It accumulates any validation
errors encountered and provides feedback to the user about the
specific requirements that their password does not meet. If the
password passes all the checks, it returns a success message. We use
for loops and conditional statements to check if the email is valid

108 | Page
Day 33
Using a for loop, we look for elements that are present in both
lists. The list comprehension will return a list of elements
that are present in list1 and list2. Once we find the numbers
present in both lists, we will swap the numbers at index 0 and -1
in the resulting intersection list and convert the list into a tuple
using the tuple method.

Extra challenge: Set vs list


To test the speed of thecode, we are going to use the timeit
function for both [Link] create two variables, set_test
and list_search. We then pass this variable to the timeit
function, and we set the number ofexecutions to 1000. Here
is the code below:

109 | Page
From the results, list search is performing faster than set search.
Note that the performance of sets and lists can vary depending on
the specific use case and the nature of the data being processed.
In general, sets are designed for efficient membership testing,
while lists provide more flexibility for element access and
manipulation.

110 | Page
Day 34
When opening files, it is good practice to open them with the
with statement. This means that you don’t have to close the
file at the end of the operation, as the with statement will
automatically close the file. In this code, we open the file in
read mode. We use the split() method to split the words in
the text intostrings. By default, the split method splits the text
on the whitespaces. The isdigit() method checks which string
elements arenon-numeric. These non-numeric elements are
appended tothe list1 variable.

111 | Page
Day 35
We usethestring module to get the alphabet letters in lowercase.
We then remove the whitespaces from our string using the
replace() method. We use the for loop to loop through the
string, remove duplicates, and append the elements of the string
to list1. We sort the elements of list1 in alphabetical order using
the sort() method, and then use the join() method to join the
string elements. We then compare the sorted sentence to the
alphabet. If the sentence has all the elements in the alphabet
variable, the code will return True.

112 | Page
Extra Challenge: Find My Position
In this challenge, it would be easy to use the enumerate
function. Since we are looking for the index of a number, the
enumerate function will return the index of all the numbers in
the list. We use the (if j == n) conditional statement to return
only indexes of the given number. If the number is not in the list,
we convert all the numbers in the list to the given number.

113 | Page
Day 36
This code creates a dictionary from a string. The code uses a nested
for loop. The first for loop returns the index elements of the
string. The second for loop also returns the index. If the element
index of loop one is equal to that of loop 2, 1 is added to the count
variable. The if statement is used to update the dictionary, d.

Extra Challenge: Sum Nested Dictionary

In the above code, the sum_nested_dict function takes a


dictionary as an argument. It iterates over the values of the
dictionary, and for each value, it checks if it is another dictionary
using the isinstance() function. If it is a dictionary, the function
makes a recursive call to sum_nested_dict to calculate the sum
of the nested dictionary. If it is not a dictionary, the value is added
to the total_sum. Finally, the function returns the total_sum.
We are using recursion to ensure that the function can retrieve the
values at any depth and calculate the sum

114 | Page
115 | Page
Day 37
The code checks if the letters in the string argument are vowels.
First, we check if the input argument is of the string data type. If
it is not of the string data type, the function will return "invalid
input." We use a for loop to loop over a string and capture
vowels. These vowels are appended to the vowels_in_str
variable. If the vowels_in_str is not empty, we return the length
of the list; otherwise, we return "The string has no vowels."

116 | Page
Day 38
We use the random module to issue a random number between 0
and 10. We use the while loop to ensure the code keeps running
until the condition becomes False. The condition becomes False
when the user guesses the right number or runs out of guesses. The
user gets a maximum of three (3) guesses.

117 | Page
Extra Challenge: Find Missing Numbers
There are many ways you can solve this challenge. Here we using
the range() function to find the missing numbers in the sequence.
We create a range object from the beginning of the list to the end.
We search for missing values in the object and append them to the
missing_numz variable.

118 | Page
Day 39
For this challenge, we are using two modules: the string module
and the random module. The string module provides all the
characters we need for the password. We use the random module
([Link]) to shuffle variable a. We ask the user to pick
the length of the password they want, so after we shuffle the
characters of the password, the issued password is the length
requested by the user.

119 | Page
Day 40
Using the enumerate() function, we obtain the index of each
letter in the string. The split() method turns the words in the
string into strings. We use the if statement to check if the first
letter of the word is a vowel. If it is a vowel, we append "yay" at
the end. If it is not, we move the first letter to the end and
append "ay."

120 | Page
Day 41
Notice that we are using the nested for loop to find the letters
in the words. We iterate over the words to check if any of the
letters in the words are vowels. If a word has a vowel in it, we
append it to the vowels list. In the vowels list, we only have
words that have vowels in them.

Extra Challenge: Class of Cars


In this challenge, we create the Cars class. This class is the
parent class of all car brand classes. This is called
inheritance. The child classes inherit the properties and
methods of the parent class. The child classes have "Cars" as
an argument.

121 | Page
122 | Page
Day 42
Thetextblob module is being used to validate the user's input. If
the word is not spelled correctly, the module suggests a correct
spelling to the user. If the user accepts the word, the word is
returned. If the user does not accept the word, the code asks the
user to enter another word. We are using a while loop, so this code
will only break once the user inputs a correct word or accepts the
correctly spelled word suggested by the code.

123 | Page
Extra Challenge: Set Alarm
We first import the winsound module to provide the sound when the
alarm goes off. The datetime module is imported to work with date and
time. We use while loops to validated inputs from user. The while loops
will keep the code running until the user enters a valid hour value in the
range of 0-2; and a validate minute value in the range of 0-59. If the input
is not valid an error message is displayed and the user is asked to enter
valid inputs.. We format the time (alarm_time) by combining the
inputted hour and minute using the format() method. When the
alarm_time matches the now time, the alarm goes off.

124 | Page
Day 43
Inthis code, we ask the user to input the name of the student and
their marks in the test. First, we check the name input to ensure
that it contains only valid inputs. We use the string library to
check if the input name contains punctuation values or
numbers (digits). If it does, we raise a NameError. If a user
inputs an invalid value, the code will raise a ValueError, which is
handled in the except block. The code only breaks once the user
enters "done." When that happens, the dictionary is returned. We
use the get() method ([Link]) to add values to the dictionary. The
get() method is used to retrieve the existing value for the key
(marks) and adds the new marks to it. If the key doesn't exist, it
initializes it with 0 and adds the marks. We use the while loop to
keep the code running until a valid input is made.

125 | Page
Day 44
There are two functions in this code. The first one appends or
writes the email onto the file. We open the file ([Link]) in
append mode "a" so we do not overwrite content that is
already on the file. If you open a file in append mode, if the
file does not exist, it will be created. We use the escape
character (\n) to ensure that every email is appended to a new
line. Since we are using the with statement, the file will be
automatically closed. The second function opens and reads
the file. Since we are just reading the file, we open the file in
read mode ("r").

126 | Page
Day 45
We are usingthe string module to generate all the elements
that we are looking for in the string. We have created variables
for special characters (specia_cha), numeric characters
(numeric_cha), and the d variable for our dictionary. The
replace() method is used to get rid of all the whitespace
between string elements.

127 | Page
Day 46
Thefirstthing that we did was import pandas. Then we put the
information in a dictionary. The [Link] creates a two-
dimensional table. This is one way you can create a DataFrame
using pandas. You may have figured out another way to create it.

Extra Challenge: Website Data with Pandas


The first thing is to importpandas. Since we are reading from a
website, we need to use theread_html method. The data
obtained from the website is in theform of a list, so we use slicing
[1] to get the part or table that we want.

128 | Page
To get the two columns, here is the code below:

129 | Page
Day 47
Forthischallenge, we import the JSON module. This code
demonstrates how to save a dictionary as JSON data in a file
using [Link](), and how to read the JSON data from the
file and load it back into a dictionary using [Link]().We
write two functions, one to save the file ( save_json) and one to
read the file (read_json). Here are the two functions below:

130 | Page
Day 48
The first step to solving a binary problem is to ensure that the list is
sorted. A binary search does not work on a list that is not sorted. For
this challenge, the first thing you had to do was sort the array or list.
At its most basic, the binary search looks for the middle element in a
list. If the list's middle element is not what you are searching for, it
will check whether the element you are searching for is greater than
or less than the middle element. If it is greater, then it will search
for the middle element of the upper half of the list; if it is less, then
it will search for the middle element of the lower part of the list. This
process is repeated until the element is found. So, it picks a portion
of the list and searches for the middle element. We use the iterative
method for this challenge.

131 | Page
Day 49
Inthis challenge, we are saving the movies to the database. The first
step is to import SQLite and create a database ([Link]). Then we
create a table called "movies" with all the columns that we need (year,
title, and genre). There are two ways to upload data to our database.
The first one is using the command [Link]. This method only
uploads one item at a time. Since we want to upload many items at
once, we use [Link]. To accomplish this, we make a list of
all the movies we want to upload (movies variable). Once we upload, we
need to commit and close to make those changes permanent.

132 | Page
a. Creating a query to see all the movies in the table. First, we connect
back to the database, and then we run the query below:

b. Tosee the movie "Brothers" we add WHERE to our SQL query.


WHERE is a conditional statement.

c. For this query, we want to see movies released in 2009. Here


is the SQL query to make it happen.

133 | Page
d. This question requires that we put multiple conditions in our
query. We need movies in the "drama" and "fantasy" genres. Here
is the query below:

e. To delete the contents of our table we can run this query:

134 | Page
Day 50
The first part of the challenge is to create the backend end of the
app. The backend of the app is powered by Python. With just a
few lines of code, Flask will have the app running. When you
install Flask, you will have to import it into your file. You will
have to import Flask and render_templates. The
render_templates file is used to render or generate our HTML
templates. Below is the script that runs the app. This file is saved
as [Link].

morf ksalf trmoip aklsF etaleptm_redner

ppkasalfigtnaitnatsni#
ppa ksalF __ema_n_

@ppaetuor. /""
f emoh:)(
e runter etalpmerte_dner lm'[Link]'o
d
@ppaetuor. "tuo/b"a
f tuoba:)(
e nruter etamlept_reedrn '[Link]'
d

fi __eman__ == "_i_anm__"
ppa nur gudbe ureT

135 | Page
Let me give a brief overview of what is going on with this project.
Even though I have faith that you have completed this project on
your own using your powerful research skills.
When working on projects, it is recommended to create a virtual
environment. A virtual environment is an environment that holds
all the dependencies for our project. Instead of installing
dependencies such as Flask on the system, you can install them in
the virtual environment that you have created. For this project, I
used Visual Studio Code. I will give you steps that you can use to
create a virtual environment easily in Visual Studio. These
commands are for Windows. Look up other commands if you are
not on Windows.
1. The first step is to go into your c drive and create a folder that
you will use for the project.
2. The second step is to open VSC. Go to File and select Open
Folder on the drop-down menu.
3. Now open the terminal in VSC (click on terminal and select
New terminal) and type the following to create a virtual
environment (highlighted in red in the picture below)
python -m venv myflask

The last part .myflaskis the name of the environment, so you can
name it whatever youwant. On the left side of your screen, Just

136 | Page
below the name of your folder, a new folder name (the name of your
environment) will be added.
4. The fourth step is to activate your virtual environment. Type
the following in your terminal. Type:
.myflask\scripts\activate (highlighted in blue below).Do
you see (.myflask) at the beginning of the next line after the
one highlighted in blue? If you see the name of your virtual
environment there, it means your virtual environment has
been activated.

137 | Page
5. Now that the virtual environment has been activated, we can
add flask to our project. Type "pip install flask" in the terminal.
See the example below.

6. The next step is to activate the interpreter for the project.


Type Ctrl + Shift + P, and it will open a command palette. Click
on "Python select interpreter" and select the recommended
Python interpreter for your project.
7. Now create a Python file for your project called [Link]. On
the top left of VSC, you will see the name of the folder you
created for the project. When you hover your mouse over
the folder, on the right, you will see the option to create a
folder or file. Select a new file and name it [Link]. This is
the file with the Python code above.

138 | Page
8. When you hover over your folder on the left side of the VSC
code again, select Create a folder and name your folder
templates. This is where you will save your HTML file.
Create another folder called "static." This is where you will
save your CSS ("[Link]") and picture files for the
project.
Below are the HTML and CSS codes for the project.

139 | Page
[Link]
% edh"[Link]}en"t%{
conoce} lt%bknt%{
<
<l
m
t<nilk erl tse"leyh"ts ferh iuf'tee{_(alm{lrtcia"rosfn,''sstses)cl'".y=}}
/hdaeh
<ydob
d
<a
e vid alcss noica'ten'r
h h1 lcssa '' emoHegaP /<1h
p
h2 lcssa ennoicar't'2_ athihopmstyTtheiiPsegIdhwhisemath,.neo
rb SMnSTaCHLd </2h
/< >
/<idv>

140 | Page
[Link]
%dh"[Link]}et
e
tl
sm
xt<nilk erl tse"leyh"ts ferh i'uf'teetss{_(almses{lrtcia'lc)"rosfn=y.",}'}
d
/hdaeh
i
<ydob
d
e
<a
n
e vid alcss ennoicart
"
h
%
h1 lcssa "" tuobeAgaP /<1h
{
c
o ytsel "txet-git"ln;anerce: rimsouLmsdrepoilo ,atet m
n sentrocucet rb
o pie,ictdsgiainl
c eremtniodsintbeoudmiasdiorcltoep
e qomailnoegaudraa rb
} em,ioumiunrtidnvaqUnaisdne
l aranlbsetolaixiumlrectooc rb
t eiqostipciulxnaume
[Link]
% dnstrnpeiiuehuaroedtDeurniol
rb
b eutelavtotisvpeles
k [Link]
n ceuiocestxtcaEprncea
rb
t
rptn, uatcdtno iaoedi
%
i
{
t /<
<
p
<
u
/<idv
i
/<ydobe
n
/<thlm
l
no}el%%bk{dc
q
/<thlm
c
no}el%%bk{dc
d
r
u
141 | Page i
e
t
s
c
[Link]
! TCEOPDY lmth
<l gnal=ne""
<m >
<t m rathecs FTU" 8"
h a >tiTel/<eltit>
d t ler eyhtssee"l"t
fa e c)osin=y.''teetss(a'lmses}rtia'lcf",}
e t
e daeh
h
rydobe
>
h l
hdae
/ t
< i dvi c = n''arabv
< l s <> h ) oHem/<a/<>orgtns
k s <> f { tAuob/< >/<gtnsor
n a e l
i /<vidl r r
" s h h
rdaeh
/< n f '
u o e "
f r r r
{ t o
_
/<ydob g '
{ s e
l l n u
tlmth
/< o f
b r (
k t m
n g }
t {
c _
o o
n "
} }
% '
o {
c l
e r
142 | Page
{ a
d t
c "
n r
o o
} '
[Link]
body
dounkgrbac e ercov
dounkgrbac i lur jpgpix. );
ytifjus t en
z ont tercen
c
gdinpad 0%s
ginmar %0 g
e
[Link] extt
m nliga tercen
t izes %02
a
f pto i%10
o okesmitewh
n mtobo %30;
g
ttex ow had sx5p 5px px10 kblac};
i
n
[Link] 2h {xtte gnali tercen
m
t izes %501
a
f pto 0%
r
o brg 262 302 23);
o
n mtobo %50;
r
g ow had sx5p 5px px10 kblac};
ttex
c
i
o
n
[Link]
l
m
owrflove
g endhi
a
dounkgrbac
i -or ol cbrg 22 81 20;)
r
onitipos
n dxefi

o
m wid 0%10
th
a
r
top
r
} c
o
aravb.n
l flo ghtri
at
g
ypladis: ck blo
i
ttex n lig arntece
n col
or :al cor
m
gdinpad x14p x16p
a
ttex nioratecod enon;}
r

143 | Page
The best that you can do is get this code running and try to
understand how everything is working together. Don’t be afraid to
take it apart and add new features. That is how you learn.

144 | Page
Other Books by Author
MasterPythonFundamentals:TheUltimate Guide for Beginners.

Amazon link: [Link]

145 | Page
End

146 | Page

You might also like