Python 基础 --- 条件判断和循环语句

    技术2022-07-11  82

    条件判断 python 中的逻辑运算符号: 与 and, 或 or, 非 not。 python中使用if - elif - else来实现条件判断,相当于java中的if - else if - else,而且同样可以嵌套使用。 score = 80 if score < 60: print("failed") elif 60 <= score < 80: # 等于 60 <= score and score < 80 print("good") else: print("excellent")

    结果:

    excellent while语句 index = 0 while index < 10: index += 1 # python中没有 ++ ,只能用+=1取代 if index == 6: continue # continue表示跳过下边的语句,开始新的循环 print(index) if index == 8: break # break 跳出循环 else: # else 表示循环中的判断条件为false时候执行的,遇到break时候不会执行 print("after while index : ", index)

    结果

    1 2 3 4 5 7 8 for 语句 for char in "HelloWorld": # for 循环可以作用于字符串,列表,集合,任何序列的项目 print(char.upper()) else: print(char)

    结果

    H E L L O W O R L D d range 语句 range 表示数字的某个范围,从第一个参数开始,到第二个参数结束, [ )的关系,第三个参数表示步长。如果只有一个参数,这表示从0开始到这个参数 for i in range(0, 5, 2): # 相当于java 中的for(int i = 0; i< 5; i +=2 ) print("==", i) for i in range(2): print("--", i) for i in list(range(3)): # 还可以用range来构建列表 print(">>", i)

    结果

    == 0 == 2 == 4 -- 0 -- 1 >> 0 >> 1 >> 2
    Processed: 0.012, SQL: 9