Python: Declare as integer and character

淺唱寂寞╮ 提交于 2019-12-01 14:40:57
# 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, chr is not a type, but a function that convert the code-point value to character)

Do this instead:

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

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

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

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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!