[英]SyntaxError: 'return' outside function keeps happening (Python). Any idea?
錯誤在代碼的底部。
def decimalToRep(num,base):
result = ""
while(num>0):
rem = num % base
if rem in range(10):
result += str(rem)
else:
result += chr(65+(rem%10))
num = num // base
result = result[::-1]
if(result == ""):
return ''
return result
def main():
"""Tests the function."""
print(decimalToRep(10, 10))
print(decimalToRep(10, 8))
print(decimalToRep(10, 2))
print(decimalToRep(10, 16))
#The entry point for program execution
if __name__ == "__main__":
main()
文件“/root/sandbox/convert.py”,第 14 行 return '' ^^^^^^^^^ SyntaxError: 'return' outside function
此錯誤是因為您的 Python 腳本的縮進錯誤。 Python 使用縮進來確定代碼塊的開始和結束位置 - 例如 while 循環和 if 語句。
有關一些示例,請參閱https://www.w3schools.com/python/gloss_python_indentation.asp 。
您的 function 應縮進為:
def decimalToRep(num,base):
result = ""
while(num>0):
rem = num % base
if rem in range(10):
result += str(rem)
else:
result += chr(65+(rem%10))
num = num // base
result = result[::-1]
if(result == ""):
return ''
return result
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.