使用for循环来创建圣诞树

编程入门 行业动态 更新时间:2024-10-27 13:28:47
本文介绍了使用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循环来创建圣诞树

本文发布于:2023-10-19 15:06:48,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:圣诞树

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!