我很困惑,if语句应该运行imo,但当然这是编程所以它不会起作用。
def create_player():
name = str()
names = []
print("hey there")
if numberofplayers == 2:
name = input("Please enter Player 1's name: ")
names.append(name)
name = input("Please enter Player 2's name: ")
names.append(name)
elif numberofplayers == 3:
name = input("Please enter Player 1's name: ")
names.append(name)
name = input("Please enter Player 2's name: ")
names.append(name)
name = input("Please enter Player 3's name: ")
names.append(name)
elif numberofplayers == 4:
name = input("Please enter Player 1's name: ")
names.append(name)
name = input("Please enter Player 2's name: ")
names.append(name)
name = input("Please enter Player 3's name: ")
names.append(name)
name = input("Please enter Player 4's name: ")
names.append(name)
print("Welcome to the game " + names[0] + ", " +names[1]+ ", "+names[2]+ " and "+names[3]+"!")
print("test")
numberofplayers = int(0)
numberofplayers = input("# of players")
create_player()
print ("aha")
(顺便说一句,这段代码不是任何接近完成的方法)随机打印操作在那里进行测试,程序似乎忽略了整个if语句,因为它打印了if语句之外的所有打印操作,但没有在声明中。任何帮助都会非常感激,谢谢你。
答案 0 :(得分:2)
您需要将numberofplayers
投放到int
,否则您需要进行比较int
和string
:
numberofplayers = int(input("# of players"))
Python 3中的 input()
返回一个字符串对象,与以前的Python2 input()
不同。
这是正在发生的事情:
>>> a = input()
2
>>> a == 2
False
>>> a == '2'
True
答案 1 :(得分:1)
虽然保罗的答案解决了你眼前的问题,但还有其他一些事情需要指出。
由于您的功能至少会创建两个玩家,因此请正确命名:create_players
。它可以避免以后混淆。
不要依赖函数范围之外的全局变量或值。您应该将它们明确地传递给您的函数。
def create_players(numberofplayers):
...
numberofplayers = int(input('# of players'))
create_players(numberofplayers)
这些行没有用处:
name = str()
numberofplayers = int(0)
您不需要将变量定义为类型以便使用它们,并且您立即用实际值替换它们。
作为单个if-elif
循环,您的分支for
会更好:
names = []
for player in range(1, numberofplayers+1):
names.append( input("Please enter Player %d's name: " % player) )
print('Welcome to the game ' + ' and '.join([', '.join(names[:-1]), names[-1]]) + '!')