首页 > 解决方案 > 显式基整数转换错误

问题描述

我只是花了最后一个小时制作你在下面看到的东西。这有点像第一个我真正使用头脑中的东西的项目。我在网上看到的关于这个问题的所有内容我都不太了解,因为我真的不知道发生了什么。我有点跳过了很多基本的东西,但我觉得我做错了函数业务。有人可以解释我的代码哪里出错了吗?

代码:

import random

uname = input("Whats up! What is your username? ")

print("Hiya " + uname + ". Cool name ;)")

global guess_loop


def game():
    question = None
    invalid_input = False
    question = input("Would you like to play my epic guessing game??? [Y/N]")
    if question != "Y" or "N":
        invalid_input: bool = True
    if question == "N":
        print("Fine then I didnt wanna play it with you anyway!")
    if question == "Y":
        guess_loop()
    if invalid_input == True:
        print("Oops its seems you've input a invalid character. Please answer with a uppercase \"Y\" or \"N\"")
        question = None
        game()

global tries

def guess_loop():
    global guess_loop
    random_number = random.randint(1, 10)
    invalid_input2 = True
    guess = int(input("Awesome lets play! Ive picked a number beetween one and ten. Try to guess it!"))
    if guess is not int(1, 11):
        invalid_input2 = True
    if guess > random_number:
        tries += 1
        int(input("Too low! guess higher!" + f" This is your {tries}th try!"))
        guess_loop()
    if guess > random_number:
        tries += 1
        int(input("Too high! guess lower!" + f" This is your {tries}th try!"))
        guess_loop()
    if guess == random_number:
        new_game = input(f"Congratulations {uname} you won! Would you like to play again? [Y/N]")
        if new_game != "Y" or "N":
            invalid_input: bool = True
        if new_game == "N":
            print("Fine then I didnt wanna play it with you anyway!")
        if new_game == "Y":
            guess_loop()
        while invalid_input == True:
            print("Oops its seems you've input a invalid character. Please answer with a uppercase \"Y\" or \"N\"")
            guess_loop()

    while invalid_input2 == True:
        print("Oops its seems you've input a invalid character. Please answer with a number between 1 and 10")
        guess_loop()

game()

输出:

Whats up! What is your username? R33
Hiya R33. Cool name ;)
Would you like to play my epic guessing game??? [Y/N]Y
Awesome lets play! Ive picked a number beetween one and ten. Try to guess it!1
Traceback (most recent call last):
  File "88888", line 58, in <module>
    game()
  File "88888", line 18, in game
    guess_loop()
  File "88888", line 32, in guess_loop
    if guess is not int(1, 11):
TypeError: int() can't convert non-string with explicit base

标签: pythontypeerror

解决方案


我有点跳过了很多基本的东西

有你的问题。你真的应该放慢速度并使用一个好的在线教程来首先了解基本的东西。

错误

int() 无法转换具有显式基数的非字符串

告诉您该int()函数,当使用两个参数调用时,期望第一个是string,第二个是给出基数的整数

您可能打算检查是否guess在 1 到 10 之间,为此您需要执行以下操作:

if 1 <= guess <= 10:

或者

if guess in range(1, 11):

推荐阅读