그래서 여기에 질문이 있습니다. 목록에 값을 입력할 수 있는 'for in range'가 있지만 숫자가 아닌 값을 입력하면 잘못된 입력을 입력했다는 메시지만 표시되지만 올바른 값을 다시 입력할 수는 없습니다. 계속 다음으로 넘어가라고 합니다.
잘못된 값(예: 영어 문자)을 입력한 경우 입력을 다시 실행하여 특정 위치에 올바른 값을 가질 수 있도록 하려면 어떻게 해야 합니까?
도움을 주셔서 감사합니다! 파이썬의 신인
내가 작성한 코드는 다음과 같습니다.
count=15
student=list()
print('please insert student score:')
for item in range(count):
line = input('enter score for student:'+str(item+1))
if line.isdecimal() and 0<=int(line)<=100:
data=int(line)
student.append(data)
else:
print(f"what you entered:Num{item+1:3d}is not a score")
total=0
for line in student:
total += line
totalF = total/15
print('Student Average Score is:','%.2f' % totalF)
print('Finish Input\n')
print("student:",student)
print('You have', end='--> ')
for item in student:
print(f'{item:d}', end=' ')
점수를 얻는 코드의 일부를 자체 함수로 추출하고 이 함수에서 값이 유효할 때까지 값을 계속 요청하는 while 루프에 넣습니다.
def get_score(num):
while True:
value = input(f'enter score for student {num}:')
try:
# int(value) will raise a ValueError if value
# is not a proper representation of an int
value = int(value)
# now we have an int, test it's value,
# and raise a ValueError if it doesn't match
if not 0 <= value <= 100:
raise ValueError("value should be between 0 and 100")
# value is ok, done
return value
except ValueError as e:
# either it's not an int or it's not in the right range
print(f"Invalid value '{value}': {e}")
# naming tip: use a plural for collections
students = []
# tip: avoid those useless "item+1" things ;-)
for num in range(1, count+1):
score = get_score(num)
students.append(score)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다