为什么我在 python if 语句中收到这个错误?

问题描述

请帮我解决这个错误!!

#Program by Gerontius Leo

hours=int(input("Enter the number of hours spend on Surfing :")

if (hours >= 5):
    print("The cost of Surfing is Rs"+str(eval(hours*20)))
    else:
        print("The cost of surfing is Rs 101")  

错误文件“/home/main.py”,第 5 行 如果(小时 >= 5): ^ 语法错误:无效语法

解决方法

您错过了第一行中的括号和 if/else 语句的缩进。 例如,我建议您阅读 geeksforgeeks 中的“Python 缩进”。

hours=int(input("Enter the number of hours spend on Surfing :"))

if (hours >= 5):
    print("The cost of Surfing is Rs"+str(eval(hours*20)))
else:
    print("The cost of surfing is Rs 101")  
,

我发现你的代码有两个问题

  1. 第一个问题是第一行的括号,你没有关闭它,因此出现错误。

  2. 第二个问题是 else 语句的缩进,它的缩进数与它尾随的 if 语句不同,简而言之,您尝试添加的 else 语句是注册为 else 语句,在第一个 if 块内跟踪另一个 if 语句,该语句不存在。

代码应该是这样的

hours=int(input("Enter the number of hours spend on Surfing :")) # fix 1 : added an ending bracket

if (hours >= 5):
    print("The cost of Surfing is Rs"+str(eval(hours*20)))
else: # fix 2 : indented the else block the complement the intended if block
    print("The cost of surfing is Rs 101")