【问题标题】:Python: User enters number, then a letter, then outputs the letter the amount of times as the number saysPython:用户输入数字,然后输入一个字母,然后按照数字表示的次数输出字母
【发布时间】:2026-01-15 07:20:05
【问题描述】:

Python:用户输入数字,然后输入一个字母,然后按照数字表示的次数输出该字母:

例如

"Enter Integer": 4
"Enter Letter": a

输出

a
a
a
a

这是我目前拥有的,但出现名称错误,' ' is not defined, ' ' is the letter

integer = int(input("Enter a positive integer: "))

character = str(input("Enter a character, e.g. 'a': "))

for i in range(integer):
    print str(character)

如果我输入 4, 4 它会给我

4
4
4
4

可以,但是不会输出字母,我是 python 新手,请见谅

有什么想法吗?

错误链接:https://imgur.com/7pKMp3y

【问题讨论】:

  • 无法重现。我觉得很好
  • EV。 Kounis,我可以发布一个 imgur 链接吗?

标签: python string integer output prompt


【解决方案1】:

在 python 2.7 中使用 raw_input。

integer = raw_input("Enter a positive integer: ")

character = raw_input("Enter a character, e.g. 'a': ")

for i in range(int(integer)):
    print character

请参阅this Stack Overflow 问题,了解有关 python 2.7 中 input 与 raw_input 的解释。

在 Python 2 中,raw_input() 返回一个字符串,而 input() 尝试将输入作为 Python 表达式运行。

由于获取字符串几乎总是你想要的,Python 3 用 input() 做到这一点。正如斯文所说,如果你想要旧的 行为,eval(input()) 有效。

【讨论】:

  • OP 可能正在使用 Python2x。否则4 4 4 4 也不会打印
  • 是的,我可以在 Python 2x 中重现。
  • Arcyaz:在 python 2.7 中使用 raw_input。
  • @cal97g 在使用raw_input() 时,您不需要转换为str
  • @Ev.Kounis - 正确,我已经更新了答案并添加了对 input 与 raw_input 的解释
【解决方案2】:

你可以使用这个网站来学习打字 python

visualize python

python3

integer = int(input("Enter a positive integer: "))
character = str(input("Enter a character, e.g. 'a': "))

for i in range(integer):
    print(character)

python2

integer = int(input("Enter a positive integer: "))
character = raw_input("Enter a character, e.g. 'a': ")

for i in range(integer):
    print character

【讨论】:

  • 这不是问题
  • @Ev. Kounis 感谢提及我,我没有注意到版本问题,所以我修复了我的答案
最近更新 更多