gpt4 book ai didi

python - 为什么我的 "if"语句在 python 中不起作用?

转载 作者:行者123 更新时间:2023-11-28 21:31:25 25 4
gpt4 key购买 nike

我想知道为什么我的“if”语句不起作用。我被要求提供输入,但之后什么也没有发生。它不会打印出它是A、B、C还是D。

def main():
printLetterGradeFromNumber(input("The grade as a number: "))

def printLetterGradeFromNumber(number_grade):

A = range(90, 100)
B = range(80, 89)
C = range(70, 79)
D = range(60, 69)

if number_grade == A:
print("That student gets an A")
elif number_grade == B:
print("That student gets a B")
elif number_grade == C:
print("That student gets a C")
elif number_grade == D:
print("That student gets a D")

return number_grade


main()

最佳答案

有两个问题:

  • input ,里面main ,需要转换为 int
    • 目前,inputstr ,这永远不会是True当测试 A 内的成员资格时, B , CD
    • 示例:'90' == 90比较为False ,所以'90' in AFalse
  • 使用membership operator, in ,而不是 comparison operator, == .
def main():
printLetterGradeFromNumber(int(input("The grade as a number: ")))

def printLetterGradeFromNumber(number_grade):
A = range(90, 100)
B = range(80, 89)
C = range(70, 79)
D = range(60, 69)

if number_grade in A:
print("That student gets an A")
elif number_grade in B:
print("That student gets a B")
elif number_grade in C:
print("That student gets a C")
elif number_grade in D:
print("That student gets a D")

return number_grade

main()

输出:

The grade as a number:  90
That student gets an A

替代实现:

  • Don’t Forget NumPy!
  • numpy.digitize
    • digitize返回 indexvalue ,在bins内。 value < 60返回index = 0 ,而value >= 90返回index = 4 .
    • 使用 index 找到字母等级的grades 。因此,顺序为 grades必须对应于bins .
from numpy import digitize

def print_letter_grade():
value = int(input('The grade as a number: '))
grades = ['F', 'D', 'C', 'B', 'A']
index = digitize(value, bins=[60, 70, 80, 90])
print(f'The student gets an {grades[index]}')

关于python - 为什么我的 "if"语句在 python 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58140843/

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