Python麻烦str / int乘法

时间:2019-05-15 03:58:03

标签: python function

因此,我试图乘以变量中指定的数字,但是每当乘以时,它将其作为字符串并乘以字符串,但是当我尝试将变量转换为int语法时说它一定是str!

我尝试将var转换为字符串前的int

def gamble_menu():
  global dice_amount
  dice_amount = input("How many dice? (higher dice count = higher wager multiplier) ")
  gamble_dice()

def gamble_dice():
  while True:

    print(str(dice_amount)); print("1 - " + (int(dice_amount)) * 6)
    print("You must guess the number rolled from the number of dice")
    print("Multiplier = *2")
    number_guess = input("#? ")
    if (int(number_guess)) < 0 or (int(number_guess)) > dice_amount * 6:
      print("Invalid integer, try again")

我期望它将变量与数字相乘,但是它将它用字面量

5 个答案:

答案 0 :(得分:0)

您的dice_amount似乎是一个字符串。 (int(number_guess)) > dice_amount * 6正在尝试将整数与字符串进行比较。尝试使用int(dice_amount)

答案 1 :(得分:0)

可能是因为您试图在打印功能中合并数字和字符串。

尝试打印(“ 1-” + str(int(dice_amount)* 6))

答案 2 :(得分:0)

我认为问题出在

20 30 40 50 60

您不能混合使用str + int。如果您像我一样使用python 3.7,请尝试:

print("1 - " + (int(dice_amount)) * 6)

答案 3 :(得分:0)

我假设您包含的代码不完整。请添加更多详细信息。我修复了几个错误,主要是由于您在Python中使用字符串的方式所致。 关于该函数要执行的操作还不清楚。

def gamble_dice(dice_amount): 

    while True:
        print(str(dice_amount)) 
        print("1 - ",  (dice_amount * 6))
        print("You must guess the number rolled from the number of dice")
        print("Multiplier = *2")
        number_guess = input("#? ")

    if number_guess < 0 or (number_guess > dice_amount * 6):
        print("Invalid integer, try again")
    else:
        print("right on!")

dice_amount = int(input("How many dice? (higher dice count = higher wager multiplier) "))

gamble_dice(dice_amount)

答案 4 :(得分:-1)

def gamble_menu():
  global dice_amount
  dice_amount = input("How many dice? (higher dice count = higher wager multiplier) ")
  gamble_dice()

def gamble_dice():
  while True:

    print(str(dice_amount)); print("1 - " + str((int(dice_amount)) * 6))
    print("You must guess the number rolled from the number of dice")
    print("Multiplier = *2")
    number_guess = input("#? ")
    if (int(number_guess)) < 0 or (int(number_guess)) > dice_amount * 6:
      print("Invalid integer, try again")

print("1 - " + (int(dice_amount)) * 6) # this is that str + int, it is wrong.
print("1 - " + str((int(dice_amount)) * 6)) # this that str + str, it works.

尽力帮助您。