A great way to improve quickly at programming with Python is to practice with a wide range of exercises and programming challenges. In this article, we give you 10 Python practice exercises to boost your skills.
Practice exercises are a great way to learn Python. Well-designed exercises expose you to new concepts, such as writing different types of loops, working with different data structures like lists, arrays, and tuples, and reading in different file types.
Good exercises should be at a level that is approachable for beginners but also hard enough to challenge you, pushing your knowledge and skills to the next level.
Exercise 1: User Input and Conditional Statements
Create a Python program that interacts with the user to obtain a positive integer. Based on the input, the program will generate and display different messages. If the input is greater than 10, it will print, "Python conditions and loops are a piece of cake." Otherwise, it will print, "I am back to check on my skills!" a number of times equal to the user's input.
Code:
number = int(input("Please enter a number: "))
if number > 10:
print("Python conditions and loops are a piece of cake.")
else:
for i in range(number):
print("I am back to check on my skills!")
In this program, we use the `input()` function to receive user input, convert it to an integer with `int()`, and store it in the variable `number`. Depending on whether `number` is greater than 10 or not, the appropriate message is displayed.
Exercise 2: Lowercase and Uppercase Characters
Given the string "text," which contains a sequence of characters, your objective is to iterate through these characters, count the number of uppercase and lowercase letters, and display the results in the following format:
Code:
LOWERCASE: <count>
UPPERCASE: <count>
To achieve this, you can utilize the `string.islower()` and `string.isupper()` methods to identify lowercase and uppercase characters.
Code:
text = "ABgvddVICJSdkeprsmgn UTPDvndhtuwPOTNRSjfisuRNSUesajdsa"
lowercase_count = 0
uppercase_count = 0
for letter in text:
if letter.islower():
lowercase_count += 1
elif letter.isupper():
uppercase_count += 1
print("LOWERCASE:", lowercase_count)
print("UPPERCASE:", uppercase_count)
In this solution, we initialize two counters, `lowercase_count` and `uppercase_count`, to keep track of the lowercase and uppercase letter counts, respectively. We then iterate through each character in the `text` string and use the `islower()` and `isupper()` methods to increment the respective counters. Finally, we print the results in the specified format.
This code effectively counts and differentiates between uppercase and lowercase letters in the given string.
Exercise 3: Building Triangles
Let's design a function called `is_triangle_possible()` that takes three positive numbers as input and returns `True` if it's possible to form a triangle with these lengths, or `False` otherwise.
Code:
def is_triangle_possible(a, b, c):
return (a + b > c) and (b + c > a) and (c + a > b)
The essence of this function lies in the triangle inequality theorem, which states that the sum of the lengths of any two sides of a triangle must be greater than the length of the remaining side. Hence, for three numbers to create a triangle, all three conditions must be met: `a + b > c`, `b + c > a`, and `c + a > b`.
Exercise 4: Call a Function From Another Function
Let's create two functions in Python: `print_five_times()` and `speak()`. The first function, `print_five_times()`, accepts one parameter, `sentence`, and prints it five times. The second function, `speak(sentence, repeat)`, has two parameters: `sentence`, which is a string of letters, and `repeat`, a Boolean with a default value of `False`. When `repeat` is `False`, the function prints the sentence once. If `repeat` is set to `True`, it calls the `print_five_times()` function.
Code:
def print_five_times(sentence):
for i in range(5):
print(sentence)
def speak(sentence, repeat=False):
if repeat:
print_five_times(sentence)
else:
print(sentence)
This code demonstrates how to create and call functions in Python. It also illustrates the use of a Boolean flag (`repeat`) to control the program's flow. When `repeat` is `True`, `print_five_times()` is invoked, printing the sentence five times. Otherwise, the sentence is printed just once. In Python, using `if repeat` is equivalent to `if repeat == True`.
Exercise 5: Looping and Conditional Statements
Let's create two functions in Python: `print_five_times()` and `speak()`. The first function, `print_five_times()`, accepts one parameter, `sentence`, and prints it five times. The second function, `speak(sentence, repeat)`, has two parameters: `sentence`, which is a string of letters, and `repeat`, a Boolean with a default value of `False`. When `repeat` is `False`, the function prints the sentence once. If `repeat` is set to `True`, it calls the `print_five_times()` function.
Code:
def print_five_times(sentence):
for i in range(5):
print(sentence)
def speak(sentence, repeat=False):
if repeat:
print_five_times(sentence)
else:
print(sentence)
This code demonstrates how to create and call functions in Python. It also illustrates the use of a Boolean flag (`repeat`) to control the program's flow. When `repeat` is `True`, `print_five_times()` is invoked, printing the sentence five times. Otherwise, the sentence is printed just once. In Python, using `if repeat` is equivalent to `if repeat == True`.
Exercise 6: Nested Loops and Conditional Statements
You can define a Python function called `find_censored_words()` that takes a list of strings and a list of special characters as arguments. This function will print all censored words one by one in separate lines. A word is considered censored if it contains at least one character from the `special_chars` list. Here's an example using the provided lists:
Code:
special_chars = ['!', '@', '#', '$', '%', '^', '&', '*']
word_list = ['se#$et', 'Ver*%&$lo', 'di$#^$nt', 'c*%e', 'is', '#%$#@!@#$%^$#']
def find_censored_words(word_list, special_chars):
for word in word_list:
for character in word:
if character in special_chars:
print(word)
break
In this code, the function iterates through each word in the `word_list` and then through each character in the current word. If it finds a character that is in the `special_chars` list, it prints the word and exits the inner loop using `break`. This way, even if a word contains multiple special characters, it's only printed once.
Exercise 7: Lists and Tuples
To create a Python function called `find_short_long_word(words_list)` that returns a tuple of the shortest and longest words in a given list, follow this example:
Code:
def find_short_long_word(words_list):
shortest_word = min(words_list, key=len)
longest_word = max(words_list, key=len)
return (shortest_word, longest_word)
This function utilizes the `min` and `max` functions with the `key` parameter to determine the shortest and longest words based on their lengths. It eliminates the need for manual comparisons and is a concise and efficient way to achieve the desired result.
Code:
words = ['go', 'run', 'play', 'see', 'my', 'stay']
result = find_short_long_word(words)
print(result)
It will return:
('go', 'stay')
The `min` and `max` functions are applied to the list of words based on their lengths, ensuring you get the shortest and longest words efficiently.
Exercise 8: Dictionaries
We provide you with the `test_results` variable, and your task is to iterate through the dictionary and print the names of students who scored less than 45 points.
Code:
test_results = {'Jenny': 50, 'Mathew': 45, 'Joe': 30, 'Peter': 40, 'Agness': 50, 'Samantha': 45, 'John': 20}
for student, score in test_results.items():
if score < 45:
print(student)
In this solution, we demonstrate how to iterate through a dictionary. Dictionaries are valuable data structures in Python, where each key (student's name) is associated with a value (test score). Using `dictionary.items()`, we access key-value pairs in tuples.
The code example iterates through these pairs and assigns the student's name to the `student` variable and their test score to the `score` variable. We then check if the score is less than 45. If the condition is met, we print the student's name.
Exercise 9: More Dictionaries
To count vowels and consonants in a dictionary, we create a function called `consonant_vowels_count(frequencies_dictionary, vowels)` that takes a dictionary with letter frequencies and a list of vowels as arguments. It calculates and prints the total number of consonants and vowels in the following format:
Code:
VOWELS: <vowels>
CONSONANTS: <consonants>
For example, given the input:
frequencies_dictionary = {'a': 2, 's': 1, 'i': 3, 'u': 3, 'm': 4, 'l': 2, 'z': 1, 'n': 3, 'k': 1, 'e': 4, 'y': 2, 'd': 2, 'o': 1}
vowels = ['a', 'e', 'i', 'u', 'o']
The output should be:
VOWELS: 13
CONSONANTS: 16
Here's the Python solution:
vowels = ['a', 'e', 'i', 'u', 'o']
frequencies_dictionary = {'a': 2, 's': 1, 'i': 3, 'u': 3, 'm': 4, 'l': 2, 'z': 1, 'n': 3, 'k': 1, 'e': 4, 'y': 2, 'd': 2, 'o': 1}
def consonant_vowels_count(frequencies_dictionary, vowels):
vowels_count = 0
consonants_count = 0
for key, value in frequencies_dictionary.items():
if key in vowels:
vowels_count += value
else:
consonants_count += value
print("VOWELS:", vowels_count)
print("CONSONANTS:", consonants_count)
In this solution, we iterate through the dictionary items, checking if each letter is in the list of vowels. Based on this, we update the counts for vowels and consonants and print the results in the required format.
Working with dictionaries and lists is a fundamental skill in Python, and this exercise demonstrates how to efficiently process and analyze data stored in these data structures.
Exercise 10: String Encryption
The Caesar Cipher is a straightforward encryption technique that involves shifting each letter in a word to a fixed number of positions down the alphabet. For example, shifting 'word' by one position results in 'xpse', and a two-position shift gives 'yqtf'.
Here's the Python solution:
alphabet = "abcdefghijklmnopqrstuvwxyz"
def cipher(word, shift):
shifted_alphabet = alphabet[shift:] + alphabet[:shift]
new_word = ""
for letter in word:
letter_index = alphabet.index(letter)
new_letter = shifted_alphabet[letter_index]
new_word += new_letter
return new_word
In this implementation, we define the alphabet and create a shifted alphabet using slicing. We then iterate through the input word, find the index of each letter in the alphabet, and replace it with the corresponding shifted letter.
Please note that this implementation works only for lowercase words. If you attempt to encrypt a word with uppercase letters, you'll encounter a ValueError. More advanced solutions using built-in functions like `chr()` and `ord()` can handle both cases. The Caesar Cipher is a fascinating encryption method that you can explore further in courses like "WORD GAMES," which offer more robust solutions and practice exercises to enhance your knowledge.
The World Best Exam Dumps Webiste is Dumpsedu. One of the top site for AZ-900 Exam Dumps. ACP-Sec1 Exam Questions
ACP-Cloud1 Exam Questions
ACA-Developer Exam Questions
ACA-Operator Exam Questions
ACA-Database Exam Questions
PCM Exam Questions