如何根据用户输入将字符串打印x次

2024-05-23 18:19:26 发布

您现在位置:Python中文网/ 问答频道 /正文

Hi, Disclaimer: I am new to python and coding in general

我正在尝试制作一个简单的应用程序,可以将一个单词打印特定的次数

现在运行我的代码,尽管我最初输入了(次),程序在退出之前只打印(word)一次

这是我的密码:

# Double Words

times = input('Ho w many times would you like to repeat your word?')

word = input('Enter your word:')

for times in times:
    print(word)

Tags: andtoin应用程序newinputyourhi
3条回答

您的代码不起作用,因为您使用相同的变量来迭代时间,最好使用range():

# Double Words

times = input('Ho w many times would you like to repeat your word?')

word = input('Enter your word:')

for time in range(int(times)):
    print(word)

最简单的方法是一行完成,如下所示,无需循环:

times = input('Ho w many times would you like to repeat your word?')
word = input('Enter your word:')

print('\n'.join([word] * int(times)))

'\n'.join()在每个元素之间添加换行符

[word] * int(times)生成一个times长列表-每个元素都是word,这样您就可以在其上使用join()

注意:如果您不关心条目之间的换行,您可以只做print(word * int(times))

times = int(input('How many times would you like to repeat your word?'))

word = input('Enter your word:')

for i in range(times):
    print(word)

相关问题 更多 >