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.

Computer Science

ScanSolve AI Answer

Step-by-step solution

11 steps

Let'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:

  1. Initialize cumulative_sum to 0.

  2. Loop through integers from 0 to 100 using range(101).

  3. In each iteration, add the current integer i to cumulative_sum.

  4. Check if cumulative_sum is divisible by 5 using the modulo operator (%).

    If the remainder is 0, print the sum.

  5. Check if cumulative_sum has exceeded 200.

    If it has, print a termination message and use break to 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:

  6. Import the random module to generate a secret number between 1 and 10.

  7. Start an infinite loop using while True, which will continue until explicitly broken.

  8. Prompt the user to enter their guess.

    The input is converted to an integer. A try-except block handles potential ValueError if the user enters non-numeric input.

  9. Compare the guess with the secret_number.

  10. If the guess is correct, a congratulatory message is printed, and the break statement terminates the loop, ending the game.

  11. If the guess is incorrect, a "Try again!" message is displayed, and the loop continues for another guess.

Was this helpful?

Still stuck on this one?

Ask a follow-up, and the answer starts from this question.

Got a different question?Ask your own question