Code Practice Edhesive import random a = random.

Code Practice Edhesive import random a = random.randint(1, 11) b = random.randint(1, 11) print(“What is: ” + str(a) + ” X ” + str(b) + “?”) ans = int(input(“Your answer: “)) if (a * b == ans): print(“Correct!”) else: print(“Incorrect!”) It says int(input(“Your answer: “)) is incorrect and is highlighted red.
2.5 Code Practice Edhesive import random a = random.randint(1, 11) b = random.randint(1, 11) print(“What is: ” + str(a) + ” X ” + str(b) + “?”) ans = int(input(“Your answer: “)) if (a * b == ans): print(“Correct!”) else: print(“Incorrect!”) It says int(input(“Your answer: “)) is incorrect and is highlighted red.

The Correct Answer and Explanation is:

✅ Corrected Code:

import random

a = random.randint(1, 11)
b = random.randint(1, 11)

print("What is: " + str(a) + " X " + str(b) + "?")

try:
    ans = int(input("Your answer: "))
    if a * b == ans:
        print("Correct!")
    else:
        print("Incorrect!")
except ValueError:
    print("Please enter a valid number.")

📚 Explanation (300+ words):

The original code is mostly correct, but if you’re working in Edhesive’s online coding environment, there may be restrictions or formatting requirements that cause the line ans = int(input("Your answer: ")) to raise an error, especially if non-integer input is entered, or if the environment uses a modified version of Python (like Python 3.6 with limited features or modified input/output handling).

Let’s break it down:

1. Purpose of the Code

This code is a simple multiplication quiz. It randomly generates two integers between 1 and 11, asks the user to multiply them, takes their input, and checks if the answer is correct.

2. Possible Issue

The line:

ans = int(input("Your answer: "))

may throw an error if the user enters a non-integer, like a letter or empty input. Python’s int() function only works on valid numerical strings (like "5"). If the user types something like "five" or presses Enter without typing anything, it raises a ValueError.

3. Why Use try-except?

To make the program more robust and user-friendly, we wrap the input line with a try-except block. This way, if the user enters something invalid, we can show a helpful message instead of crashing the program.

Example:

try:
    ans = int(input("Your answer: "))
except ValueError:
    print("Please enter a valid number.")

4. Environment-Specific Constraints

If Edhesive is flagging the line in red, it might also be due to:

  • Required use of raw_input() in older Python versions (Python 2).
  • Limited console interaction support.
  • An internal error unrelated to your syntax.

If you’re using Edhesive with Python 3, the corrected code above should work. But if it’s Python 2, use raw_input() instead:

ans = int(raw_input("Your answer: "))

5. Best Practices

  • Always validate user input.
  • Avoid crashing your program with unexpected inputs.
  • Give clear instructions and feedback.
Scroll to Top