根据条件执行功能

时间:2018-05-12 08:41:53

标签: python function

我想根据条件执行一个函数。如果sentence变量设置为How are you?,那么我希望reply()函数将response的值更改为I am good,以便Bot可以响应。 任何帮助表示赞赏。

response = ""
def reply():
    response = 'I am good'
    return;

sentence = input('You: ')

if sentence == "How are you?":
    reply()
print('Bot: ' + response)

2 个答案:

答案 0 :(得分:1)

您可以使用词典来匹配回复:

reply_dict = {
    "How are you?" : "I am good"
}
sentence = input('You: ')
response = reply_dict.get(sentence, "")
print('Bot: ' + response) 

注意使用dict.get方法,它将搜索其中的句子并返回匹配值,如果没有找到,我将默认值设置为""

答案 1 :(得分:-1)

enter image description here

设置对全局的响应

var initialProperty = {
  name: '',
  id: 0,
  type: ''
}

class Example extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      otherProperty: '',
      targetProperty: initialProperty
      //at the start of the Component, everything works fine.
      //the targetproperty is set to initialproperty
    }
  }
  //by the time, the targetproperty was changed from the initial in the component
  //but if i click a button, i want to set targetproperty to the initialproperty
  somethingHappensOnClick = () => {
    this.setState({targetProperty: initialProperty})
    //unfortunately, the targetproperty wasn't set to the initial.
  }
}