为什么第13行a = input()影响第15行上的变量b = input(int()?)python3

时间:2019-05-22 17:06:22

标签: python python-3.x input

我正在尝试编写一个函数,该函数采用字符串形式的用户输入,并将其分配给变量a。然后,接受用户输入的整数并将其分配给变量b。问题是,当我在Windows命令行中运行代码并输入一个字符串,以为我只是将变量a分配为字符串时,出现此错误,它表示它正在寻找变量{{1的int }}。

如果我将变量b设置为等于b而不是input("Please enter starting account balance: "),则错误将按预期消失,但不需要int,我不知道如何添加try和声明。

input(int("Please enter starting account balance: "))

我希望变量a为字符串,b为整数。这些变量最终应用于初始化一个名为def player_setup(): a = input("Please enter player name: ") print(f"Name saved as {a}.") b = input(int("Please enter starting account balance: ")) return Player(name = a, account = b) from BlackJackPackage.game_support_functions import welcome from BlackJackPackage.game_support_functions import player_setup welcome() while True: #Enter Player Name, and Enter Player Starting Money human_player = player_setup() print(f"Welcome {human_player.name}!") print(f"You have ${human_player.account} in your account!.") break 的类,该类需要一个Player和一个name(string)输入。看来account(integer)的输入行试图将其输入分配给aa,从而引起ValueError。

错误:

b

1 个答案:

答案 0 :(得分:2)

在第一种情况下,您交换了intinput关键字,因此您试图将字符串"Please enter starting account balance: "转换为整数,这会导致错误ValueError: invalid literal for int() with base 10: 'Please enter starting account balance:

所以不是

b = input(int("Please enter starting account balance: "))

如下所示,您将在其中获取输入,然后将其转换为整数。

b = int(input("Please enter starting account balance: "))

因此更新后的代码将是

def player_setup():
    a = input("Please enter player name: ")
    print(f"Name saved as {a}.")

    #Fixed this line by swapping int and input
    b = int(input("Please enter starting account balance: "))
    return Player(name = a, account = b)

from BlackJackPackage.game_support_functions import welcome
from BlackJackPackage.game_support_functions import player_setup


welcome()

while True:
    #Enter Player Name, and Enter Player Starting Money
    human_player = player_setup()
    print(f"Welcome {human_player.name}!")
    print(f"You have ${human_player.account} in your account!.")
    break