Dive into Python with Interactive Exercises: A Practical Guide
Welcome to an engaging and hands-on journey into the world of Python programming! This tutorial will walk you through a series of exercises designed to strengthen your understanding of fundamental Python concepts. Whether you are new to programming or looking to refresh your skills, this guide will help you develop practical coding abilities and enhance your problem-solving techniques.
Python is a powerful and versatile language widely used in various domains, including data analysis, web development, automation, and artificial intelligence. By following along with this tutorial, you'll not only enhance your Python skills but also see how programming can solve real-world challenges.
Setting Up in Google Colab
Google Colab is a free, cloud-based platform that allows you to write and execute Python code in a Jupyter notebook environment. Here’s how to get started:
Step 1: Access Google Colab (FREE)
Open Google Colab: Visit Google Colab in your browser.
Sign In: Make sure you are signed in with your Google account.
Step 2: Create a New Notebook
New Notebook: Click on “New Notebook” to create a new Jupyter notebook. You can find this option under the "File" menu or the “+ New Notebook” button on the Colab welcome page.
Step 3: Add Code and Text Cells
Add Code Cells: Click on the “+ Code” button to add code cells where you can paste your Python code.
Add Text Cells: Click on the “+ Text” button to add explanations or instructions using Markdown for formatting.
Step 4: Copy and Paste the Tutorial Code
Copy the following code snippets into separate code cells in your Colab notebook. Make sure to click the +Code button to create a new block for each code snippet.
Snippet 1: Initialize Scoring Dictionary
This snippet initializes a dictionary to keep track of the results for each exercise.
(Leave untouched)
python
# This cell initializes the scoring dictionary to keep track of exercise results. score = dict()
Snippet 2: Exercise 1 - Checking if a Word is Present in Text
Explanation: In this exercise, you'll write a function that searches for a specific word within a given text. The function should return 1 if the word is found and -1 if it is not. This will help you understand string operations and conditional statements in Python. At the end of this article, there is a cheat sheet with the correct completed answer.
Detailed Steps:
What is a Function?: A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. You define a function using the
def
keyword, followed by the function name and parentheses()
. Inside the parentheses, you can specify parameters. For example:def my_function(): # Code to execute pass
Define the Function: The function
is_word_there
should take two arguments:text
(the string to search within) andword
(the string to search for).Search for the Word: Use the
in
operator or methods likefind()
to check if the word is in the text. Thein
operator is used to check if a value exists in a sequence (like a string, list, or tuple). For example:if 'word' in 'This is a word': print('Word found!')
Return the Result: If the word is found, return 1; otherwise, return -1. The
return
statement is used to exit a function and go back to the place from where it was called.
Useful Resources:
Python Conditional Statements
python
def is_word_there(text, word): """ Checks if a specific word is present in the provided text. Returns 1 if the word is found, otherwise returns -1. """ # Add your code here return # Test Case for Exercise 1 text = """ Python is an amazing programming language. Python is also one of the primary languages in the data analysis field""" word = "amazing" try: if is_word_there(text, word) == 1: score['exercise 1'] = 'pass' else: score['exercise 1'] = 'fail' except: score['exercise 1'] = 'fail'
Snippet 3: Exercise 2 - Counting Occurrences of a Word in Text
Explanation: In this exercise, you'll write a function that counts how many times a specific word appears in a given text. The function should return the count. This will help you practice string manipulation and counting. At the end of this article, there is a cheat sheet with the correct completed answer.
Detailed Steps:
Define the Function: The function
count_word
should take two arguments:text
(the string to search within) andword
(the string to search for).Count Occurrences: Use the
count()
method to find how many times the word appears in the text. Thecount()
method returns the number of occurrences of a substring in the given string. For example:text = "Hello world! Hello everyone!" count = text.count("Hello") print(count) # Output: 2
Return the Count: Return the integer count. The
return
statement is used to exit a function and go back to the place from where it was called.
Useful Resources:
python
def count_word(text, word): """ Counts the number of times a specific word appears in the provided text. Returns the count as an integer. """ # Add your code here return # Test Case for Exercise 2 word = "Python" try: if count_word(text, word) == 2: score['exercise 2'] = 'pass' else: score['exercise 2'] = 'fail' except: score['exercise 2'] = 'fail'
Snippet 4: Exercise 3 - Calculating the Area of a Circle
Explanation: In this exercise, you'll write a function to calculate the area of a circle given its radius. This will help you understand basic arithmetic operations and the use of constants in Python. At the end of this article, there is a cheat sheet with the correct completed answer.
Detailed Steps:
Define the Function: The function
get_area_circle
should take one argument:r
(the radius).Calculate the Area: Use the formula
area = π * r^2
(where π can be approximated as 3.1415). To perform this calculation, you'll use the multiplication operator*
and the exponentiation operator**
in Python. For example:area = 3.1415 * r ** 2
Return the Area: Return the calculated area as a float. The
return
statement is used to exit a function and go back to the place from where it was called.
Useful Resources:
python
def get_area_circle(r): """ Calculates the area of a circle given its radius. Returns the area as a float. """ # Add your code here return # Test Case for Exercise 3 try: if ((get_area_circle(5) > 78) and (get_area_circle(5) < 79)): score['exercise 3'] = 'pass' else: score['exercise 3'] = 'fail' except: score['exercise 3'] = 'fail'
Snippet 5: Exercise 4 - Computing Factorial
Explanation: In this exercise, you'll write a function that computes the factorial of a given number. The factorial of a number n is the product of all positive integers up to n. This will help you understand loops and recursion. At the end of this article, there is a cheat sheet with the correct completed answer.
Detailed Steps:
What is a Factorial?: The factorial of a number
n
(denoted asn!
) is the product of all positive integers from 1 ton
. For example,5! = 5 * 4 * 3 * 2 * 1 = 120
.Define the Function: The function
get_factorial
should take one argument:number
.Calculate the Factorial: You can use a loop to compute the factorial. A
for
loop is used to iterate over a sequence (like a range of numbers). For example:factorial = 1 for i in range(1, number + 1): factorial *= i
Return the Factorial: Return the computed factorial as an integer. The
return
statement is used to exit a function and go back to the place from where it was called.
python
def get_factorial(number): """ Calculates the factorial of a given number. Returns the factorial as an integer. """ # Add your code here return # Test Case for Exercise 4 try: if get_factorial(5) == 120: score['exercise 4'] = 'pass' else: score['exercise 4'] = 'fail' except: score['exercise 4'] = 'fail'
Snippet 6: Exercise 5 - Summing Elements of Two Lists
Explanation: In this exercise, you'll write a function that sums the elements of two lists element-wise. This will help you practice list operations and iteration. At the end of this article, there is a cheat sheet with the correct completed answer.
Detailed Steps:
Define the Function: The function
sum_lists
should take two arguments:list1
andlist2
.Sum Elements: Use a loop to iterate through both lists and sum their elements. A
for
loop is used to iterate over a sequence. For example:summed_list = [] for i in range(len(list1)): summed_list.append(list1[i] + list2[i])
Return the Sum: Return a new list containing the sums of the corresponding elements. The
return
statement is used to exit a function and go back to the place from where it was called.
Useful Resources:
Python Lists
Python For Loops
python
def sum_lists(list1, list2): """ Sums the elements of two lists elementwise. Returns a new list with the summed elements. """ # Add your code here return # Test Case for Exercise 5 try: if sum_lists([1, 2, 3], [10, 11, 12]) == [11, 13, 15]: score['exercise 5'] = 'pass' else: score['exercise 5'] = 'fail' except: score['exercise 5'] = 'fail'
Snippet 7: Exercise 6 - Checking if a Number is Even
Explanation: In this exercise, you'll write a function to check if a given number is even. This will help you understand conditional statements and the modulus operator. At the end of this article, there is a cheat sheet with the correct completed answer.
Detailed Steps:
Define the Function: The function
isEven
should take one argument:number
.Check Evenness: Use the modulus operator
%
to check if the number is divisible by 2. The modulus operator returns the remainder of a division. For example:if number % 2 == 0: # Number is even else: # Number is odd
Return the Result: Return 1 if the number is even, otherwise return -1. The
return
statement is used to exit a function and go back to the place from where it was called.
Useful Resources:
Python Modulus Operator
python
def isEven(number): """ Checks if a given number is even. Returns 1 if even, otherwise returns -1. """ # Add your code here return # Test Case for Exercise 6 try: if isEven(5) == -1: score['exercise 6'] = 'pass' else: score['exercise 6'] = 'fail' except: score['exercise 6'] = 'fail'
Snippet 8: Exercise 7 - Checking if a Number is Odd
Explanation: In this exercise, you'll write a function to check if a given number is odd. This will help you further practice conditional statements and the modulus operator. At the end of this article, there is a cheat sheet with the correct completed answer.
Detailed Steps:
Define the Function: The function
isOdd
should take one argument:number
.Check Oddness: Use the modulus operator
%
to check if the number is not divisible by 2. The modulus operator returns the remainder of a division. For example:if number % 2 != 0: # Number is odd else: # Number is even
Return the Result: Return 1 if the number is odd, otherwise return -1. The
return
statement is used to exit a function and go back to the place from where it was called.
Useful Resources:
Python Modulus Operator
python
def isOdd(number): """ Checks if a given number is odd. Returns 1 if odd, otherwise returns -1. """ # Add your code here return # Test Case for Exercise 7 try: if isOdd(5) == 1: score['exercise 7'] = 'pass' else: score['exercise 7'] = 'fail' except: score['exercise 7'] = 'fail'
Snippet 9: Exercise 8 - Computing Standard Deviation
Explanation: In this exercise, you'll write a function to compute the standard deviation of a list of numbers. Standard deviation measures the amount of variation or dispersion in a set of values. At the end of this article, there is a cheat sheet with the correct completed answer.
Detailed Steps:
What is Standard Deviation?: Standard deviation is a measure of how spread out the numbers in a data set are. The formula for standard deviation is:
Define the Function: The function
compute_stdev
should take one argument:a_list
.Calculate the Mean: First, compute the mean (average) of the list. The mean is the sum of all values divided by the number of values. For example:
mean = sum(a_list) / len(a_list)
Calculate the Variance: Compute the variance by summing the squared differences between each value and the mean, then dividing by the number of values minus one. For example:
variance = sum((x - mean) ** 2 for x in a_list) / (len(a_list) - 1)
Calculate the Standard Deviation: Take the square root of the variance to get the standard deviation. You can use the
**
operator or themath.sqrt
function. For example:import math stdev = math.sqrt(variance)
Return the Standard Deviation: Return the computed standard deviation as a float. The
return
statement is used to exit a function and go back to the place from where it was called.
Useful Resources:
Python Lists
Python Sum Function
python
def compute_stdev(a_list): """ Calculates the standard deviation of a list of numbers. Returns the standard deviation as a float. """ # Add your code here return # Test Case for Exercise 8 try: if (compute_stdev([5, 4, 8, 3]) > 2.160) and (compute_stdev([5, 4, 8, 3]) < 2.162): score['exercise 8'] = 'pass' else: score['exercise 8'] = 'fail' except: score['exercise 8'] = 'fail'
Snippet 10: Exercise 9 - Finding the Range of a List
Explanation: In this exercise, you'll write a function to find the range of a list of numbers. The range is the difference between the maximum and minimum values in the list. At the end of this article, there is a cheat sheet with the correct completed answer.
Detailed Steps:
Define the Function: The function
compute_range
should take one argument:a_list
.Find the Maximum and Minimum Values: Use the
max()
andmin()
functions to find the maximum and minimum values in the list. For example:max_value = max(a_list) min_value = min(a_list)
Calculate the Range: Subtract the minimum value from the maximum value to get the range. For example:
range_value = max_value - min_value
Return the Range: Return the computed range as a float or integer. The
return
statement is used to exit a function and go back to the place from where it was called.
Useful Resources:
Python Lists
Python Max Function
Python Min Function
python
def compute_range(a_list): """ Calculates the range of a list of numbers. Returns the range as a float or integer. """ # Add your code here return # Test Case for Exercise 9 try: if compute_range([2, 5, 8, 1]) == 7: score['exercise 9'] = 'pass' else: score['exercise 9'] = 'fail' except: score['exercise 9'] = 'fail'
Snippet 11: Exercise 10 - Finding Common Words in Two Texts
Explanation: In this exercise, you'll write a function to find common words in two texts. This will help you work with string and set operations. At the end of this article, there is a cheat sheet with the correct completed answer.
Detailed Steps:
What is a Set?: A set is a collection of unique elements. Sets are unordered, and you can perform operations like unions, intersections, and differences on them. For example:
set1 = {"apple", "banana", "cherry"} set2 = {"cherry", "date", "fig"} common = set1.intersection(set2) print(common) # Output: {'cherry'}
Define the Function: The function
get_common_words
should take two arguments:text1
andtext2
.Convert Texts to Sets: Convert each text to a set of words. Use the
split()
method to break the text into words, and then use theset()
function to create sets. For example:set1 = set(text1.split()) set2 = set(text2.split())
Find Common Words: Use the
intersection()
method to find common words between the two sets. For example:common_words = set1.intersection(set2)
Return the Common Words: Return the common words as a list. Use the
list()
function to convert the set to a list. Thereturn
statement is used to exit a function and go back to the place from where it was called.
Useful Resources:
Python Sets
Python String split() Method
python
def get_common_words(text1, text2): """ Finds common words occurring in both texts. Returns a list of common words. """ # Add your code here return # Test Case for Exercise 10 text1 = """ Python is an amazing programming language. It is also one of the primary languages in the data analysis field""" text2 = "Python is a genus of constricting snakes in the Pythonidae family. You can find amazing pictures of python snakes in this link" try: if sorted(get_common_words(text1, text2)) == sorted(['amazing', 'of', 'the', 'is', 'python', 'in']): score['exercise 10'] = 'pass' else: score['exercise 10'] = 'fail' except: score['exercise 10'] = 'fail'
Snippet 12: Calculate the Total Score
This snippet calculates the total score based on the results of the exercises. (Do not edit)
python
# Calculate the Total Score total_score = 0 for result in score.values(): if result == 'pass': total_score += 10 print('Your total score is:', total_score)
Step 5: Save and Download Your Notebook
Save Your Work: Google Colab automatically saves your work to your Google Drive. However, it's good practice to click on "File" and then "Save a copy in Drive" to ensure your progress is saved.
Download Your Notebook: Once you've completed the exercises, you can download the notebook by clicking on "File" > "Download" > "Download .ipynb".
Benefits of Learning Python Through Practical Exercises
Real-World Skills: By following along with these exercises, you'll gain practical programming skills that can be directly applied to real-world situations.
Critical Thinking: Each exercise encourages you to think critically and develop problem-solving skills.
Versatility: Python is a versatile language used in various fields such as data science, web development, automation, and more. Mastering Python opens up numerous career opportunities.
Community Support: Python has a large and active community. By learning Python, you can easily find resources, tutorials, and support from other programmers.
By completing this tutorial, you'll build a strong foundation in Python programming and be better prepared to tackle more advanced topics and projects. Happy coding!
Cheat Sheet: Completed Answers for Exercises
Here's a quick reference cheat sheet with the correct completed answers for each exercise. Use this to verify your solutions or if you get stuck.
# Initialize Scoring Dictionary score = dict() # Exercise 1: Checking if a Word is Present in Text def is_word_there(text, word): if word in text: return 1 else: return -1 # Exercise 2: Counting Occurrences of a Word in Text def count_word(text, word): return text.count(word) # Exercise 3: Calculating the Area of a Circle def get_area_circle(r): pi = 3.1415 area = pi * r ** 2 return area # Exercise 4: Computing Factorial def get_factorial(number): factorial = 1 for i in range(1, number + 1): factorial *= i return factorial # Exercise 5: Summing Elements of Two Lists def sum_lists(list1, list2): summed_list = [] for i in range(len(list1)): summed_list.append(list1[i] + list2[i]) return summed_list # Exercise 6: Checking if a Number is Even def isEven(number): if number % 2 == 0: return 1 else: return -1 # Exercise 7: Checking if a Number is Odd def isOdd(number): if number % 2 != 0: return 1 else: return -1 # Exercise 8: Computing Standard Deviation def compute_stdev(a_list): mean = sum(a_list) / len(a_list) variance = sum((x - mean) ** 2 for x in a_list) / (len(a_list) - 1) stdev = variance ** 0.5 return stdev # Exercise 9: Finding the Range of a List def compute_range(a_list): max_value = max(a_list) min_value = min(a_list) range_value = max_value - min_value return range_value # Exercise 10: Finding Common Words in Two Texts def get_common_words(text1, text2): set1 = set(text1.split()) set2 = set(text2.split()) common_words = set1.intersection(set2) return list(common_words) # Calculate the Total Score total_score = 0 for result in score.values(): if result == 'pass': total_score += 10 print('Your total score is:', total_score)
This cheat sheet provides you with the correct answers to all the exercises in the tutorial. Use it wisely to check your work and learn from any mistakes. Happy coding!