Python代码报invalid syntax错误:print语句end参数位置语法问题求助
Hey there! Let's break down why your code is throwing that "invalid syntax" error—surprisingly, it's not actually from the print(a,end=" ") line you noticed. Here's what's going wrong:
The Root Cause
When you use input() to get the number of rows, Python returns a string value by default. For example, if you type 5, n becomes the string "5", not the integer 5.
Your flyod function tries to run range(1, n+1)—but you can't add an integer (1) to a string ("5"). This type mismatch is what's causing the error, and sometimes Python's error message might point to the nearest line of code (like the print statement) instead of the actual source of the problem.
The Fix
All you need to do is convert the input to an integer using int() when you assign n:
print(" This is the test for floyds formation ") def flyod(n): a=1 for i in range(1,n+1): for j in range(i): print(a,end=" ") a+=1 print() print() # Convert input to integer here n=int(input("Enter the number of rows baby : ")) flyod(n)
Quick Style Note
As a small side point, you might want to spell the function name floyd instead of flyod to match the official name of the triangle—this just makes your code more readable for other developers. That said, it's purely a style choice; your code will work perfectly once you fix the input type issue.
内容的提问来源于stack exchange,提问作者satishKR

