我知道这将是非常具体的,甚至可能是以前问过的,但是我找不到任何可以帮助我的东西。我正在尝试创建一种类似于“ Papers,Please”的游戏,并且在同时使用“ if”变量和列表时遇到困难。
这是我的代码:
import time
import random
#Variables
NAT = ["British","American","French","Spanish","Italian"]
GEN = ["M","F"]
if GEN == "M":
FN = ["Greg","Harvey","Joseph","Prabesh","John","Joe"]
elif GEN == "F":
FN = ["Emma","Olivia","Sophia","Ava","Georgia","Nia"]
LN = ["Sutton","Little","Mayers","Pearce","Fagu","Smith"]
D = list(range(1,28))
M = ["Jan","Feb","March"]
Y = list(range(1900,1975))
#Design
def passport():
global NAT
global FN
global GEN
print(" __________")
print("|-PASSPORT-|")
print("|Nationality:",random.choice(NAT))
print("|Gender:",random.choice(GEN))
print("|First Name:",random.choice(FN))
print("|Last Name:",random.choice(LN))
print("|D.O.B:",random.choice(D),random.choice(M),random.choice(Y))
passport()
一切正常,直到我添加了性别变量。我得到的错误是:
Traceback (most recent call last):
File "C:/Users/Greg/AppData/Local/Programs/Python/Python37-32/Games.py", line 60, in <module>
passport()
File "C:/Users/Greg/AppData/Local/Programs/Python/Python37-32/Games.py", line 55, in passport
print("|First Name:",random.choice(FN))
NameError: name 'FN' is not defined
>>>
任何帮助将不胜感激,因为我不知道从这里去哪里。对不起,很痛苦:)
答案 0 :(得分:0)
GEN
在if语句运行时的值为["M", "F"]
。这意味着如果语句大小写,GEN
也不匹配,因此也从未定义FN
。
您可能希望函数选择名字,以便在运行时传递所选的性别。
答案 1 :(得分:0)
您定义以下内容:
GEN = ["M","F"]
因此,这两个if/elif
语句都会失败(因为["M","F"] != "M"
和["M","F"] != "F"
):
if GEN == "M":
FN = ["Greg","Harvey","Joseph","Prabesh","John","Joe"]
elif GEN == "F":
FN = ["Emma","Olivia","Sophia","Ava","Georgia","Nia"]
因此,FN
未定义。
答案 2 :(得分:-1)
就像其他人说的那样,变量FN
没有定义,在if GEN == "M":
之前定义FN
就像这样:
FN = []
if GEN == "M":
# And so on ...