使用for循环来创建圣诞树 [英] Using for loops to create a christmas tree

查看:377
本文介绍了使用for循环来创建圣诞树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个程序,你输入一个数字,程序创建一个christmastree排列的+。例如,如果我输入数字5,程序应该打印:

  + 
+++
+ ++++
+++++++
+++++++++

我到目前为止是:

  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)

您的代码可以通过以下方式变得更紧凑:


  • 使用中缀运算符,用 x + = 2 来替换 x = x + 2 / li>
  • range 自动从零开始,所以 range(0,z)可以被替换为 range(z)

  • 使用字符串乘法,替换使用''* z



应用以下结果: / 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循环来创建圣诞树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆