python中打印菱形

方法一:

# 原始的办法 total = int(input("How many lines(odd) do you want to print:")) mid = total // 2 + 1 for i in range(1,total): if i < mid: print(" "*(mid-i)+"*"*(2*i-1)) else: print(" "*(i-mid)+"*"*(2*mid-1-(i-mid)*2))

方法二:
total = int(input("How many lines(odd) do you want to print:")) for i in range(-total // 2,total // 2 + 1): if i < 0: print(" "*(-i)+"*"*(5-2*(-i))) else: print(" "*i+"*"*(5-2*i))

【python中打印菱形】方法三:
total = int(input("How many lines(odd) do you want to print:")) for i in range(-total // 2,total // 2 + 1): prespace = (i if i > 0 else -i) print(" "*prespace+"*"*(5-2*prepsace))

后记 多找找规律,发现代码会精简很多^_^

    推荐阅读