【问题标题】:input give me incorrect even im writing correct answer输入给我不正确即使我写正确的答案
【发布时间】:2023-01-24 02:16:06
【问题描述】:

我正在尝试制作问答游戏,但如果我回答正确,它会给我错误的答案,是否区分大小写?

代码 :

score = 0
question_n = 0

playing = input('Do you wish to start? (Yes-No)')
if playing == "yes" or playing == "y":
    question_n +=1
    ques = input(f'\n{question_n}. Who owns amazon? ')

    if ques == 'Jeff bezos':
        print('Correct! You got 1 point.')
        score +=1
        print(f'Your score is : {score}')
                 

    else:
        print('Incorrect')
        print(f'The correct answer is --> Jeff bezos. ')
        x = input('Press any key to exit..')
elif playing == "no" or playing == "n":
    print('Thanks for trying me (:')

错误 :

Do you wish to start? (Yes-No)yes

1. Who owns amazon? jeff bezos
Incorrect
The correct answer is --> Jeff bezos. 
Press any key to exit..

【问题讨论】:

  • 这似乎不是tkinter问题
  • 是的,它区分大小写。取一些字符串 s = 'jEfF bEzOs' 并设置 s = s.title() 将通过将字符串中每个单词的首字母大写来设置 s = 'Jeff Bezos'

标签: python tkinter


【解决方案1】:

是的,字符串比较区分大小写。您可以通过对输入字符串和比较字符串执行相同的大小写修改来使其不区分大小写,例如:

if ques.upper() == 'Jeff bezos'.upper():
    ...

在上面的示例中,用户输入和“正确”字符串在比较之前都被转换为大写。这样,如果用户输入"JeFf BeZoS",而正确答案是"Jeff bezos",则它们都被比较为"JEFF BEZOS",因此被认为是相等的。

在 Python 中有处理字符串大小写的函数

  • str.upper() # convert to upper case
  • str.lower() # convert to lower case
  • str.capitalize() # capitalize string
  • str.title() # capitalize every word in the string(感谢@Vin,我不知道这个!)

例子:

string = 'foo'
print(string.upper())
>>> FOO
string = 'FOO'
print(string.lower())
>>> foo
string = 'foo bar'
print(string.capitalize())
>>> Foo bar
string = 'foo bar'
print(string.title())
>>> Foo Bar

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多