浅谈Python基础—判断和循环

yipeiwu_com5年前Python基础

判断

缩进代替大括号。

冒号(:)后换号缩进。

if

test=100
if test>50:
 print('OK')
print('test')

if-elif-else

test=50
if test>200:
 print('200')
elif test<100:
 print('100')
else:
 print('100-200')

列表

test1=[123,456,789]
if 123 in test1:
 print('OK')

字典

test2={'hello':123,'world':456}
if 'hello' in test2:
 print('OK')

循环

while

数值

test=0
while test<10:
 print(test)
 test+=1

集合

test1=set(['hello','world'])
while test1:
 test2=test1.pop()
 print(test2)

for

集合

test3=set(['hello','world'])
for t in test3:#相当于foreach
 print(t)

列表

test4=[123,456,789]
for i in range(3):
 print(test4[i])
test5=[123,456,789,34,5435,26,2362,262,26,5]
for i in range(len(test5)):
 print(test5[i])

continue

test6=[11,12,13,14,15,16,17,18,19,20]
for i in test6:
 if i%2==0:
  print(i) 
 else:
  continue
 print(i)

break

test7=[12,13,14,15,16,17,18,19,20]
for i in test7:
 if i%2==0:
  print(i) 
 else:
  break
 print(i)

以上所述是小编给大家介绍的Python基础—判断和循环详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!

相关文章

深入浅析Python的类

面向对象编程时,都会遇到一个概念,类,python也有这个概念,下面我们通过代码来深入了解下。 创建和使用类 class Dog(): def __init__(self, n...

Python字典中的键映射多个值的方法(列表或者集合)

一个字典就是一个键对应一个单值的映射。如果你想要一个键映射多个值,那么你就需要将这多个值放到另外的容器中, 比如列表或者集合里面。比如,你可以像下面这样构造这样的字典: d = {...

Python基于回溯法子集树模板解决马踏棋盘问题示例

Python基于回溯法子集树模板解决马踏棋盘问题示例

本文实例讲述了Python基于回溯法子集树模板解决马踏棋盘问题。分享给大家供大家参考,具体如下: 问题 将马放到国际象棋的8*8棋盘board上的某个方格中,马按走棋规则进行移动,走遍棋...

Python判断对象是否为文件对象(file object)的三种方法示例

文件操作是开发中经常遇到的场景,那么如何判断一个对象是文件对象呢?下面我们总结了3种常见的方法。 方法1:比较类型 第一种方法,就是判断对象的type是否为file >>...

Python上下文管理器类和上下文管理器装饰器contextmanager用法实例分析

本文实例讲述了Python上下文管理器类和上下文管理器装饰器contextmanager用法。分享给大家供大家参考,具体如下: 一. 什么是上下文管理器 上下文管理器是在Python2....