当我想通过执行random.shuffle随机分配角色时,我会遇到以下错误:TypeError:只能将str(而不是“NoneType”)连接到str

2024-04-30 03:20:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近开始做一个小程序,我想用random.shuffle的方式给某人一个随机角色。在我真正提到这个角色之前,一切都很顺利

import random
roles = ['Lizard','Human']

random.shuffle(roles)

name = input("Enter Your Name")

color = input("Select a color \n Blue \n Red \n Green \n Yellow \n Color: ")

print(name + " You are " + random.shuffle(roles))

Tags: nameimport程序角色inputyour方式random
2条回答

这里的问题是^{}将列表洗牌到,但函数的返回值不是洗牌列表,而是实际上None

或者,函数^{}从其参数中随机选择一个元素。我想这是你想用的。然后,您的代码应该如下所示:

import random

roles = ['Lizard', 'Human']

name = input("Enter Your Name")
color = input("Select a color \n Blue \n Red \n Green \n Yellow \n Color: ")

print(name + ", you are a " + random.choice(roles))

请注意,不需要预先洗牌roles列表

首先,您不能期望从处理过的对象获得返回值。此行将给您一个错误,因为您希望从None input print(name + " You are " + random.shuffle(roles))返回一个值

因此,您需要了解random.shuffle是如何工作的random.shuffle是一个随机获取列表并交换其值的函数。因此,您需要做的只是在执行后声明角色的一件事>调用了random.shuffle函数

所以,它必须是这样的

import random
roles = ['Lizard','Human']

random.shuffle(roles) # called function to swap the values of the roles _list

name = input("Enter Your Name")

color = input("Select a color \n Blue \n Red \n Green \n Yellow \n Color: ").upper() # upper() function for giving the user to write whatever he want in case you want to use this input for any other later benefits...

print(name + " You are " + roles[0]) # declaring the first value in the list doesn't mean it will be 'lizard' after randomly swapping it may display as 'human' or 'lizard'

输出的示例

# Output No. 1: -

Enter Your Name Jhon
Select a color 
 Blue 
 Red 
 Green 
 Yellow 
 Color: Blue
 Jhon You are Human

# Output No. 2

Enter Your Name Slave
Select a color 
 Blue 
 Red 
 Green 
 Yellow 
 Color: green
 Slave You are Lizard

相关问题 更多 >