25 Basic Exercises of Python for Beginners
Python is a popular high-level programming language used for various applications such as web development, data analysis, and artificial intelligence. If you are a beginner in Python, it is essential to practice writing code to improve your programming skills. In this regard, here are 25 basic practice exercises for Python beginners to solve in PyCharm. These exercises cover fundamental concepts such as data types, control structures, and functions. By completing these exercises, you will become more familiar with the Python syntax and develop your problem-solving abilities.
Exercise 1: Hello World Write a program that prints “Hello, World!” to the console.
print("Hello, World!")
Exercise 2: Input and Output Write a program that prompts the user to enter their name and age, then prints out a message with that information.
name = input("Enter your name: ")
age = input("Enter your age: ")
print(f"Hello {name}, you are {age} years old.")
Exercise 3: Calculation Write a program that calculates the area of a rectangle with a width of 5 and a height of 10.
width = 5
height = 10
area = width * height
print(f"The area of the rectangle is {area}.")
Exercise 4: Lists Write a program that creates a list of numbers from 1 to 5, then prints out each number on a new line.
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
Exercise 5: Conditional Statements Write a program that prompts the user to enter a number and then prints out whether the number is even or odd.
number = int(input("Enter a number: "))
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")
Exercise 6: Looping Write a program that prints the numbers from 1 to 10 using a for loop.
for i in range(1, 11):
print(i)
Exercise 7: Functions Write a program that defines a function called “greet” that takes a name as a parameter and prints out a greeting.
def greet(name):<br> print(f"Hello, {name}!")<br><br>greet("John")
Exercise 8: String Manipulation Write a program that prompts the user to enter a word, then prints out the word reversed.
word = input("Enter a word: ")
reversed_word = word[::-1]
print(reversed_word)<code>
</code>
Exercise 9: Data Types Write a program that creates a dictionary with the keys “name” and “age”, and the values “John” and 25, respectively. Then, print out the dictionary.
person = {"name": "John", "age": 25}
print(person)
Exercise 10: File I/O Write a program that prompts the user to enter a filename, then reads in the contents of that file and prints them out. (Basic Exercises of Python)
filename = input("Enter a filename: ")
with open(filename, "r") as file:
contents = file.read()
print(contents)
Exercise 11: Error Handling Write a program that prompts the user to enter a number, then attempts to convert that number to an integer. If the conversion fails, print an error message.
number = input("Enter a number: ")
try:
number = int(number)
print(f"The number is {number}.")
except ValueError:
print("Error: Not a valid number.")
Exercise 12: Lists and Loops Write a program that creates a list of names, then uses a for loop to print out a greeting for each name.
names = ["Alice", "Bob", "Charlie", "David"]
for name in names:
print(f"Hello, {name}!")
Exercise 13: Random Numbers Write a program that generates a random number between 1 and 10, then prompts the user to guess the number. If the guess is correct, print a congratulatory message. If the guess is incorrect, print a message indicating whether the guess was too high or too low.
import random
number = random.randint(1, 10)
guess = int(input("Guess the number (between 1 and 10): "))
if guess == number:
print("Congratulations, you guessed the number!")
elif guess < number:
print("Sorry, your guess was too low.")
else:
print("Sorry, your guess was too high.")
Exercise 14: Object-Oriented Programming Write a program that defines a class called “Person” with the attributes “name” and “age”. Then, create an instance of the class and print out the attributes.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("John", 25)
print(f"Name: {person.name}, Age: {person.age}")
Exercise 15: Dictionaries and Loops Write a program that creates a dictionary of student names and their corresponding grades. Then, use a for loop to print out each student’s name and grade.
students = {"Alice": 90, "Bob": 85, "Charlie": 80, "David": 95}
for name, grade in students.items():
print(f"{name}: {grade}")
Exercise 16: Sets Write a program that creates two sets of integers, then prints out the intersection and union of the two sets.
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
intersection = set1.intersection(set2)
union = set1.union(set2)
print(f"Intersection: {intersection}")
print(f"Union: {union}")
Exercise 17: Lambda Functions Write a program that defines a lambda function to calculate the square of a number, then uses the function to calculate the squares of the numbers 1 through 5.
square = lambda x: x**2
for i in range(1, 6):
print(square(i))
Exercise 18: Conditional Loops Write a program that prompts the user to enter a password, then continues to prompt the user until they enter the correct password.
password = "password123"
while True:
guess = input("Enter the password: ")
if guess == password:
print("Access granted.")
break
else:
print("Incorrect password. Try again.")
Exercise 19: Modules Write a program that imports the “math” module and uses it to calculate the value of pi.
import math
pi = math.pi
print(f"The value of pi is approximately {pi}.")
Exercise 20: Exception Handling Write a program that prompts the user to enter two numbers, then divides the first number by the second number. Use exception handling to handle the case where the second number is zero.
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
result = num1 / num2
print(f"The result is {result}.")
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
Exercise 21: Calculate the area of a circle:
import math
radius = float(input("Enter the radius of the circle: "))
area = math.pi * radius ** 2
print(f"The area of the circle is {area:.2f}")
Exercise 22: Check if a number is prime or not:
number = int(input("Enter a number: "))
if number > 1:
for i in range(2, int(number/2) + 1):
if (number % i) == 0:
print(f"{number} is not a prime number")
break
else:
print(f"{number} is a prime number")
else:
print(f"{number} is not a prime number")
Exercise 23: Count the number of vowels in a string:
string = input("Enter a string: ")
vowels = "aeiou"
count = 0
for char in string:
if char.lower() in vowels:
count += 1
print(f"The number of vowels in '{string}' is {count}")
Exercise 24: Check if a string is a palindrome or not:
string = input("Enter a string: ")
if string == string[::-1]:
print(f"'{string}' is a palindrome")
else:
print(f"'{string}' is not a palindrome")
Exercise 25: Print the Fibonacci sequence up to a given number:
max_num = int(input("Enter a number: "))
fibonacci_seq = [0, 1]
while fibonacci_seq[-1] < max_num:
fibonacci_seq.append(fibonacci_seq[-1] + fibonacci_seq[-2])
print("Fibonacci sequence:")
for num in fibonacci_seq[:-1]:
print(num, end=", ")
print(fibonacci_seq[-1])
A detailed exercise code for PyCharm beginners
Exercise: Basic Exercises of Python
You are working on a project that requires you to manipulate data from a CSV file. Your task is to write a Python program that reads data from the file, performs some calculations on it, and writes the results to a new file.
You need to write a Python program that performs the following steps:
- Create a new Python file named
data_manipulation.py
. - Import the
csv
module. - Open the file
data.csv
for reading. - Read the contents of the file into a list.
- Calculate the total sales for each salesperson.
- Calculate the average sales for each salesperson.
- Write the results to a new file named
results.csv
. - Close both files.
The data.csv
file contains the following data:
salesperson,sales
Alice,1000
Bob,2000
Charlie,3000
Alice,1500
Bob,2500
Charlie,3500
The results.csv
file should contain the following data:
salesperson,total_sales,average_sales
Alice,2500,1250.0
Bob,4500,2250.0
Charlie,6500,3250.0
Make sure to handle any errors that may occur during the execution of your program.
the PyCharm Python code for the exercise:
import csv
# Open the data.csv file for reading
with open('data.csv', 'r') as f:
reader = csv.reader(f)
# Skip the header row
next(reader)
# Create a dictionary to store the total and count for each salesperson
totals = {}
counts = {}
for row in reader:
salesperson = row[0]
sales = float(row[1])
if salesperson in totals:
totals[salesperson] += sales
counts[salesperson] += 1
else:
totals[salesperson] = sales
counts[salesperson] = 1
# Open the results.csv file for writing
with open('results.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['salesperson', 'total_sales', 'average_sales'])
# Calculate and write the results for each salesperson
for salesperson, total in totals.items():
average = total / counts[salesperson]
writer.writerow([salesperson, total, average])
# Close the files
f.close()
This code reads the data from the data.csv
file, calculates the total sales and average sales for each salesperson, and writes the results to a new file named results.csv
. The code uses the csv
module to read and write the data from and to the CSV files.
Photo by Christina Morillo
Leave a Comment