在Python3中反转while序列的输出?

在Python3中反转while序列的输出?,python,Python,任务是编写一个程序,打印函数2^n的图表,如下所示: * ** **** ******** **************** ******************************** **************** ******** **** ** * 我能够编程后半部分(示例中从2^6向下),但我不知道如何反转while函数来创建前半部分。这是我迄今为止的代码: import math n=None while n is None: try: n=input

任务是编写一个程序,打印函数2^n的图表,如下所示:

*
**
****
********
****************
********************************
****************
********
****
**
*
我能够编程后半部分(示例中从2^6向下),但我不知道如何反转
while
函数来创建前半部分。这是我迄今为止的代码:

import math
n=None
while n is None:
    try:
        n=input("Enter an integer for the power of two you wish to represent: ")
        n=int(n)
    except ValueError:
        print("That is not an integer. Please try again.")
    else:
        while n>=0:
            amt=(math.pow(2,n))
            print('*'*int(amt))
            n=int(n)-1
当我输入6时,输出

********************************
****************
********
****
**
*

那么如何让它也做上半部分呢?

您可以计算结果值​​并将它们存储在一个列表中,然后反转列表的两半以获得预期结果

import math
n=None
while n is None:
    try:
        n=input("Enter an integer for the power of two you wish to     represent: ")
        n=int(n)
    except ValueError:
        print("That is not an integer. Please try again.")
    else:
        lst = [math.pow(2,abs(r)) for r in range(0-n, n)]
        lst = lst[len(lst)/2:] + lst[:len(lst)/2+1]
        for item in lst:
           print('*'*int(item))

我不会使用while函数。在我看来,for循环在这里更好。 例如,您可以在两个for循环中使用代码,一个是升序循环,另一个是降序循环

for power in range(n):
    amt=(math.pow(2,power))
    print('*'*int(amt))
for power in range(n-1)[::-1]:
    amt=(math.pow(2,power))
    print('*'*int(amt))

您可以通过以下方式在一个循环中解决此问题:

        i=n*-1
        while i<=n:
          x =n-abs(i)
          amt=(math.pow(2,x))
          print('*'*int(amt))
          i=i+1
i=n*-1

虽然iyou写的第一个图表属于2^n,但它不是。我猜你在试图解释时遗漏了一些东西。第一个图表确实对应。2^0是第一行,2^1是第二行,等等。是的,我注意到了,但当涉及到它的一半时,它会向下移动。你想弄明白吗?是的,这正是我想做的!!!这是可行的,但我对编码非常陌生,而且我真的试图理解它的机制。你能给我解释一下你代码的第四行(“权力…”)是什么,为什么?我不明白n-1的意思。非常感谢您的帮助。范围(n)创建了一个序列,如果n等于5,您可以将其解释为[0,1,2,3,4]
for power
的意思是“对于序列中的每个元素,我称之为‘power’”,所以在第一次迭代中,power等于0,在第二次迭代中,power等于1,等等。第二次for循环也一样,但对于n=5,生成[0,1,2,3](因为n-1),然后通过[:-1]将其反转,因此通过[3,2,1,0]进行迭代。它可以理解吗?你可能会发现它更容易理解,因为
是反向的(范围(n-1))
。谢谢你,但由于我还没有使用for循环,我想我会用Grysik的答案来扩展我的实践:)abs函数做什么?你能像我是个傻瓜一样向我解释这个循环吗?函数abs返回一个数字的绝对值-5返回5。Def和draw做什么?在python中,Def定义函数。所以draw是一个函数。您可以传递到绘图函数并开始打印。
import math

def draw(n):
    i = 0;
    while i <= n:
        d = i
        if i > n /2:
            d = n - i;
        print("*" * int(math.pow(2,d)))
        i+=1
draw(12)
*
**
****
********
****************
********************************
****************************************************************
********************************
****************
********
****
**
*