gpt4 book ai didi

python - 如何在 Python 程序中使用两个 != 中断?

转载 作者:太空宇宙 更新时间:2023-11-04 03:35:41 24 4
gpt4 key购买 nike

问题陈述、所有变量和给定/已知数据我需要一个程序,一旦在输入名称和输入等级中输入 0,它就会中断并显示结果。我知道如何在名义上做到这一点,但我该如何添加另一个休息时间?喜欢成绩 !="0"?

目前我的程序:

students = []
grades = []

while True:
name = input ("Enter a name: ")
if name.isalpha() == True and name != "0":
while True:
grade = input("Enter a grade: ")
if grade.isdigit()== True:
grade = int(grade)
if grade >= 1 and grade <= 10:
if name in students:
index = students.index(name)
grades[index].append(grade)
break
else:
students.append(name)
grades.append([grade])
break
else:
print("Grade is not valid. Try to enter it again!")
elif name == "0":
print("A zero is entered!")
break
else:
print ("Grade is not valid. Try to enter it again!")

for i in range(0,len(students)):
print("NAME: ", students[i])
print("GRADES: ", grades[i])
print("AVERAGE: ", round(sum(grades[i])/len(grades[i]),1), "\n")

还有什么方法可以让 Python 忽略输入函数中的空格?

示例:我输入的成绩中有“________8”(_ 是空格),但程序不想忽略它,我如何让它忽略空格并直接接受数字?

最佳答案

剥离() 方法

使用 stringstrip() 方法去除空格。

演示:

>>> a = "  Go  "
>>> a.strip()
'Go'
>>> a.rstrip()
' Go'
>>> a.lstrip()
'Go '
>>>

您的代码可以正常工作。产生正确的输出。


使用字典保存学生记录。

演示:

import collections
student_record = collections.defaultdict(list)

while True:
name = raw_input("Enter a name: ").strip()
if name=="0":
print "A zero is entered!"
break

if not name.isalpha():
print "Name is no valid. Try again. Enter alpha value only."
continue

while True:
grade = raw_input("Enter a grade: ").strip()
if grade.isdigit():
grade = int(grade)
if 1<=grade <= 10:
student_record[name].append(grade)
break
else:
print "Grade is not valid. Try again. Enter digit values between 1 and 10."
else:
print "Grade is not valid. Try again. Enter digit values."

for i, j in student_record.items():
print "\nNAME: ", i
print "GRADES: ", j
print "AVERAGE: ", round(sum(j)/len(j),1)

输出:

$ python test1.py
Enter a name: ABC
Enter a grade: 2
Enter a name: XYZ
Enter a grade: 5
Enter a name: ABC
Enter a grade: 6
Enter a name: 0
A zero is entered!

NAME: XYZ
GRADES: [5]
AVERAGE: 5.0

NAME: ABC
GRADES: [2, 6]
AVERAGE: 4.0

注意:

在 Python 2.x 中使用 raw_input()

在 Python 3.x 中使用 input()

关于python - 如何在 Python 程序中使用两个 != 中断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29236813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com