如何在python中设置等于for循环的变量

时间:2014-09-05 01:19:02

标签: python for-loop python-3.x

这是我的代码。如何使bownew =多行*?我不想只在范围(高度)中打印x:打印bownew。我希望bownew等于范围(高度)中的for x。怎么办呢?

height = int(input("Enter an odd number greater than 4: "));
column = height * 2;

screen = [];
bownew = ""

def bow(height):
    for x in range(height):
        screen.append(["*"]*column);

bow(height);

for i in screen:
    bownew = " ".join(i)
print(bownew)

2 个答案:

答案 0 :(得分:2)

不要使用for循环,join希望列表作为参数。如果你想让它有多行,请用换行符加入它们。

bownew = "\n".join(screen)

您还需要使screen成为字符串列表,而不是列表列表:

def bow(height):
    for x in range(height):
        screen.append("*" * column);

整个剧本:

height = int(input("Enter an odd number greater than 4: "));
column = height * 2;

screen = [];
bownew = ""

def bow(height):
    for x in range(height):
        screen.append("*" * column);

bow(height);

bownew = "\n".join(screen)

print(bownew)

试运行:

$ python test.py
Enter an odd number greater than 4: 5
**********
**********
**********
**********
**********

答案 1 :(得分:0)

1 。可能有一个更简单的解决方案,不需要使用 for循环

height = int('Enter an odd number greater than 4: ')
column = height * 2

row = '*' * column
bownew = [row] * height
bownew = '\n'.join(bownew)

print(bownew)

,并且我已经对其进行了测试,

Enter an odd number greater than 4: 5
**********
**********
**********
**********
**********

2 。至于问题(如何在python中将变量设置为等于for循环?),我怀疑您不能使变量等于任何循环,除非使用{{ 1}}。

将使用def

def

这应该给您相同的结果。

祝您编程愉快,希望对您有所帮助。