微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决为什么我在 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")  

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。