为什么setname函数在运行?

时间:2015-12-18 23:43:25

标签: python-3.x

我正在尝试使用Python3创建一个多用途程序。 我测试了def weather():它可以显示给定邮政编码的天气数据。除非用户输入STOP,否则程序永远不会结束。 只有当用户输入'name'和'my'或'set'时,才会运行setname():函数。当我运行该程序时,它询问“无论我输入什么,你想要被称为什么”。我甚至尝试输入z,但它仍以某种方式启动了setname():函数。请原谅我,因为这是我第一次在堆栈上询问。

导致setname():函数激活的原因是什么?

def weather():
    import requests
    wgURL = "http://api.wunderground.com/api/0def10027afaebb7/forecast/q/f/place.json"
    print('What place are you looking for?')
    wgURL = wgURL.replace('place', input())
    r = requests.get(wgURL)
    data = r.json()

    for day in data['forecast']['simpleforecast']['forecastday']:
        print (day['date']['weekday'] + ":")
        print ("Conditions: ", day['conditions'])
        print ("High: ", day['high']['fahrenheit'] + "F", "Low: ", day['low']['fahrenheit'] + "F", '\n')

def setname():
    print('What would you like to be called?')
    username = input()
    print('Okay, I will now call you ' + username) 

username = 'Anthony'

print('Done')

run = True
while run == True:
    request = input()
    if request == 'hi' or 'hello':
        print('Hello there ' + username)
    if 'weather' in request:
        weather()
    if 'name' and 'my' or 'set' in request:
        setname()
    if request == 'STOP':
        run = False

Here is a screenshot from IDLE

1 个答案:

答案 0 :(得分:0)

你误解了in的工作原理。由于in的绑定比andor更紧密,因此'name' and 'my' or 'set' in request表示('name' and 'my') or ('set' in request)。这总是评估为真,因为'name'是真实的,'my'是真实的(两者都是非空字符串)。

请改为:

if ('name' in request and 'my' in request) or ('set' in request):
    setname()

您同样对request == 'hi' or 'hello'有疑问:这意味着(request == 'hi') or 'hello',这始终是真的,因为'hello'是真实的。你可能想要的是:

if request == 'hi' or request == 'hello':

如果您想要它,请咨询operator precedence table