【问题标题】:How to display an integer many times如何多次显示一个整数
【发布时间】:2021-07-08 00:57:18
【问题描述】:

我想创建一个函数,将 2 加到我们想要的整数上。它看起来像这样:

>>> n = 3 
>>> add_two(n)
Would you like to add a two to n ? Yes
The new n is 5
Would you like to add a two to n ? Yes
the new n is 7
Would you like to add a two to n ? No

谁能帮帮我?我不知道如何在不调用函数的情况下打印句子。

【问题讨论】:

  • 你要找的是一个'while'语句。
  • 谢谢你!

标签: python string input integer display


【解决方案1】:

这个想法是在你的函数中使用while 循环,每次你告诉它时它都会继续添加两个。否则,它会退出。

鉴于这些知识,我建议您先自己尝试一下,但我会在下面提供一个解决方案,您可以与您的解决方案进行比较。


那个解决方案可以简单到:

while input("Would you like to add a two to n ?") == "Yes":
    n += 2
    print(f"the new n is {n}")

但是,由于我很少错过改进代码的机会,因此我也会提供更复杂的解决方案,但有以下区别:

  • 它先打印起始编号;
  • 它允许添加任意数字,如果没有提供则默认为两个;
  • 输出文本更人性化;
  • 它需要一个是或否的答案(实际上以大写或小写yn 开头的任何内容都可以,其他所有内容都被忽略并重新提出问题)。
def add_two(number, delta = 2):
    print(f"The initial number is {number}")

    # Loop forever, relying on break to finish adding.

    while True:
        # Ensure responses are yes or no only (first letter, any case).

        response = ""
        while response not in ["y", "n"]:
            response = input(f"Would you like to add {delta} to the number? ")[:1].lower()

        # Finish up if 'no' selected.

        if response == "n":
            break

        # Otherwise, add value, print it, and continue.

        number += delta
        print(f"The new number is {number}")

# Incredibly basic/deficient test harness :-)

add_two(2)

【讨论】:

    【解决方案2】:

    您可以在 add_two() 函数中使用循环。因此,您的函数可以在不调用函数的情况下打印句子。

    【讨论】:

      【解决方案3】:

      上面的答案详细描述了要做什么以及为什么,如果您正在寻找满足您要求的非常简单的初学者类型代码,请尝试以下操作:

      n = 3
      
      while True:
          inp = input("Would you like to add 2 to n? Enter 'yes'/'no'. To exit, type 'end' ")
          if inp == "yes":
              n = n + 2
          elif inp == "no":
              None
          elif inp == "end":      # if the user wants to exit the loop
              break
          else:
              print("Error in input")     # simple input error handling
          print("The new n is: ", n)
      

      【讨论】:

        【解决方案4】:

        您可以将其包装在一个函数中。一旦不满足是条件,函数就会中断

        def addd(n):
            while n:
                inp = input('would like to add 2 to n:' )
                if inp.lower() == 'yes':
                    n = n + 2
                    print(f'The new n is {n}')
                else:
                    return
        
        addd(10)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-10-11
          • 2014-03-09
          相关资源
          最近更新 更多