【问题标题】:How to print a string x times based on user input如何根据用户输入打印字符串 x 次
【发布时间】:2020-10-22 01:29:08
【问题描述】:

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

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

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

这是我的代码:

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

【问题讨论】:

标签: python python-3.x python-2.7


【解决方案1】:
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)

【讨论】:

    【解决方案2】:

    您的代码不起作用,因为您使用相同的变量来迭代时间并更好地使用 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)
    

    【讨论】:

      【解决方案3】:

      最简单的方法是在一行中完成,不需要循环:

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

      【讨论】:

        【解决方案4】:

        你可以使用:

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

        但这可能会给您带来错误,就好像用户输入了一个非整数值一样。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-11-11
          • 2020-11-05
          • 1970-01-01
          • 2022-11-19
          • 2013-10-03
          • 1970-01-01
          • 1970-01-01
          • 2019-06-05
          相关资源
          最近更新 更多