= 21: print("elif") else: print("else") Again, nothing remarkable here, just need to learn the synta…" />
返回介绍

Conditional Statements

发布于 2025-02-25 23:43:35 字数 1483 浏览 0 评论 0 收藏 0

a = 20
if a >= 22:
   print("if")
elif a >= 21:
    print("elif")
else:
    print("else")

Again, nothing remarkable here, just need to learn the syntax. Here, we should also mention spacing. Python is picky about indentation - you must start a newline after each conditional statemen (it is the same for the iterators above) and indent the same number of spaces for every statement within the scope of that condition.

a = 23
if a >= 22:
   print("if")
    print("greater than or equal 22")
elif a >= 21:
    print("elif")
else:
    print("else")
a = 23
if a >= 22:
   print("if")
   print("greater than or equal 22")
elif a >= 21:
    print("elif")
else:
    print("else")

Four spaces are customary, but you can use whatever you like. Consistency is necessary.

Python has another type of conditional expression that is very useful. Suppose your program is processing user input or data from a file. You don’t always know for sure what you are getting in that case, and this can lead to problems. The ‘try/except’ conditional can solve them!

a = "1"

try:
  b = a + 2
except:
  print(a, " is not a number")

Here, we have tried to add a number and a string. That generates an exception - but we have trapped the exception and informed the user of the problem. This is much preferable to the programming crashing with some cryptic error like:

a = "1"
b = a + 2

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文