10 Essential Python Exercises
Improve your skills with these practical examples.
Introduction
Practicing Python is essential to mastering the language. In this article, we present ten Python problems to help you enhance your skills. Each problem comes with a full code solution and detailed explanation, designed to help you understand the logic behind the code.
Python’s clear syntax makes it an ideal language for beginners. This article will guide you through ten diverse Python practice problems, each crafted to reinforce your understanding of different concepts. The exercises we present here are specifically chosen to cover a variety of fundamental topics.
As the saying goes, practice makes perfect, and learning Python is no different. Whether you aim to develop software, explore data science, or automate tasks, practicing coding is vital.
Let’s dive into these exercises and boost our Python skills! 🐍💡
“Did you know that you can clap up to 50 times per article? Well now you do! If you found this article helpful, please consider clapping and following me for more insights. Your support is greatly appreciated!” 😊
Interested in more Python content? Feel free to explore my Medium Lists!
Exercise 1: Determine if a Number is Positive, Negative, or Zero
Exercise
Write a Python program that asks the user to enter a number and determines if the number is positive, negative, or zero.
Solution
number = float(input("Enter a number: "))
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
Explanation
This program prompts the user to enter a number and then uses an if-else statement to check whether the number is positive, negative, or zero. The float()
function ensures that the input is treated as a floating-point number. The conditions number > 0
, number < 0
, and the else
statement cover all possible scenarios for the input number.
Exercise 2: Check Even or Odd
Exercise
Write a Python program that asks the user to enter a number and determines if the number is even or odd.
Solution
number = int(input("Enter a number: "))
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
Explanation
This program prompts the user to enter a number and then checks if the number is even or odd using the modulus operator %
. If the remainder when dividing the number by 2 is zero, the number is even. Otherwise, it is odd.
Exercise 3: Find the Largest of Three Numbers
Exercise
Write a Python program that asks the user to enter three numbers and determines the largest of the three.
Solution
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
if num1 >= num2 and num1 >= num3:
print("The largest number is", num1)
elif num2 >= num1 and num2 >= num3:
print("The largest number is", num2)
else:
print("The largest number is", num3)
Explanation
This program prompts the user to enter three numbers and then uses if-else statements to compare them. It checks if the first number is greater than or equal to the other two, then checks if the second number is greater than or equal to the other two, and finally, if neither condition is met, it concludes that the third number is the largest.
Curious about more Python articles? No need to fret — I’ve got you covered! 🐍📚
Exercise 4: Check if a String is a Palindrome
Exercise
Write a Python program that asks the user to enter a string and checks if the string is a palindrome (reads the same forward and backward).
Solution
string = input("Enter a string: ")
if string == string[::-1]:
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
Explanation
This program prompts the user to enter a string and then checks if the string is a palindrome by comparing the string to its reverse. The slicing notation [::-1]
is used to reverse the string. If the original string matches its reverse, it is a palindrome; otherwise, it is not.
Exercise 5: Calculate the Factorial of a Number
Exercise
Write a Python program that asks the user to enter a non-negative integer and calculates the factorial of that number.
Solution
number = int(input("Enter a non-negative integer: "))
factorial = 1
if number < 0:
print("Factorial is not defined for negative numbers.")
else:
for i in range(1, number + 1):
factorial *= i
print(f"The factorial of {number} is {factorial}.")
Explanation
This program prompts the user to enter a non-negative integer and calculates its factorial using a for loop. The loop multiplies the current value of factorial
by each number from 1 to the input number. If the input number is negative, the program prints a message indicating that the factorial is not defined for negative numbers.
Exercise 6: Find the Sum of Digits in an Integer
Exercise
Write a Python program that asks the user to enter an integer and calculates the sum of its digits.
Solution
number = input("Enter an integer: ")
sum_of_digits = 0
for digit in number:
sum_of_digits += int(digit)
print(f"The sum of the digits in {number} is {sum_of_digits}.")
Explanation
This program prompts the user to enter an integer and calculates the sum of its digits by iterating through each character in the string representation of the number. Each character is converted back to an integer and added to sum_of_digits
.
Exercise 7: Print Fibonacci Sequence up to n Terms
Exercise
Write a Python program that asks the user to enter a positive integer n and prints the first n terms of the Fibonacci sequence.
Solution
n = int(input("Enter a positive integer: "))
a, b = 0, 1
if n <= 0:
print("Please enter a positive integer.")
else:
print("Fibonacci sequence:")
for _ in range(n):
print(a, end=' ')
a, b = b, a + b
Explanation
This program prompts the user to enter a positive integer n
and prints the first n
terms of the Fibonacci sequence. The sequence starts with 0 and 1, and each subsequent term is the sum of the previous two terms. The program uses a for loop to generate and print the terms.
Exercise 8: Count Vowels in a String
Exercise
Write a Python program that asks the user to enter a string and counts the number of vowels (a, e, i, o, u) in the string.
Solution
string = input("Enter a string: ")
vowels = "aeiouAEIOU"
count = 0
for char in string:
if char in vowels:
count += 1
print(f"The number of vowels in the string is {count}.")
Explanation
This program prompts the user to enter a string and counts the number of vowels by iterating through each character in the string and checking if it is a vowel. The program maintains a count of vowels and prints the total at the end.
Exercise 9: Check for Prime Number
Exercise
Write a Python program that asks the user to enter a positive integer and checks if the number is a prime number.
Solution
number = int(input("Enter a positive integer: "))
is_prime = True
if number <= 1:
is_prime = False
else:
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
is_prime = False
break
if is_prime:
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")
Explanation
This program prompts the user to enter a positive integer and checks if the number is prime. A number is considered prime if it is greater than 1 and has no divisors other than 1 and itself. The program uses a for loop to check for divisors from 2 up to the square root of the number. If a divisor is found, the number is not prime.
Exercise 10: Find the GCD of Two Numbers
Exercise
Write a Python program that asks the user to enter two positive integers and calculates their greatest common divisor (GCD).
Solution
def gcd(a, b):
while b:
a, b = b, a % b
return a
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = gcd(num1, num2)
print(f"The GCD of {num1} and {num2} is {result}.")
Explanation
This program defines a function gcd
that calculates the greatest common divisor (GCD) of two numbers using the Euclidean algorithm. The user is prompted to enter two positive integers, and the program prints their GCD. The Euclidean algorithm repeatedly replaces the larger number by the remainder of dividing the larger number by the smaller number until the remainder is zero. The last non-zero remainder is the GCD.
Are you interested in more SQL and Database content? Click here to check out my list on Medium.
Conclusion
These ten exercises are designed to enhance your Python programming skills by covering a variety of fundamental concepts. From decision-making with if-else statements to working with loops and functions, each problem provides a practical way to practice and reinforce your understanding.
Regular practice is crucial for mastering Python or any programming language. By solving different types of problems, you not only become familiar with syntax and functions but also develop problem-solving skills that are essential for real-world applications. Don’t hesitate to experiment with the code and explore different solutions to the problems.
Python is a powerful and versatile language that is widely used in various fields, including web development, data analysis, artificial intelligence, and more. By dedicating time to practice and continuously challenging yourself with new problems, you’ll be well on your way to becoming proficient in Python and opening up numerous opportunities in the tech industry.
Happy coding!
Eager to enhance your data manipulation prowess? Dive into NumPy for numerical operations and Pandas for data analysis! Supercharge your data science toolkit and computational skills with these powerful Python libraries!
Final Words:
Thank you for taking the time to read my article.
This article was first published on medium by CyCoderX.
Hey There! I’m CyCoderX, a data engineer who loves crafting end-to-end solutions. I write articles about Python, SQL, AI, Data Engineering, lifestyle and more!
Join me as we explore the exciting world of tech, data and beyond!
For similar articles and updates, feel free to explore my Medium profile
If you enjoyed this article, consider following for future updates.
Interested in Python content and tips? Click here to check out my list on Medium.
Interested in more SQL, Databases and Data Engineering content? Click here to find out more!
Happy Coding!
What did you think about this article? If you found it helpful or have any feedback, I’d love to hear from you in the comments below!
Please consider supporting me by:
- Clapping 50 times for this story
- Leaving a comment telling me your thoughts
- Highlighting your favorite part of the story
Let me know in the comments below … or above, depending on your device 🙃
Python’s Gurus🚀
Thank you for being a part of the Python’s Gurus community!
Before you go:
- Be sure to clap x50 time and follow the writer ️👏️️
- Follow us: Newsletter
- Do you aspire to become a Guru too? Submit your best article or draft to reach our audience.