使用if和else语句返回正确输出的代码

2024-10-01 07:25:46 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码没有为某些测试返回正确的输出。我曾尝试重新编写代码来解决此问题,但一直无法做到这一点。我正在寻求有关如何使我的代码返回正确输出的帮助:

def get_translations(string):
"""convert string to list"""
list1 = []
lines = string.splitlines()
order = 1 if string.split(',')[0] == "english" else -1

if 'english,māori' in string:
    for seperate_words in lines:
        list1.append(tuple(seperate_words.split(",")[::order])) 
    
if 'māori,english' in string:
    for seperate_words in lines:
        list1.append(tuple(seperate_words.split(",")[::order]))

else:
    print("Header language not recognized!")
    print("We can't play, hōhā!")
    return -1
    
if len(list1) >= 1:
    print("Kia ora, you have {0} terms to translate today :-)"\
          .format(len(list1) - 1))

number = 0
correct = 0
possible = (len(list1) - 1)

for num in range(len(list1[1:])):
    print("E: {}".format(list1[1+number][0]))
    answer = input("M: ")
    
    if answer == list1[1+number][1]:
        print("Ka pai")
        correct += 1
        number += 1
        
    else:
        print("A: {}".format(list1[1+number][1]))
        number += 1

total = (correct / possible) * 100
return total

def reo_test(string):
    """stuff"""
    return get_translations(string)

这是返回错误输出的测试:

days_string = '''english,māori
Monday,Rāhina
Tuesday,Rātū
Wednesday,Rāapa
Thursday,Rāpare
Friday,Rāmere
Saturday,Rāhoroi
Sunday,Rātapu'''

score = reo_test(days_string)
print("Score {:.2f}".format(score))

它应该返回(输入是每个M字母后面的单词):

Kia ora, you have 7 terms to translate today :-)
E: Monday
M: Rāhina
Ka pai
E: Tuesday
M: Ratū
A: Rātū
E: Wednesday
M: Rātapu
A: Rāapa
E: Thursday
M: Rāari
A: Rāpare
E: Friday
M: Rāmere
Ka pai
E: Saturday
M: Rāhōrōi
A: Rāhoroi
E: Sunday
M: Rātapu
Ka pai
Score 42.86

Tags: to代码informatnumberstringlenif
1条回答
网友
1楼 · 发布于 2024-10-01 07:25:46

错误在这里if 'māori,english' in string:if应该是一个elif。 目前,您在第一个分支english,māori中正确地构建了翻译列表,但随后有一个单独的if/else块失败,因此会打印错误

干杯,祝你学习顺利

相关问题 更多 >