简体   繁体   中英

I'm a beginner in python and I'm trynna code a number guessing game. It keeps giving me a math domain error. Any suggestions pls?

import random
import math
n = int(input("Enter a number between 20 and: "))
number = random.randint(20, n)
print("You have only ", round(math.log(20 - n + 1, 2)), "chances to guess the number!")

attempts = 0
while attempts < round(math.log(20 - n + 1, 2)):
    attempts += 1

    trial = int(input("Guess the number!: "))

    if trial == n:
        print("You guessed the number correctly in just ", attempts, "attempts! Well Done")
    elif trial < n:
        print("Your guess is too low, try again!")
    elif trial > n:
        print("Your guess is too high, try again!")

        if attempts >= round(math.log(20 - n + 1, 2)):
            print("You have reached the limit of your number of guesses")
            break

okay the problem is this

(20 - n + 1, 2)

lets say n is 25

20 - 25 = negative 5

I assume you want use to select a number(n) higher that 20

if so its a simple fix of

(n-20 + 1, 2))

so you now get a positive number

make sure you fix this in both the place you have it

you are trying to get log of a number math.log(20 - n + 1, 2) which is Zero or less than zero and in mathematics log of a zero or less than zero is NOT Defined and that's why you are getting ValueError: math domain error

so in math.log(20 - n + 1, 2) and other log s make sure the number 20 - n + 1 is greater than zero >0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM