Python:声明为整数和字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42463856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:43:50  来源:igfitidea点击:

Python: Declare as integer and character

pythondeclare

提问by John

# 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)

When I execute this code and enter "10" I get, built-in function chr, in the shell. I want it to print A, or another character depending on the score. For example if the input score was 8 or 9 it would have to read B. But, I'm trying to get past the first step first. I am new to programming, and if I can get pointed in the right direction that would help a lot.

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

回答by falsetru

# declare score as integer
score = int

# declare rating as character
rating = chr

Above two statement, assigns the function int, chr, not declaring the variable with the default value. (BTW, chris not a type, but a function that convert the code-point value to character)

上面两条语句,赋值给函数int, chr,而不是用默认值声明变量。(顺便说一句,chr不是类型,而是将代码点值转换为字符的函数)

Do this instead:

改为这样做:

score = 0    # or   int()
rating = ''  # or   'C'   # if you want C to be default rating

NOTEscoreis not need to be initialized, because it's assigned by score = input("Enter score: ")

NOTEscore不需要初始化,因为它是由score = input("Enter score: ")

回答by Edward Aung

In python, you can't do static typing (i.e. you can't fix a variable to a type). Python is dynamic typing.

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

What you need is to force a type to the input variable.

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

# 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)