Python if and else

时间:2019-03-07 15:24:13

标签: python

我的代码总是给出“祝你有美好的一天”,我哪里出错了

import random
random_choice = ['Noob', 'Average', 'Pro', 'Expert']

name = input('What is your gamername? ')

print(name, 'is a', random.choice(random_choice), 'Gamer')

if random.choice == 'Noob':
    print('Im afraid there is nothing to be done')
else:
    print('Have a Nice Day', name)

输出始终为

What is your gamername? (name=
Gamerman is a (Random) Gamer
Have a Nice Day (name)

2 个答案:

答案 0 :(得分:3)

if random.choice == 'Noob':永远不会求值为True,因为random.choice是一个函数,并且函数绝不等于字符串。

第一次调用random.choice时,请将其分配给变量。然后,您可以在条件中与该变量进行比较。

import random
random_choice = ['Noob', 'Average', 'Pro', 'Expert']

name = input('What is your gamername? ')

gamer_kind = random.choice(random_choice)
print(name, 'is a', gamer_kind, 'Gamer')

if gamer_kind == 'Noob':
    print('Im afraid there is nothing to be done')
else:
    print('Have a Nice Day', name)

答案 1 :(得分:1)

您不想在if语句中使用random.choice函数。

将随机名称另存为变量并进行检查。

import random

random_choice = ['Noob', 'Average', 'Pro', 'Expert']

name = input('What is your gamername? ')

random_name = random.choice(random_choice)

print(name, 'is a', random_name, 'Gamer')

if random_name == 'Noob':
    print('Im afraid there is nothing to be done')
else:
    print('Have a Nice Day', name)