gpt4 book ai didi

Python:声明为整数和字符

转载 作者:行者123 更新时间:2023-12-03 19:39:11 26 4
gpt4 key购买 nike

# declare score as integer
score = int

# declare rating as character
rating = chr

# write "Enter score: "
# input score
score = input("Enter score: ")

# if score == 10 Then
# set rating = "A"
# endif
if score == 10:
rating = "A"

print(rating)

当我执行此代码并输入“10”时,我在 shell 中得到了内置函数 chr。我希望它根据分数打印 A 或其他字符。例如,如果输入分数是 8 或 9,则必须读取 B。但是,我试图首先通过第一步。我是编程新手,如果我能指出正确的方向,那将大有帮助。

最佳答案

在 python 中,你不能做静态类型(即你不能将变量固定为类型)。 Python 是动态类型。

您需要的是强制输入变量的类型。

# declare score as integer
score = '0' # the default score

# declare rating as character
rating = 'D' # default rating

# write "Enter score: "
# input score
score = input("Enter score: ")

# here, we are going to force convert score to integer
try:
score = int (score)
except:
print ('score is not convertable to integer')

# if score == 10 Then
# set rating = "A"
# endif
if score == 10:
rating = "A"

print(rating)

关于Python:声明为整数和字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42463856/

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