【问题标题】:Python: Declare as integer and characterPython:声明为整数和字符
【发布时间】:2017-07-16 18:34:33
【问题描述】:
# 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* 中声明变量;您只需分配给它们,必要时创建它们。 (* 类型注释除外,这些仍然不是声明​​。)
  • 您似乎需要阅读教程或停止跳过您正在使用的教程的大部分内容。
  • score == 10 检查不起作用的原因是input() 返回一个字符串,因此您将得到"10" == 10,这是 False。使用int(input("Enter score: ")) 将输入转换为int
  • 我建议你参加 Python 课程。现在先学习一下关于变量和类型的这一课:learnpython.org/en/Variables_and_Types

标签: python declare


【解决方案1】:
# declare score as integer
score = int

# declare rating as character
rating = chr

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

改为这样做:

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

注意 score不需要初始化,因为它是由score = input("Enter score: ")分配的

【讨论】:

  • 那些变量甚至不需要初始化。
  • @TigerhawkT3,谢谢你的评论。 score 不需要初始化,但rating 应该初始化,因为它是有条件分配的。
  • 你真的不认为一旦他们弄清楚了基本的 Python 语法(这应该被视为基础研究和 SO 题外话)那里会有一个 else: rating = 'F' 吗?
  • @TigerhawkT3,不,我不知道。我认为,这取决于编程风格。有些使用if .. else ..,有些喜欢预先初始化默认值。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    • 2012-10-22
    • 2019-03-01
    • 1970-01-01
    相关资源
    最近更新 更多