简体   繁体   English

当值通过循环输入时,不会拾取字典 0 键值

[英]Dictionary 0 key value is not picked up when the values enter through the loop

At runtime it does't access value at index[0] and give error of 'avg' not defined How do i fix it.在运行时,它不会访问 index[0] 处的值并给出未定义的“avg”错误我该如何修复它。 It require two decimal value but it give only one decimal value.它需要两个十进制值,但它只给出一个十进制值。 CODE BELOW:下面的代码:

    n = int(input())
    student_marks = {}
    for i in range(n):
        name, *line = input().split()
        scores = list(map(float, line))

        student_marks[name] = scores
        print(scores)
        print(student_marks)
    query_name = input()
    if query_name == name:
        print(query_name)
        avg=0
        avg=sum(scores)/3
    print(avg)

OUTPUT: OUTPUT:

    4
    dd 3 34 2 2
    [3.0, 34.0, 2.0, 2.0]
    {'dd': [3.0, 34.0, 2.0, 2.0]}
    g 3 4 5 6
    [3.0, 4.0, 5.0, 6.0]
    {'dd': [3.0, 34.0, 2.0, 2.0], 'g': [3.0, 4.0, 5.0, 6.0]}
    d 3 4 534 34
    [3.0, 4.0, 534.0, 34.0]
    {'dd': [3.0, 34.0, 2.0, 2.0], 'g': [3.0, 4.0, 5.0, 6.0], 'd': [3.0, 4.0, 534.0, 34.0]}
    e 3 4 4 4
    [3.0, 4.0, 4.0, 4.0]
    {'dd': [3.0, 34.0, 2.0, 2.0], 'g': [3.0, 4.0, 5.0, 6.0], 'd': [3.0, 4.0, 534.0, 34.0], 'e': [3.0, 4.0, 4.0, 4.0]}
    dd
    Traceback (most recent call last):
      File "C:/Users/Priya/Desktop/1.py", line 15, in <module>
        print(avg)
    NameError: name 'avg' is not defined

Instead of:代替:

if query_name == name:

Perhaps you want to do:也许你想做:

if query_name in student_marks:    # Check if the query name is in the previously provided student details.

Because:因为:

name, *line = input().split()名称,*line = input().split()

if query_name == name:如果 query_name == 名称:

Means if you enter the query name as the name of the last student provided, then only it will go inside if .表示如果您输入查询名称作为最后提供的学生的名称,那么只有它会在 go 里面if (I am 99.99% sure this is not what you want.) (我 99.99% 确信这不是你想要的。)

In your input, students are: ['dd', 'g', 'd', 'e' ].在您的输入中,学生是:['dd', 'g', 'd', 'e' ]。 If you provide the query name as 'e' , then only it will go inside if .如果您将查询名称提供为'e' ,那么只有它会在if中出现 go 。 Also if you provide n = 0, then it will throw an error because for loop will not run and name will not exist.此外,如果您提供 n = 0,那么它将引发错误,因为for循环将不会运行并且name将不存在。 (I am 99.99% sure this is not what you want.) (我 99.99% 确信这不是你想要的。)


Also:还:

avg=sum(scores)/3

Should be:应该:

avg=sum(student_marks[query_name])/4   # You have four marks and not three.

So, change:所以,改变:

query_name = input()
if query_name == name:
    print(query_name)
    avg=0
    avg=sum(scores)/3
print(avg)

To:至:

query_name = input()
if query_name in student_marks:
    print(query_name)
    avg=sum(student_marks[query_name])/len(student_marks[query_name])
    print(avg)
else:
    print('Student details does not exist.')

Modify your code from this line.从此行修改您的代码。

query_name = input()

if query_name in student_marks:
    scores = student_marks[query_name]
    avg = sum(scores) / len(scores)
    print(avg)
else:
    print(f'Student {query_name} does not exist')

A bit of explanation on how python variables are scoped:关于 python 变量的作用域的一些解释:
A variable created inside an if-else clause or a loop is accessible outside the block.if-else子句或loop内创建的变量可在块外访问。

Therefore, the reason python can't find the variable avg is because it never got created, which means the if condition was not satisfied.因此,python 找不到变量avg的原因是它从未被创建,这意味着不满足if条件。 While coding, try debugging by simply putting print statements and print out the values to see why the condition is not satisfied.在编码时,尝试通过简单地放置print语句并打印出值来进行调试,以查看不满足条件的原因。

The variable name gets assigned a new value in each iteration of the for loop.在 for 循环的每次迭代中,变量name都会被分配一个新值。 When the control leaves the loop, the value of name is the last value entered by the user (name = 'e' for the example provided in the question) .当控件离开循环时, name的值是用户输入的最后一个值(name = 'e' for the example provided in the question)

You need to check if the query_name is present among all the names entered by the user, which can be found from the keys of the dict student_marks .您需要检查用户输入的所有名称中是否存在query_name ,这可以从 dict student_marks的键中找到。 A simple membership check using the in operator does the trick.使用in运算符进行简单的成员资格检查就可以解决问题。

Put the avg=0 statement outside the if because avg is not defined when if statement is not true.将 avg=0 语句放在 if 之外,因为当 if 语句不为真时未定义 avg。

So whenever the if statement is false, 'avg' is not defined that is coming in the 'print(avg)' statement.因此,只要 if 语句为假,'avg' 就不会被定义在 'print(avg)' 语句中。

n = int(input())
student_marks = {}
for i in range(n):
    name, *line = input().split()
    scores = list(map(float, line))

    student_marks[name] = scores
    print(scores)
    print(student_marks)
query_name = input()
avg=0
if query_name == name:
    print(query_name)
    avg=sum(scores)/3
print(avg)

Another way is to provide a else statement and assign a value to avg there but i guess you dont need that.另一种方法是提供一个 else 语句并在那里为 avg 分配一个值,但我想你不需要那个。

Hope it helps!希望能帮助到你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 循环遍历字典键中的最后一个值而不是字典中的所有值 - Loop looping through last value in dictionary key instead of all values in dictionary 通过 Pandas DF 和 append 值循环到一个列表,该列表是一个字典的值,其中条件值是键 - loop through Pandas DF and append values to a list which is a value of a dictionary where conditional value is the key 值循环时字典中的键错误 - Key error in dictionary when the values are in loop 当我 go 通过 Python 中的循环时,只剩下最后一个键/值对添加到字典 - Only left with the last key/value pairs added to a dictionary when I go through a loop in Python 如何遍历字典中的值以查看它们是否曾作为键出现 - How to loop through values in a dictionary to see if they ever appear as a key 循环遍历 python 中的嵌套字典并显示键值对 - loop through nested dictionary in python and display key value pair 如何循环浏览字典列表并提取具有布尔值的键 - How to loop through dictionary list and extract one key with boolean value 如何遍历字典列表并选择特定的键值python - How to loop through a list of dictionary and select specific key value python 循环字典,参考键 - Loop through a dictionary, reference key 在Python中查找值数组作为字典键的值 - Look up array of values as the value of a key of a dictionary in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM