尝试访问另一个函数中的字典值

时间:2019-05-16 13:23:30

标签: python dictionary

您开得太快了,警察阻止了您。编写代码以计算结果,并将其编码为一个int值:0 =无票据,1 =小票据,2 =大票据。如果速度等于或小于60,则结果为0。如果速度介于61和80之间(含端点),则结果为1。如果速度等于或大于81,则结果为2。除非是您的生日-那天,您的在所有情况下,速度都可以提高5。

为此,我实际上想到了创建字典。我的第一个功能与字典的创建有关。第二个将返回0,1或2,具体取决于我的输入速度。我稍后将解决的出生部分。我只需要帮助来了解字典的值

def code_computing():
  code_rules={'No ticket':0,'Small ticket':1,'Big ticket':2}
  return code_rules
print(code_computing())

def speed_limits():
  speed=int(input('Digit your current speed\n'))
  code_computing()
  while speed>=0:
    if 0<=speed<=60:
      traffic_ticket=code_rules['No ticket']
      print('You have only received a warning')
      return 0
    elif 61<=speed<=80:
      traffic_ticket=code_rules['Small ticket'] 
      print('You will pay  a small amount')
    return 1
    elif speed>=80:
      traffic_ticket=code_rules['Big ticket']
      print('You will pay the highest amount')
    return 2
    else:
      print('Enter a correct speed value to evaluate')
      break
print(speed_limits())

它使我的elif speed> 80出现语法错误

2 个答案:

答案 0 :(得分:1)

您的返回语句return 1缩进不正确。缩进在python中非常重要。

def code_computing():
    code_rules = {'No ticket': 0, 'Small ticket': 1, 'Big ticket': 2}
    return code_rules


code_rules = code_computing()
print(code_rules)


def speed_limits():
    speed = int(input('Digit your current speed\n'))
    code_computing()
    while speed >= 0:
        if 0 <= speed <= 60:
            traffic_ticket = code_rules['No ticket']
            print('You have only received a warning')
            return 0
        elif 61 <= speed <= 80:
            traffic_ticket = code_rules['Small ticket']
            print('You will pay  a small amount')
            return 1
        elif speed >= 80:
            traffic_ticket = code_rules['Big ticket']
            print('You will pay the highest amount')
            return 2
        else:
            print('Enter a correct speed value to evaluate')
            break


print(speed_limits())

尝试以上

答案 1 :(得分:1)

语法错误是由于您的布尔比较导致的。当在if语句中使用多个条件时,必须按如下所示将它们分开:

if 0<=speed & speed<=60:

根据您的所有条件进行此操作,您将很高兴。

否则,您可以对代码进行一些小改进。首先,您不需要字典功能。否则,您将在每次调用speed_limits函数时创建字典。这是您的方法:

def speed_limits(speed, code_rules):
    while speed>=0:
        if 0<=speed & speed<=60:
            traffic_ticket = code_rules['No ticket']
            print('You have only received a warning')
            return 0
        elif 61<=speed & speed<=80:
            traffic_ticket = code_rules['Small ticket'] 
            print('You will pay  a small amount')
            return 1
        elif speed>=80:
            traffic_ticket = code_rules['Big ticket']
            print('You will pay the highest amount')
            return 2
        else:
            print('Enter a correct speed value to evaluate')
            break

code_rules={'No ticket':0,'Small ticket':1,'Big ticket':2}

In [1] : print(speed_limits(65, code_rules))
Out[1] : You will pay  a small amount
1