【问题标题】:While loop creatingWhile 循环创建
【发布时间】:2016-02-18 03:50:26
【问题描述】:

我正在用 Python 编写一个程序,它定义了一个接受单个参数的函数。该函数必须是一个while循环,返回它等于的16的最大幂。但是,我不确定如何编写 while 循环。

【问题讨论】:

标签: python python-3.x while-loop


【解决方案1】:

Python Docs

while True:
    n = input("Please enter 'hello':")
    if n.strip() == 'hello':
        break

所以,通俗地说

while <condition>:
    ...

【讨论】:

    【解决方案2】:

    我无法完全理解您的问题,但这里是如何执行 while 循环以将 x 设为输入的 16 次方:

    def loop_function(x):
        y = 1
        start = x
        while y != 16:
            result = start * x
            start = result
            y += 1
        return result
    
    print loop_function(3)
    

    以上代码将返回 3^16 的答案,即 43046721

    你甚至可以把它变成一个更广泛的函数两个参数

    def loop_function(x, y):
        z = 1
        start = x
        while z != z:
            result = start * x
            start = result
            z += 1
        return result
    
    print loop_function(3, 2)
    

    以上代码将返回 9 即 3^2

    【讨论】:

      猜你喜欢
      • 2021-02-20
      • 2011-03-05
      • 2012-10-07
      • 1970-01-01
      • 2013-12-20
      • 2021-02-04
      • 2018-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多