對於一個任務,如果字符等於一個偶數,我想用一個用戶輸入做一個三角形。三角形假設打印高達5行,其左側應該是字符串的左半部分,而三角形的右側應該是字符串的右側。從用戶輸入創建一個三角形字符
Example of what the triangle is suppose to look like
問題是我無法弄清楚如何劃分了我的一半三角形沒有硬編碼,或如何正確地顯示沒有環的白色空間(未在分配允許)。現在,如果我把在 「AB」,它將返回:
aabb
aabbaabb
aabbaabbaabb
aabbaabbaabbaabb
aabbaabbaabbaabbaabb
相反的:
aabb
aaaabbbb
aaaaaabbbbbb
aaaaaaaabbbbbbbb
aaaaaaaaaabbbbbbbbbb
這裏是我的代碼:
#GET Users String
userString = input("Please enter a string with a value of 7 or less characters: ")
#CALCULATE IF userString is less than or equal to 7 and is even
if len(userString) <= 7 and len(userString) % 2 == 0:
print (" " * 5 + userString)
print(" " * 4 + userString * 2)
print(" " * 3 + userString * 3)
print(" " * 2 + userString * 4)
print(" " + userString * 5)
#CALCULATE IF userString is less than 7 but and off
elif len(userString) <=7 and len(userString) % 2 == 1:
print("You are odd")
#CALCULATE IF userString is over 7 characters
else:
print ('The string is too long. \nGood-bye!')
如果你不允許使用循環,我想你應該使用遞歸... – Julien