[英]How to combine these two functions in python
I currently have created this code in python. 我目前已经在python中创建了此代码。 The output is exactly what I want.
输出正是我想要的。 (If you know of a better way to get it, I am open to hear).
(如果您知道一种更好的获取方法,我很乐意听到)。 I want to know how I can combine my functions triangle and triangle2 into one main function.
我想知道如何将我的函数triangle和triangle2合并为一个主要函数。 (My output is a sideways pyramid).
(我的输出是一个侧面金字塔)。
def triangle(n):
for x in range(n):
print ('*'*x)
n = n - 1
def triangle2(n):
for x2 in range(n):
print ('*'*n)
n = n - 1
height = int(input("Enter an odd number greater than 4: "))
triangle(height)
triangle2(height)
Just put the two loops together into one function, but don't alter n
until the second loop (the first doesn't use it anyway): 只需将两个循环放到一个函数中,但不要更改
n
直到第二个循环(第一个循环还是不使用它):
def sideways_pyramid(n):
for x in range(n):
print('*' * x)
for x in range(n):
print('*' * n)
n = n - 1
You can avoid altering n
altogether by counting down with the range()
instead: 您可以通过使用
range()
倒数来避免完全更改n
:
def sideways_pyramid(n):
for x in range(1, n):
print('*' * x)
for x in range(n, 0, -1):
print('*' * x)
The second loop counts down, starting at n
and ending at 1. I also start the first loop at 1, to not print an empty first line (0 times '*'
is an empty string) 第二个循环从
n
开始倒数,从1开始倒数。我也从1开始第一个循环,不打印空的第一行(0倍'*'
是空字符串)
Demo: 演示:
>>> def sideways_pyramid(n):
... for x in range(1, n):
... print ('*' * x)
... for x in range(n, 0, -1):
... print ('*' * x)
...
>>> sideways_pyramid(5)
*
**
***
****
*****
****
***
**
*
def triangle(n):
for x in range(n):
print ('*'*x)
for x in range(n):
print ('*'*n)
n -= 1
height = int(input("Enter an odd number greater than 4: "))
triangle(height)
To keep it as close to your original Code as possible: 为使其尽可能接近原始代码,请执行以下操作:
def triangle2(n):
for x2 in range(n):
print ('*'*n)
n = n - 1
def triangle(n):
for x in range(n):
print ('*'*x)
triangle2(n)
height = int(input("Enter an odd number greater than 4: "))
triangle(height)
You can just call your other function from the first one. 您可以从第一个函数中调用其他函数。
If you always want to run them both in the order specified at the bottom I would do something like this: 如果您始终想同时按底部指定的顺序运行它们,则可以执行以下操作:
def triangle(n):
for x in [y for y in range(n)] + [z for z in range(n, 0, -1)]:
print("*"*x)
height = int(input("Enter an odd number greater than 4: "))
triangle(height)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.