简体   繁体   English

从用户输入的列表中删除名称,并平均成绩

[英]deleting a name from a list input by user and averaging a class score

I've read lots of tutorials on Python and am currently in an intro to programming class using python, but I can't figure this out. 我已经阅读了很多关于Python的教程,并且目前正在使用python进行编程类的入门,但是我无法弄清楚。 I've searched stack overflow, dani web, java2s, github and many others but can't understand what I'm doing wrong. 我已经搜索了堆栈溢出,dani网站,java2s,github和许多其他内容,但无法理解我在做什么错。

This is for a final project in my programming class and I'd like to do a couple of things in class and then import them into the main program. 这是我编程班上的最后一个项目,我想在课堂上做几件事,然后将它们导入主程序。

Eventually I hope to use this in my workplace as well and I want it to present the user with a menu of options. 最终,我希望也可以在我的工作场所中使用它,并希望它向用户提供选项菜单。 1: Add names and typing speeds. 1:添加名称和键入速度。 2: delete a name by value(the name of a student -- I'd like to do this with a class if possible. 3: print the names and speeds. 4: print a list of the speeds. 5: print the average speeds from the list of speeds (which I'd also like to do in a class). and 6 to quit the program. 2:按值删除姓名(学生的姓名,如果可能的话,我想在课堂上做这件事。3:打印姓名和速度。4:打印速度列表。5:打印平均值速度列表中的速度(我也想在课堂上做),并退出程序6。

I tried to be ambitious and create a random name generator so I created a function to print the list of names as well, but this is due Monday morning so I scrapped that project since I wasn't getting anywhere. 我试图变得雄心勃勃,并创建了一个随机的名称生成器,所以我也创建了一个打印名称列表的函数,但这要在星期一早上进行,所以由于没有时间,我取消了该项目。

The parts that aren't working are #2 - deleting a name and #3 - averaging the score. 无效的部分是#2-删除名称和#3-平均分数。 On #2, I haven't had any luck trying .remove, del, or any other things I've seen people try. 在#2上,我没有尝试过.remove,del或其他任何我见过的人尝试过的事情。 It seems most of examples are only hard coded in. The others don't make sense to me. 似乎大多数示例仅是硬编码的。其他示例对我而言没有意义。 On #3, I've tried multiple calculations including adding the numbers together separately, creating different functions and dividing by len and I've tried the mean built_in. 在#3上,我尝试了多种计算,包括将数字分别加在一起,创建不同的函数并除以len,还尝试了均值Built_in。

I can turn the assignment in based on what is working, but the other pieces would be especially helpful for when it is used for a purpose. 我可以根据工作情况进行分配,但是其他部分对将其用于特定目的特别有用。

Here is my class program: 这是我的课程:

class student_info:

    def __init__(self):
        self.name = ""
        self.speed = ""
        self.speed_average = 0

def speed_average(self):
    return sum(self.speed) / len(self.speed)

and the main program (with comments): 和主程序(带注释):

import studentClass

name_list = []
speed = 0

def edit_list(name):
    new_name = input("What is the student's name? ")
    if new_name != "":
        name.name = new_name

    while True:
        try:
            typing_speed = input("What was the last typing speed? ")
            if speed != "":
                name.speed = float(typing_speed)
                #print (test_score)
            else:
                raise ValueError
            break
        except ValueError:
            print("Not a valid score.")

def print_students(list):
    for i, n in enumerate(list):
        print("#%d: Name: %s, Typing Speed (wpm): %d" % (i+1, n.name, n.speed))

def print_speed(list):
    for i, n in enumerate(list):
        print("%s" % (n.speed))

##Since the class instantiation didn't work, I tried creating a function - that didn't work either.
def print_avg(list):
    speed_list = speed
    print(sum(speed)/len(speed))

while True:
    print("Hi user, (1) add (2) delete (3) print (4) print scores (5) print average (6) quit")
    choice = input(" >> ")
    if choice == '1':
        name_list.append(studentClass.student_info())
        edit_list(name_list[-1])
    elif choice == '2':
        names = [name_list]       
        del_name = input("What name would you like to remove? ")
        name_list.remove(del_name)
        if del_name not in name_list:
            print("Name not found.")
        else:
            print("%s removed." % del_name)
    elif choice == '3':
        print_students(name_list)           
    elif choice == '4':
        print_speed(name_list)
    elif choice == '5':
        class_avg = studentClass.student_info()
        print("Average score for class: " %(class_avg.speed_average))
    elif choice == '6':
        print('Happy Typing!')
        break
    else:
        print("That's not an option. Please try again.")



Error returned when #2 is selected:
Hi user, (1) add (2) delete (3) print (4) print scores (5) print average (6) quit
 >> 1
What is the student's name? john
What was the last typing speed? 20
Hi user, (1) add (2) delete (3) print (4) print scores (5) print average (6) quit
 >> 1
What is the student's name? mary
What was the last typing speed? 10
Hi user, (1) add (2) delete (3) print (4) print scores (5) print average (6) quit
 >> 4
20.0
10.0
Hi user, (1) add (2) delete (3) print (4) print scores (5) print average (6) quit
 >> 3
#1: Name: john, Typing Speed (wpm): 20
#2: Name: mary, Typing Speed (wpm): 10
Hi user, (1) add (2) delete (3) print (4) print scores (5) print average (6) quit
 >> 2
What name would you like to remove? john
Traceback (most recent call last):
  File "C:\Users\Whited\Desktop\Classes\Programming\studentRun.py", line 44, in <module>
    name_list.remove(del_name)
ValueError: list.remove(x): x not in list
>>>



Error returned when #5 is selected:

    Hi user, (1) add (2) delete (3) print (4) print scores (5) print average (6) quit
     >> 1
    What is the student's name? john
    What was the last typing speed? 20
    Hi user, (1) add (2) delete (3) print (4) print scores (5) print average (6) quit
     >> 1
    What is the student's name? mary
    What was the last typing speed? 10
    Hi user, (1) add (2) delete (3) print (4) print scores (5) print average (6) quit
     >> 5
    Traceback (most recent call last):
      File "C:\Users\Whited\Desktop\Classes\Programming\studentRun.py", line 56, in <module>
        print("Average score for class: " %(class_avg.speed_average))
    TypeError: not all arguments converted during string formatting
    >>> 

Everything else is running as it should. 其他一切都按预期运行。 If anyone can help me out with this I'd sure appreciate it. 如果有人可以帮助我解决这个问题,我将不胜感激。 Thank you! 谢谢!

UPDATE: running 5 with proper indentation and call. 更新:以适当的缩进和调用来运行5。

Traceback (most recent call last): File "C:\\Users\\Whited\\Desktop\\Classes\\Programming\\studentRun.py", line 56, in print("Average score for class: " %(class_avg.speed_average())) TypeError: 'int' object is not callable 追溯(最近一次通话):文件“ C:\\ Users \\ Whited \\ Desktop \\ Classes \\ Programming \\ studentRun.py”,行56,在打印中(“类的平均分数:“%(class_avg.speed_average())) TypeError:“ int”对象不可调用

UPDATE: Using Python 3 by the way. 更新:顺便使用Python 3。 - And, the file is saved as studentClass -并且,该文件另存为studentClass

I am bored, and a little buzzed, so I thought I would just throw out some working code that you might be able to learn from: 我很无聊,而且有点嗡嗡作响,所以我想我只想抛出一些可以从中学习的工作代码:

# A Student object will just take care of tracking the name and speed.
# Classes like this in Python (with no methods) are often better represented
# by a namedtuple from the collections package.
class Student(object):

    def __init__(self, name="", speed=0):
        self.name = name
        self.speed = speed

# The Class object will represent a group of students.
# The students are tracked via a dictionary where the key is the name of 
# the student and the value is the Student object.
class Class(object):

    def __init__(self):
        """ Create an empty dictionary for the students """
        self.students = {}

    def add_student(self, student):
        """ Add a student to the "roster".  The student name will be the 
            key and the Student instance will be the value """
        self.students[student.name] = student

    def remove_student(self, name):
        """ Remove a student if they exist.  If they exist and are removed
            return True.  If they do not exist, return False """
        if name in self.students:
            del self.students[name]
            return True
        return False

    def average(self):
        """ Get the average speed of the students.
            The self.student.values() will be the values of the self.students
            dictionary, which means it will be a list of students.
            For each of the students, get their speed.  Sum those speeds
            and divide by the number of students.
            The fancy syntax of [x for x in y] below is called a list comprehension """
        return sum(student.speed for student in self.students.values()) / len(self.students)

def print_students(group):
    for i, student in enumerate(group.students.values()):
        print("#%d: Name: %s, Typing Speed (wpm): %d" % (i+1, student.name, student.speed))

def print_speed(group):
    for i, student in enumerate(group.students.values()):
        print("#%d: Typing Speed (wpm): %d" % (i+1, student.speed))


def add_student(group):
    new_name = ""
    typing_speed = None
    while not new_name:
        new_name = input("What is the student's name? ")
    while typing_speed in ("", None):
        typing_speed = input("What was the last typing speed? ")
        try:
            typing_speed = float(typing_speed)
        except:
            print("Please enter a number")
            typing_speed = None
            continue
    # We have a valid name and value speed, so create a Student and add them to the Class
    group.add_student(Student(new_name, typing_speed))


if __name__ == "__main__":
    group = Class()

    while True:
        print("Hi user, (1) add (2) delete (3) print (4) print scores (5) print average (6) quit")
        choice = input(" >> ")

        if choice == '1':
            add_student(group)
            continue

        if choice == '2':
            del_name = input("What name would you like to remove? ")
            if group.remove_student(del_name):
                print("%s removed." % del_name)
            else:
                print("Name not found.")
            continue

        if choice == '3':
            print_students(group)
            continue

        if choice == '4':
            print_speed(group)
            continue

        if choice == '5':
            print("Average score for class: %0.2f" %(group.average()))
            continue

        if choice == '6':
            print('Happy Typing!')
            break

        print("That's not an option. Please try again.")

I prefer the if => continue in this case instead of the if, elif... 我更喜欢if =>在这种情况下继续,而不是if,elif ...

Using a Class (poorly named) to manage the students (addition and removal) and take their average is a pretty good approach. 使用班级(粗略地命名)来管理学生(添加和删除)并取其平均值是一种很好的方法。

As far as what you did wrong: 至于你做错了什么:

  1. Deleting a student. 删除学生。

You name_list isn't a list of names, it is a list of student_info . 您的name_list不是名称列表,它是student_info的列表。 You try to remove the name from the list before checking if it is in there, so this will always fail. 您尝试先从列表中remove该名称,然后再检查该名称是否在其中,因此这将始终失败。 At the very least you would want to check for existence before calling remove . 至少您要在调用remove之前检查是否存在。 But that would never work for you because the list does not contain strings, it contains student_info . 但这对您永远不会起作用,因为列表不包含字符串,而是包含student_info To make yours work you would need to do something like 要使您的工作正常,您需要做类似的事情

found = False
for i, student in enumerate(name_list):
    if student.name == del_name:
        found = i
if found != False:
    del name_list[found]
    print("Deleted...")
else:
    print("Could not find name %s" % (del_name,))
  1. Taking the average: 取平均值:

What you were doing is creating a new, empty instance of student_info. 您正在做的是创建一个Student_info的新的空实例。 What you want to do is get the values of the students that exist. 您要做的就是获取现有学生的价值。

total_score = 0
for student in name_list:
    total_score += student.speed
average = total_score / len(name_list)

In response to your questions in the comment: 在评论中回答您的问题:

  1. All classes should inherit from object (New Style Classes) https://wiki.python.org/moin/NewClassVsClassicClass 所有类都应从对象继承(新样式类) https://wiki.python.org/moin/NewClassVsClassicClass

  2. values is a way to get the values of a dictionary. values是一种获取字典的方法。

    {"1": ['a', 'b'], "foo", 10.0}.values() == [["a", "b"], 10.0]

  3. Just copy the Student and Class classes into another file (say models.py for instance) and either: 只需将Student和Class类复制到另一个文件(例如,使用models.py),然后执行以下任一操作:

    import models

And then everywhere you use a Student or Class (outside of models.py) you prefix them with models. 然后,在任何使用“学生”或“班级”(在models.py之外)的地方,都使用模型作为前缀。 Like 喜欢

group = models.Class()
...
group.append(models.Student(new_name, typing_speed))

Or you could just have 或者你可能只有

from models import *

This would import everything from models.py into the current namespace so no other code would need to change. 这会将所有内容从models.py导入当前名称空间,因此无需更改其他代码。 Keeping the namespace is a good idea... so I would go for option 1. 保留名称空间是一个好主意...所以我会选择选项1。

  1. The name == main thing... 名称==主要内容...
if __name__ == "__main__"

It is good practice to include this in every file. 最好在每个文件中都包含此内容。 When you execute a python program the file you execute has a name of " main ". 执行python程序时,执行的文件名为main ”。 This check will tell you whether you were the file being executed. 此检查将告诉您是否正在执行文件。 If your file was imported by something else then name would not be " main ". 如果您的文件是通过其他方式导入的,则名称将不是“ main ”。 This allows for you to do different things depending on whether you were executed or imported. 这使您可以根据执行还是导入来执行不同的操作。

I think you could have used a dictionary for this problem. 我认为您本可以使用字典来解决这个问题。

Also you have a member speed_average and a member function speed_average. 另外,您还有一个成员speed_average和一个成员函数speed_average。 Have a different names for the function and the variable. 函数和变量的名称不同。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM