这是我的代码,我正在尝试添加递归,因此当用户输入一个小于 0 的数字时,它不仅会说无效输入,还会显示原始提示,让他们尝试另一个数字。我也在尝试将我的 for 循环更改为 while 循环。有什么帮助吗?
space = '\t'
star = '*'
size = int(input("Enter the height of the pattern (must be greater than 0): "))
if size <= 0 :
print("Invalid Entry!\n")
for i in range(0, size) :
star_count = 2 * i - 1
line = space * (size - i - 1)
if i == 0 :
line += "1"
else :
line += str(2 * i) + space
line += (star + space) * star_count
if i > 0 :
line += str(2 * i + 1)
print(line)
输出应该是这样的
1
2 * 3
4 * * * 5
6 * * * * * 7
8 * * * * * * * 9
答案 0 :(得分:0)
如果大小不大于 0,您可以添加一个条件来重复输入循环
space = '\t'
star = '*'
size = -1
while size <= 0:
size = int(input("Enter the height of the pattern (must be greater than 0): "))
if size <= 0 :
print("Invalid Entry!\n")
for i in range(0, size) :
star_count = 2 * i - 1
line = space * (size - i - 1)
if i == 0 :
line += "1"
else :
line += str(2 * i) + space
line += (star + space) * star_count
if i > 0 :
line += str(2 * i + 1)
print(line)
所以输出是
Enter the height of the pattern (must be greater than 0): -2
Invalid Entry!
Enter the height of the pattern (must be greater than 0): 0
Invalid Entry!
Enter the height of the pattern (must be greater than 0): 3
1
2 * 3
4 * * * 5
答案 1 :(得分:0)
for 循环有什么问题?
space = '\t'
star = '*'
while 1:
size = int(input("Enter the height of the pattern (must be greater than 0): "))
if size > 0:
break
print("Invalid Entry!")
print("Please Try again.")
i = 0
while i < size:
star_count = 2 * i - 1
line = space * (size - i - 1)
if i == 0 :
line += "1"
else :
line += str(2 * i) + space
line += (star + space) * star_count
if i > 0 :
line += str(2 * i + 1)
i += 1
print(line)
答案 2 :(得分:0)
此代码的限制是您必须始终输入 3 才能获得打算根据您的查询获得的答案
space = '\t'
star = '*'
size = int(input("Enter the height of the pattern (must be greater than 0): "))
while size <= 0 :
print("Invalid Entry!\n")
size = int(input("Enter the height of the pattern (must be greater than 0): "))
for i in range(0, size) :
star_count = 2 * i - 1
line = space * (size - i - 1)
if i == 0 :
line += "1"
else :
line += str(2 * i) + space
line += (star + space) * star_count
if i > 0 :
line += str(2 * i + 1)
print(line)