[go: up one dir, main page]

0% found this document useful (0 votes)
254 views5 pages

Python Exercises with Solutions

python learning

Uploaded by

rohansalunke643
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
254 views5 pages

Python Exercises with Solutions

python learning

Uploaded by

rohansalunke643
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming Exercises with Solutions - Retry

1. Birthday Invitations:

Write a Python program to send birthday invitations to your friends:

- Create a list of 5 friends' names (e.g., 'Alice', 'Bob', 'Charlie', 'Dana', 'Eve').

- Use a for loop to go through each friend's name in the list.

- Print a message for each friend: 'Hi <name>, you are invited to my birthday party!'

# Solution

friends = ['Alice', 'Bob', 'Charlie', 'Dana', 'Eve']

for friend in friends:

print(f"Hi {friend}, you are invited to my birthday party!")

2. Counting Apples in Baskets:

Write a Python program to count the total number of apples in multiple baskets:

- Assume you have 5 baskets, each containing a different number of apples (e.g., [5, 8, 3, 10,

7]).

- Use a for loop to add up the apples from all baskets.

- At the end, print: 'The total number of apples is: <total_apples>'.

# Solution

baskets = [5, 8, 3, 10, 7]

total_apples = 0

for apples in baskets:

total_apples += apples

print(f"The total number of apples is: {total_apples}")

3. Greeting Each Classmate:

Write a Python program to greet your classmates individually:


- Create a list of 5 classmates' names (e.g., 'John', 'Sarah', 'Mike', 'Anna', 'Chris').

- Use a for loop to go through each name in the list.

- Print a greeting message for each classmate: 'Hello <name>, good to see you!'

# Solution

classmates = ['John', 'Sarah', 'Mike', 'Anna', 'Chris']

for classmate in classmates:

print(f"Hello {classmate}, good to see you!")

4. Daily Water Intake Tracker:

Write a Python program to track your daily water intake for a week and check if you met your

daily goal of 2 liters:

- Create a list with the amount of water you drank each day for 7 days (e.g., [2.5, 1.8, 2.0, 1.5,

2.2, 2.0, 2.1]).

- Use a for loop to go through each day's water intake.

- For each day, print:

- 'Day <day_number>: You drank enough water!' if the intake is 2 liters or more.

- 'Day <day_number>: Drink more water tomorrow!' if the intake is less than 2 liters.

# Solution

water_intake = [2.5, 1.8, 2.0, 1.5, 2.2, 2.0, 2.1]

for day, intake in enumerate(water_intake, start=1):

if intake >= 2.0:

print(f"Day {day}: You drank enough water!")

else:

print(f"Day {day}: Drink more water tomorrow!")

5. Magic Numbers:

Write a Python program to display the first 5 multiples of a number entered by the user:
- Ask the user to input a number.

- Use a for loop to generate and print the first 5 multiples of the number.

- For example, if the user enters 3, the program should print:

The first 5 multiples of 3 are:

12

15

# Solution

number = int(input("Enter a number: "))

print(f"The first 5 multiples of {number} are:")

for i in range(1, 6):

print(number * i)

6. Collecting Coins:

Write a Python program to count the number of coins in 4 treasure chests:

- Create a list with the number of coins in each treasure chest (e.g., [50, 120, 90, 30]).

- Use a for loop to print how many coins each chest contains, with the message:

'Treasure chest <chest_number> contains <coins> coins.'

# Solution

treasure_chests = [50, 120, 90, 30]

for chest_number, coins in enumerate(treasure_chests, start=1):

print(f"Treasure chest {chest_number} contains {coins} coins.")

7. Guessing Game for Secret Numbers:

Write a Python program to check if a list of guesses contains the secret number:
- Define a secret number (e.g., 7).

- Create a list of guesses made by the user (e.g., [3, 5, 7, 9, 11]).

- Use a for loop to go through each guess in the list.

- Print:

- 'Guess <guess>: Correct!' if the guess matches the secret number.

- 'Guess <guess>: Wrong, try again.' if it does not match.

# Solution

secret_number = 7

guesses = [3, 5, 7, 9, 11]

for guess in guesses:

if guess == secret_number:

print(f"Guess {guess}: Correct!")

else:

print(f"Guess {guess}: Wrong, try again.")

8. Candy Distribution:

Write a Python program to distribute candies equally among 3 children:

- Assume you have 15 candies in total.

- Use a for loop to print how many candies each child gets, with the message:

'Child <child_number> gets <candies_per_child> candies.'

# Solution

total_candies = 15

children = 3

candies_per_child = total_candies // children

for child in range(1, children + 1):

print(f"Child {child} gets {candies_per_child} candies.")


9. Star Ratings:

Write a Python program to display a 5-star rating system for a product:

- Use a for loop to print one additional star (*) in each line.

- The final output should look like this:

**

***

****

*****

# Solution

for i in range(1, 6):

print('*' * i)

10. Days Until Vacation:

Write a Python program to count down the days until a vacation starts:

- Assume you have 5 days left until vacation.

- Use a for loop to print:

'5 days left...', '4 days left...', and so on, until it reaches: 'Vacation starts now!'.

# Solution

days_left = 5

for day in range(days_left, 0, -1):

print(f"{day} days left...")

print("Vacation starts now!")

Common questions

Powered by AI

A Python program uses integer division to calculate how many candies each child receives. By dividing the total number of candies by the number of children using the '//' operator, it ensures each child gets an equal share with a message indicating the distribution: "Child <child_number> gets <candies_per_child> candies." .

For loops in Python enable systematic iteration over lists, which can be applied to generate personalized greetings for each individual in contexts like classrooms or social settings. By iterating over a list, the loop prints custom messages for each student (e.g., "Hello <name>, good to see you!"), emphasizing automation and personalization in communication .

Python effectively sums quantities by using a for loop to iterate over a list of apple counts from different baskets. It accumulates the total using a running sum variable, demonstrating efficient use of loops and variable updates for tallying items in collections .

The enumerate function aids iteration over indexed data by providing both the index and the value directly within the loop. In tasks like tracking treasure chests, 'enumerate' allows referencing the chest number alongside its coin count (e.g., "Treasure chest <chest_number> contains <coins> coins."), simplifying access to both the index and value for loop operations .

The program exemplifies iterative decrementing by starting from a set number of days and using a loop to decrease this number, printing a message each iteration until reaching zero. This exemplifies the concept by showcasing a decreasing loop counter that results in the sequence "5 days left... " until "Vacation starts now!" which provides a practical demonstration of for-loop usage in countdowns .

A Python program can track daily water intake by creating a list with daily amounts and using a for loop to iterate through each day's intake. It checks if each day's intake meets the goal of 2 liters, printing a message of success or the need to drink more, such as "Day <day_number>: You drank enough water!" or "Day <day_number>: Drink more water tomorrow!" .

Using Python to find the first five multiples of a user-entered number gives insight into iterating over a range and dynamically handling user inputs. The program prompts the user for a number, then calculates and prints the first five multiples by looping from 1 to 5, enhancing understanding of loops and basic arithmetic operations in Python .

The program uses a for loop to incrementally build a visual representation of star ratings by printing increasing numbers of '*' on each line. This approach effectively demonstrates loop iteration with output modification, creating a basic yet impactful visual sequence (*, **, ***, ****, *****).

The logical approach involves iterating through a list of daily water intakes using a loop and checking each day's value against the 2-liter goal. The program employs a conditional check within the loop to print distinctive messages based on whether the day's intake meets the requirement, assessing success daily and collectively over the week .

Python handles conditional logic for guessing a secret number by looping through each guess in a list, using an if-else statement to check if the guess matches the secret number. It outputs a specific message for correct and incorrect guesses, demonstrating Python's control flow features with conditions .

You might also like