Write a Python program that calculates the cumulative sum of integers from 0 to 100, prints the sums that are divisible by 5, and terminates execution once the cumulative sum exceeds 200 2. Write a simple number guessing game in Python where the user has to guess a predefined secret number, and the game continues until the correct number is entered.
ScanSolve AI Answer
Step-by-step solution
11 stepsLet's knock this out.
Here are the Python programs for your requests:
1. Cumulative Sum Program
cumulative_sum = 0
print("Cumulative sums divisible by 5 (until sum exceeds 200):")
for i in range(101): # Loop from 0 to 100
cumulative_sum += i
if cumulative_sum % 5 == 0:
print(f"Current cumulative sum: {cumulative_sum}")
if cumulative_sum > 200:
print(f"Cumulative sum {cumulative_sum} exceeded 200. Terminating.")
break
Explanation:
Initialize
cumulative_sumto 0.Loop through integers from 0 to 100 using
range(101).In each iteration, add the current integer
itocumulative_sum.Check if
cumulative_sumis divisible by 5 using the modulo operator (%).If the remainder is 0, print the sum.
Check if
cumulative_sumhas exceeded 200.If it has, print a termination message and use
breakto exit the loop.2. Number Guessing Game
import random secret_number = random.randint(1, 10) # Generates a random number between 1 and 10 # You can also set a fixed secret_number = 7 for example print("Welcome to the Number Guessing Game!") print("I'm thinking of a number between 1 and 10.") while True: try: guess = int(input("Enter your guess: ")) if guess == secret_number: print(f"Congratulations! You guessed the correct number: {secret_number}") break # Exit the loop if the guess is correct else: print("Incorrect guess. Try again!") except ValueError: print("Invalid input. Please enter an integer.")Explanation:
Import the
randommodule to generate a secret number between 1 and 10.Start an infinite loop using
while True, which will continue until explicitly broken.Prompt the user to enter their guess.
The input is converted to an integer. A
try-exceptblock handles potentialValueErrorif the user enters non-numeric input.Compare the
guesswith thesecret_number.If the guess is correct, a congratulatory message is printed, and the
breakstatement terminates the loop, ending the game.If the guess is incorrect, a "Try again!" message is displayed, and the loop continues for another guess.
Still stuck on this one?
Ask a follow-up, and the answer starts from this question.