我到目前为止是:
def holidaybush(n):z = n -1 x = 1 为范围(0,n)中的i:为范围(0,z)中的i: print('',end ='') (0,x): print('+',end ='')在范围内(0,z): print(' ',end ='')x = x * 2 x = x-1 z = z-1 print() holidaybush(5)即使我经历了逻辑,它似乎在我的脑海中工作。任何帮助?我只是今天学习了循环,所以我可能不知道他们的一切。
解决方案好的,你有两个问题。首先,当你去做缩进时,你写:
print('',end ='')在python(和其他语言)中,''是一个空的字符串。你应该使用''。
其次,你的 x 增量逻辑似乎是错误的。简单地添加 2 每个循环都可以正常工作,从而使您的程序:
def (0,n):z = n-1 x = 1 对于范围(0,n)中的i:对于范围(0,z)中的i:$ b $ (0,x): print('+',end ='')在范围内(0, ,z): print('',end ='')x = x + 2 z = z-1 print() holidaybush(5)您的代码可以通过以下方式变得更紧凑:
应用以下结果: / p>
de f假期布什(n):z = n - 1 x = 1 我在范围(n): print(''* z +'+'* x + '* z) x + = 2 z- = 1 holidaybush(5)但是您可能想要坚持使用详细版本。
I am trying to create a program where you enter a number and the program creates a "christmastree" arrangement of +'s. For example if I enter the number 5 the program should print:
+ +++ +++++ +++++++ +++++++++What I have so far is:
def holidaybush(n): z=n-1 x=1 for i in range(0,n): for i in range(0,z): print('',end='') for i in range(0,x): print('+',end='') for i in range(0,z): print('',end='') x=x*2 x=x-1 z=z-1 print() holidaybush(5)It does not work quite the way I expect, even though I go through the logic and it seems to work in my head. Any help? I just learned for loops today so I may not know everything about them.
解决方案OK, you have two problems. First, when you go to do your indentation, you write:
print('',end='')In python (and other languages), '' is an empty string. You should use ' '.
Second, your x incrementing logic seems to be wrong. Simply adding 2 each loop works fine, making your program:
def holidaybush(n): z=n-1 x=1 for i in range(0,n): for i in range(0,z): print(' ',end='') for i in range(0,x): print('+',end='') for i in range(0,z): print(' ',end='') x=x+2 z=z-1 print() holidaybush(5)Your code can be made more compact by:
- Using infix operators, replacing x=x+2 with x+=2
- range automatically starts at zero, so range(0,z) can be replaced with range(z)
- Using string multiplication, replacing your inner for loops with ' ' * z
Applying these results in:
def holidaybush(n): z = n - 1 x = 1 for i in range(n): print(' ' * z + '+' * x + ' ' * z) x+=2 z-=1 holidaybush(5)But you might want to stick with the verbose version.
更多推荐
使用for循环来创建圣诞树
发布评论