Practicing coding through real-world examples and exercises is one of the best ways to learn and improve your Python skills. This tutorial will present a set of Python practical exercises, ranging from beginner to advanced levels. By completing these exercises, you will reinforce the concepts you’ve learned and gain confidence in applying Python in various situations.
1. Beginner Exercises
These exercises focus on basic Python concepts such as variables, loops, functions, and conditionals. Perfect for those who are new to Python.
1.1 Exercise 1: Temperature Converter
Write a Python program that converts temperatures between Celsius and Fahrenheit. The program should ask the user to input a temperature and the unit (Celsius or Fahrenheit), then convert it to the other unit.
def convert_temperature(temp, unit): if unit == 'C': return (temp * 9/5) + 32 # Celsius to Fahrenheit elif unit == 'F': return (temp - 32) * 5/9 # Fahrenheit to Celsius else: return "Invalid unit" # Example usage temp = float(input("Enter temperature: ")) unit = input("Enter unit (C/F): ").upper() result = convert_temperature(temp, unit) print(f"Converted temperature: {result}")
1.2 Exercise 2: Simple Calculator
Write a Python program that asks the user to enter two numbers and then performs addition, subtraction, multiplication, and division based on the user’s choice.
def calculator(num1, num2, operation): if operation == 'add': return num1 + num2 elif operation == 'subtract': return num1 - num2 elif operation == 'multiply': return num1 * num2 elif operation == 'divide': if num2 != 0: return num1 / num2 else: return "Cannot divide by zero" else: return "Invalid operation" # Example usage num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) operation = input("Enter operation (add, subtract, multiply, divide): ").lower() result = calculator(num1, num2, operation) print(f"Result: {result}")
2. Intermediate Exercises
These exercises involve working with data structures like lists, dictionaries, and loops to perform more complex tasks.
2.1 Exercise 1: Find the Largest Number in a List
Write a Python function that finds the largest number in a list of numbers.
def find_largest_number(numbers): return max(numbers) # Example usage numbers = [10, 24, 3, 14, 52, 7] print("Largest number:", find_largest_number(numbers))
2.2 Exercise 2: Count Vowels in a String
Write a Python function that counts the number of vowels in a given string.
def count_vowels(s): vowels = "aeiou" count = 0 for char in s.lower(): if char in vowels: count += 1 return count # Example usage input_string = input("Enter a string: ") print("Number of vowels:", count_vowels(input_string))
2.3 Exercise 3: Reverse a String
Write a Python function that reverses a given string without using the built-in reverse()
method or slicing.
def reverse_string(s): reversed_s = '' for char in s: reversed_s = char + reversed_s return reversed_s # Example usage input_string = input("Enter a string: ") print("Reversed string:", reverse_string(input_string))
3. Advanced Exercises
These exercises are designed to challenge your problem-solving skills and test your understanding of more advanced Python concepts such as file handling, object-oriented programming, and algorithms.
3.1 Exercise 1: Palindrome Checker
Write a Python program that checks if a given string is a palindrome (reads the same forward and backward). The program should ignore spaces and punctuation.
import re def is_palindrome(s): # Remove spaces and non-alphanumeric characters s = re.sub(r'[^a-zA-Z0-9]', '', s.lower()) return s == s[::-1] # Example usage input_string = input("Enter a string: ") if is_palindrome(input_string): print("The string is a palindrome.") else: print("The string is not a palindrome.")
3.2 Exercise 2: Fibonacci Sequence
Write a Python function that generates the first n
numbers in the Fibonacci sequence.
def fibonacci(n): fib_sequence = [0, 1] for i in range(2, n): fib_sequence.append(fib_sequence[i-1] + fib_sequence[i-2]) return fib_sequence # Example usage n = int(input("Enter the number of terms: ")) print("Fibonacci sequence:", fibonacci(n))
3.3 Exercise 3: File Handling – Read and Write
Write a Python program that reads a text file and counts how many times a specific word appears. Then, the program should write this count to a new file.
def count_word_in_file(file_name, word): with open(file_name, 'r') as file: text = file.read() count = text.lower().count(word.lower()) return count # Example usage file_name = 'sample.txt' word = input("Enter the word to search for: ") count = count_word_in_file(file_name, word) # Writing result to a new file with open('word_count.txt', 'w') as output_file: output_file.write(f"The word '{word}' appears {count} times in {file_name}.\n")
4. Bonus Challenge: Tic-Tac-Toe Game
For an advanced project, you can try implementing a simple command-line Tic-Tac-Toe game. The game should allow two players to play, validate moves, and check for a winner.
def print_board(board): for row in board: print(' | '.join(row)) print("-" * 5) def check_win(board, player): for row in board: if all([cell == player for cell in row]): return True for col in range(3): if all([board[row][col] == player for row in range(3)]): return True if all([board[i][i] == player for i in range(3)]) or all([board[i][2-i] == player for i in range(3)]): return True return False # Example usage: Implementing a Tic-Tac-Toe game can be complex, but it involves: # - A board that is a list of lists (3x3 grid). # - A loop to allow two players to take turns, inputting their moves. # - A function to check for a winner. # - Displaying the board after each move.
Conclusion
By completing these Python practical exercises, you will reinforce your understanding of basic, intermediate, and advanced Python concepts. Whether you are solving beginner-level problems or tackling more complex real-world challenges, practicing consistently will help you become more proficient in Python programming.