在if语句中使用字符串

时间:2017-07-11 16:21:40

标签: python if-statement

我需要一种方法让用户输入在if语句中使用:

print("Hello, World!")

name = input("What is your name?")

hobby = input("Cool, so " + name + " what do you do you for fun? You can say something like play, work, learn, etc.")

play = 'play'
work = 'work'
learn = 'learn'

if hobby = play
    print('awesome')

elif hobby = work
    print('must be busy')

elif hobby =  learn
    print('ha, me too')

3 个答案:

答案 0 :(得分:6)

ifelifelse语句必须以:终止。另外==用于比较,=用于分配。所以

if hobby == play:
    print('awesome')

elif hobby == work:
    print('must be busy')

elif hobby == learn:
    print('ha, me too')

答案 1 :(得分:1)

在您的解决方案中,您缺少:==运算符,但在您的情况下,而不是else-if梯形图,您可以使用字典。

from __future__ import print_function

actions = {'play': 'awesome', 'work': 'must be busy', 'learn': 'ha, me too', }

if hobby in actions:
   print(actions[hobby])
else:
   print("default case")

OR

from __future__ import print_function

actions = {'play': 'awesome', 'work': 'must be busy', 'learn': 'ha, me too', }

try:
   print(actions[hobby])
except KeyError:
   print("default case")

答案 2 :(得分:0)

您可以通过编码

删除作业
if hobby == 'play':
    print('awesome')

OR

if hobby == play:
    print('awesome')