如何使用Python创建楼梯

时间:2019-11-13 08:08:26

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

我正在学习Python,我的任务之一是使用用户输入的阶梯数来创建以下阶梯:

How many stairs? 6
#####
#####
##########
##########
###############
###############
####################
####################
#########################
#########################
##############################
##############################

到目前为止,这就是我所拥有的:

stairs = int(input("How many stairs? "))
for i in range(1,stairs+1):
    print("#####",end="")
    for j in range(1,i):
        print("#####",end="")
    print()

这给了我

#####
##########
###############
####################
#########################
##############################

但是如何创建与上面相同的第二行?我似乎无法弄清楚...

4 个答案:

答案 0 :(得分:3)

你可以喜欢,

>>> stairs = 6
>>> for i in range(1, stairs+1):
...      print("#####" * i)
...      print("#####" * i)
... 
#####
#####
##########
##########
###############
###############
####################
####################
#########################
#########################
##############################
##############################

答案 1 :(得分:0)

具有两个打印语句的更清洁的版本(很少,很少)可能是:

# NOTE: "l" is individual list of the your data set.
value_for_id = "abc" # Value to be set for id
for i in l: # For each element in l - where l is your individual list
    if i.get("id",None) is not None: # verify if dict with key -> "id" exist
        i["id"] = value_for_id # If exist then update the value for key -> "id"
        break # break and come out of the for loop
else: # if there is no break, i.e. data doesn't have dict with "id" then we will append a new dict to the list. 
    l.append({"id":value_for_id}) # Appending new dict to the list

print (l)

答案 2 :(得分:0)

类似这样的东西:

n = int(input("How many stairs? "))
stair = '#####'

for i in range(1, n + 1):
    print(stair * i)
    print(stair * i)

答案 3 :(得分:0)

有趣的难以理解的一线:

list(map(print, ("#####" * i + "\n" + "#####" * i for i in range(1, int(input("How many stairs?")) + 1))))