我已经阅读了很多关于Python的教程,目前正在使用python编写类的介绍,但我无法弄清楚这一点。我搜索了堆栈溢出,dani web,java2s,github和许多其他人,但无法理解我做错了什么。
这是我编程课程中的最后一个项目,我想在课堂上做几件事,然后将它们导入主程序。
最终我希望在我的工作场所也能使用它,我希望它能为用户提供一系列选项。 1:添加名称和打字速度。 2:按值删除名称(学生的名字 - 如果可能的话我想用一个类做.3:打印名称和速度.4:打印速度列表.5:打印平均值速度列表中的速度(我也喜欢在课堂上做)和6来退出程序。
我试图雄心勃勃并创建一个随机名称生成器,所以我创建了一个函数来打印名称列表,但这是在星期一早上到期所以我废弃了该项目,因为我没有到达任何地方。
不工作的部分是#2 - 删除名称和#3 - 平均得分。在#2上,我没有任何运气尝试。删除,删除或我见过的人尝试过的任何其他事情。似乎大多数例子都只是硬编码。其他例子对我来说没有意义。在#3上,我尝试了多次计算,包括分别将数字加在一起,创建不同的函数并除以len,我尝试了平均的build_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行,in print(“课程的平均分数:”%(class_avg.speed_average())) TypeError:'int'对象不可调用
更新: 顺便使用Python 3。 - 并且,文件保存为studentClass
答案 0 :(得分:2)
我很无聊,而且有点嗡嗡声,所以我想我会抛弃一些你可以学习的工作代码:
# 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 =&gt;在这种情况下继续而不是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)
回答您在评论中提出的问题:
所有类都应该从object继承(New Style Classes) 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 ”。此检查将告诉您是否是正在执行的文件。如果您的文件是由其他内容导入的,则名称不会是“主要”。根据您是执行还是导入,这允许您执行不同的操作。
答案 1 :(得分:0)
我认为您可以使用字典来解决此问题。
你还有一个成员speed_average和一个成员函数speed_average。函数和变量的名称不同。