[英]deleting a name from a list input by user and averaging a class score
我已经阅读了很多关于Python的教程,并且目前正在使用python进行编程类的入门,但是我无法弄清楚。 我已经搜索了堆栈溢出,dani网站,java2s,github和许多其他内容,但无法理解我在做什么错。
这是我编程班上的最后一个项目,我想在课堂上做几件事,然后将它们导入主程序。
最终,我希望也可以在我的工作场所中使用它,并希望它向用户提供选项菜单。 1:添加名称和键入速度。 2:按值删除姓名(学生的姓名,如果可能的话,我想在课堂上做这件事。3:打印姓名和速度。4:打印速度列表。5:打印平均值速度列表中的速度(我也想在课堂上做),并退出程序6。
我试图变得雄心勃勃,并创建了一个随机的名称生成器,所以我也创建了一个打印名称列表的函数,但这要在星期一早上进行,所以由于没有时间,我取消了该项目。
无效的部分是#2-删除名称和#3-平均分数。 在#2上,我没有尝试过.remove,del或其他任何我见过的人尝试过的事情。 似乎大多数示例仅是硬编码的。其他示例对我而言没有意义。 在#3上,我尝试了多种计算,包括将数字分别加在一起,创建不同的函数并除以len,还尝试了均值Built_in。
我可以根据工作情况进行分配,但是其他部分对将其用于特定目的特别有用。
这是我的课程:
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)
和主程序(带注释):
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
>>>
其他一切都按预期运行。 如果有人可以帮助我解决这个问题,我将不胜感激。 谢谢!
更新:以适当的缩进和调用来运行5。
追溯(最近一次通话):文件“ C:\\ Users \\ Whited \\ Desktop \\ Classes \\ Programming \\ studentRun.py”,行56,在打印中(“类的平均分数:“%(class_avg.speed_average())) TypeError:“ int”对象不可调用
更新:顺便使用Python 3。 -并且,该文件另存为studentClass
我很无聊,而且有点嗡嗡作响,所以我想我只想抛出一些可以从中学习的工作代码:
# 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.")
我更喜欢if =>在这种情况下继续,而不是if,elif ...
使用班级(粗略地命名)来管理学生(添加和删除)并取其平均值是一种很好的方法。
至于你做错了什么:
您的name_list
不是名称列表,它是student_info
的列表。 您尝试先从列表中remove
该名称,然后再检查该名称是否在其中,因此这将始终失败。 至少您要在调用remove
之前检查是否存在。 但这对您永远不会起作用,因为列表不包含字符串,而是包含student_info
。 要使您的工作正常,您需要做类似的事情
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,))
您正在做的是创建一个Student_info的新的空实例。 您要做的就是获取现有学生的价值。
total_score = 0
for student in name_list:
total_score += student.speed
average = total_score / len(name_list)
在评论中回答您的问题:
所有类都应从对象继承(新样式类) https://wiki.python.org/moin/NewClassVsClassicClass
values
是一种获取字典值的方法。
{"1": ['a', 'b'], "foo", 10.0}.values() == [["a", "b"], 10.0]
只需将Student和Class类复制到另一个文件(例如,使用models.py),然后执行以下任一操作:
import models
然后,在任何使用“学生”或“班级”(在models.py之外)的地方,都使用模型作为前缀。 喜欢
group = models.Class()
...
group.append(models.Student(new_name, typing_speed))
或者你可能只有
from models import *
这会将所有内容从models.py
导入当前名称空间,因此无需更改其他代码。 保留名称空间是一个好主意...所以我会选择选项1。
if __name__ == "__main__"
最好在每个文件中都包含此内容。 执行python程序时,执行的文件名为 “ main ”。 此检查将告诉您是否正在执行文件。 如果您的文件是通过其他方式导入的,则名称将不是“ main ”。 这使您可以根据执行还是导入来执行不同的操作。
我认为您本可以使用字典来解决这个问题。
另外,您还有一个成员speed_average和一个成员函数speed_average。 函数和变量的名称不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.