[英]I get this error when i run this code “TypeError: can only concatenate str (not ”NoneType“) to str”, why?
[英]When I want to randomly assign a role by doing random.shuffle i get this error: TypeError: can only concatenate str (not "NoneType") to str
我最近開始研究一個小程序,我想使用 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))
首先,你不能指望從處理過的 object 得到返回值。這一行會給你一個錯誤,因為你期望從 None input print(name + " You are " + random.shuffle(roles))
。
因此,您需要了解random.shuffle
工作原理。 random.shuffle
是一個 function,它接受一個列表並隨機交換它的值。 所以,你需要做的只是在你執行后聲明角色的一件事——>調用random.shuffle
function。
所以,它必須像那樣 go :-
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
# 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
這里的問題是random.shuffle
就地打亂列表,但函數的返回值不是打亂后的列表,而是實際上是None
。
作為替代方案,function random.choice
從其參數中隨機選擇一個元素。 我認為這就是您想使用的。 您的代碼應如下所示:
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
列表。
我最近開始研究一個小程序,我想使用 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))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.