I don't really know how to accomplish that with the star
function you provided, but there is a way to greatly simplify the star2
function:
def star(startpoint, num):
s = ["*", "* *", "*****"]
print(f"{' ' * startpoint}{s[0]}{' ' * startpoint}" * num)
print(f"{' ' * (startpoint - 1)}{s[1]}{' ' * (startpoint - 1)}" * num)
print(f"{' ' * (startpoint - 2)}{s[2]}{' ' * (startpoint - 2)}" * num)
star(3, 2)
Output:
* *
* * * *
***** *****
A few notes to what changes I made:
- The
str()
wrapper around the s[0]
, s[1]
and s[2]
aren't necessary, as each of its elements are already strings, so adding the str()
wrapper only decreases efficiency.
- It's better to define the
s
list inside the function, or make it an argument that needs to be passed into the brackets, or risk a bug if the list were to be altered elsewhere in your code.
- Use
f
strings instead of constant concatenations for readability.
- Finally, it is possible, but not very necessary for only three values, to use the built-in
enumerate()
method to iterate through the s
list, instead of hard-coding its indices:
def star(startpoint, num):
s = ["*", "* *", "*****"]
for i, v in enumerate(s):
print(f"{' ' * (startpoint - i)}{v}{' ' * (startpoint - i)}" * num)
star(3, 2)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…