Python-Loops and conditional control statements (if, while, for) in Python language

note:

  • No in Python switch … case… Statement

  • No in Python do … while … Statement

Conditional control statement keywords:

  • if 、elif、else

Loop control statement keywords:

  • while

  • while … else …

  • The for
    Python for loop is more complex and diverse than the statement in C language. It can traverse any sequence of items, such as a list or a string.

languages = ["C", "C++", "Perl", "Python"] 
for x in languages:
	print (x)
  • The range() function
    If you need to traverse a sequence of numbers, you can use the built-in range() function. It will generate a sequence of numbers.

  • Break and continue statements and else clauses in loops.
    1. The break statement can jump out of the loop body of for and while. If you terminate from a for or while loop, any corresponding loop else block will not be executed.
    2. The continue statement is used to tell Python to skip the remaining statements in the current loop block, and then continue to the next loop.

  • The pass statement
    Python pass is an empty statement to maintain the integrity of the program structure. Pass does nothing, and is generally used as a placeholder statement.


from time import  sleep                         # 导入时间模块进行延时,类似于C语言中的库文件
var = 0
value = 0                                       # 变量要有名称与赋值才算完成创建变量,同时也明确了变量的类型

while var <= 10:                                # Python与C语言相比,循环条件不用括号,冒号“:”代替了C语言中的大括号“{ }”,没有了大括号划定程序的范围,所以Python用缩进区分代码块
    if var == 5:                                # Python中条件控制语句的关键字是:if elif  else 。其中elif 类似于 C语言中的 else if
        print("var = 5")
    elif var == 8:
        print("var = 8")
    else:                                       # 条件可以为空,但一定要又冒号 “:”,否则会报错
        print(var)

    var += 1                                    # i+=1 与 i=i+1 与 i++
    sleep(1)

print("Good Bye!while~~~~ ")                    # 看缩进的范围,划定代码块的范围,所以print()在while()循环外执行



"""
Python中条件控制语句的关键字是:if elif  else 

Python中的循环语句while、for循环的用法:



"""

'''

i+=1 与 i=i+1 与 i++ 三者的区别:
1、i += 1  等价于 i = i + 1 但是前者的运行速度预算符的优先级要高于后者
2、i++     是有值后自增


'''



Reference

Guess you like

Origin blog.csdn.net/Naiva/article/details/106273361