【问题标题】:Python can't assign value to a string based on values of two integersPython 无法根据两个整数的值为字符串赋值
【发布时间】:2021-01-16 13:13:54
【问题描述】:

我正在尝试使用 Python 制作基于文本的游戏,并且我正在尝试将旅行系统添加到游戏中

我使用三个变量进行旅行 位置的两个整数 (a & b) 和一个字符串告诉玩家位置(locationstr)

代码通过输入为 a 和 b 赋值,并且应该根据 a 和 b 的值给 locationstr 赋值,但即使 a 和 b 改​​变 locationstr 也不会

这里是代码

#Variables
#new travel system variables
a = 3
b = 3
#New Location definitions
if (a == 3 and b == 3):
 locationstr = "the Center of the Wilds"
elif (a == 2 and b == 2):
 locationstr = "the Northwestern plains of the Wilds"
#Game
print("You are currently in", locationstr)
print("Debug: a", a)
print("Debug: b", b)
while True:
 print("Do you want to travel somewhere?")
 print("(T)ravel")
 print("Do you want to end the day?")
 print("(Y)es")
 print("(N)o")
 #Choice input
 x = input("What is your choice?")
 if (x == "Y" or x == "y"):
     #Ending the day
  print("You decided to end the day")

  print("###########################################################################")
  print("You are currently in", locationstr)
  print("Debug: a", a)
  print("Debug: b", b)
 elif (x == "N" or x == "n"):
  print("###############################################################################")
  print("You decided to not end the day")
 elif (x == "T" or x == "t"):
     #Travel system
      print("###########################################################################")
      print("You decided to travel somewhere")
      print("Where to travel?")
      print("(1) Northwest")
      ti = input("What is your choice?")
      if(ti == "1"):
       a = a - 1
       b = b -1
       print("########################################################################")
       print("You traveled to", locationstr)
       print("Debug: a", a)
       print("Debug: b", b)
      else:
         print("#######################################################################")
         print(ti, "is not a valid choice")
 else:
  print(x, "is not a valid choice")

注意:我通过两个变量(location 和 locatşonstr)使用旧的旅行系统,它可以工作,但效率不高,所以我决定更改旅行系统

【问题讨论】:

  • 欢迎来到 StackOverflow。不要将链接粘贴到您的代码中,请在此处键入/粘贴链接stackoverflow.com/help/how-to-ask 没有人有时间下载链接代码
  • 代码太多,我们无法为您排除故障。制作一个重现错误的最小工作示例(MWE)

标签: python string if-statement variables input


【解决方案1】:

为什么会改变?

如果你这样做

a = 4
b = a
b = 5

你不会期望a5

要更新 locationstr 的值,您需要使用 locationstr = ... 更新它

我建议您通过函数更新 locationstr。 (here is a guide for function in python if you need it)

所以你会做类似的事情

def change_loc(a, b):
   if (a == 1 and b == 1):
      return "the Northwestern corner of the Wilds"
   ...

当你想改变位置时,像这样调用它:

locationstr = change_loc(a, b)

【讨论】:

    猜你喜欢
    • 2011-12-08
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    相关资源
    最近更新 更多