0

Python

Why is my code not running properly? Can you guys help me solve this problem https://sololearn.com/compiler-playground/c5yRKidYU8Fi/?ref=app

12th Jul 2024, 6:58 PM
AnnDell
AnnDell - avatar
3 odpowiedzi
+ 2
IMPROVEMENTS: 1. Direct import: - "from random import randint" is used to import the randint function directly 2. Game loop: - The outer "while True" loop keeps the game running until the user decides to quit. - The "if play_game != 'y': break" condition checks if the user wants to play again and exits the loop if not. 3. Guess loop: - The inner while True loop handles the guessing process - Included exception check: The "try-except" block ensures that the user inputs a valid integer. - The "continue_game" input allows the user to exit the guessing loop.
12th Jul 2024, 7:53 PM
#Meatloaf
#Meatloaf - avatar
+ 1
Your code works fine. But Sololearns python compiler requires all inputs at the start. On seperate lines. 10 30 20 50 40 60 50 80 70 100 90
12th Jul 2024, 7:11 PM
Chris Coder
Chris Coder - avatar
+ 1
I agree with Chris Coder, anyways here's a refactored version of your code: from random import randint def main(): while True: play_game = input("Enter 'Y' to play the game: ").strip().lower() if play_game != 'y': break answer = randint(1, 100) counter = 0 while True: try: try_guess = int(input("Guess a number from 1 to 100: ")) counter += 1 if try_guess < answer: print('The number is too low.') elif try_guess > answer: print('The guess is too large.') else: print(f"Congratulations! You've guessed the number in {counter} tries.") break except ValueError: print("Please enter a valid number.") continue_game = input("Do you want to continue guessing? (y/n): ").strip().lower() if continue_game != 'y': break
12th Jul 2024, 7:41 PM
#Meatloaf
#Meatloaf - avatar