ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python入门系列(五)一篇搞懂python语句

2022-08-30 10:02:59  阅读:208  来源: 互联网

标签:语句 关键字 Python else python while print 搞懂 than


If语句

elif关键字是pythons表示“如果前面的条件不为真,那么试试这个条件”。

The else keyword catches anything which isn't caught by the preceding conditions.

a = 200
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

如果只有一条语句要执行,则可以将其与If语句放在同一行。

if a > b: print("a is greater than b")

如果只有一条语句要执行,一条用于If,另一条用于else,则可以将所有语句放在同一行中

a = 2
b = 330
print("A") if a > b else print("B")

and关键字是一个逻辑运算符,用于组合条件语句

a = 200
b = 33
c = 500
if a > b and c > a:
  print("Both conditions are True")

or关键字是一个逻辑运算符,用于组合条件语句

a = 200
b = 33
c = 500
if a > b or a > c:
  print("At least one of the conditions is True")

循环语言

while语句

使用while循环,只要条件为true,我们就可以执行一组语句。

i = 1
while i < 6:
  print(i)
  i += 1

使用break语句,即使while条件为true,我们也可以停止循环

i = 1
while i < 6:
  print(i)
  if i == 3:
    break
  i += 1

使用continue语句,我们可以停止当前迭代,然后继续下一个迭代

i = 0
while i < 6:
  i += 1
  if i == 3:
    continue
  print(i)

使用else语句,当条件不再为真时,我们可以运行一段代码

i = 1
while i < 6:
  print(i)
  i += 1
else:
  print("i is no longer less than 6")

for语句

fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)

for循环中的else关键字指定循环完成时要执行的代码块

for x in range(6):
  print(x)
else:
  print("Finally finished!")
for x in range(6):
  if x == 3: break
  print(x)
else:
  print("Finally finished!")

#If the loop breaks, the else block is not executed.

您的关注,是我的无限动力!

公众号 @生活处处有BUG

标签:语句,关键字,Python,else,python,while,print,搞懂,than
来源: https://www.cnblogs.com/bugs-in-life/p/16638249.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有