设为首页 加入收藏

TOP

python 学习 之 第二章(条件、循环和其他语句)(一)
2017-10-09 17:33:44 】 浏览:736
Tags:python 学习 第二章 条件 循环 其他 语句

1.    简单的条件执行语句( if )

num = int( input("enter a number\n") )

if num == 0:

         print("num = 0\n")

else:

         print("num != 0\n")

稍微复杂一点的执行语句:

num = int( input("enter a number\n") )

if num == 0:

         print("num = 0\n")

elif num > 0:

         print("num > 0\n")

else:

         print("num < 0\n")

从上面的例子可以看出,条件判断句,就是根据一个执行语句的结果的bool值,来确定句子下面的语句是否执行,

if 判断语句(如果为真,执行:后面的句子,否则执行else 或者elif 后面的语句),

记住if也罢,elif也罢,else也罢,都不能忘记后面的冒号:两个点;否则都是错误的;

2.    简单的循环执行语句(while)

4.1 一个简单的循环输出

x = 1

while x <= 5:

    print (x)

    x += 1

1

2

3

4

5

4.2 一个稍微复杂一点的while循环:

name = input("please enter your name:\n")

while name not in ('aiyq195','wgj','yb'):

    print("the name is err\n")

    name = input("please enter your name,too:\n")

please enter your name:

j

the name is err

please enter your name,too:

ni

the name is err

please enter your name,too:

aiyq195

4.3 判断如何退出while循环

x = int(input("Enter a number to exit the loop!\n"))

while x:

    print ("The number unable to exit the loop!\n")

x = int(input("Enter a number to exit the loop!\n"))

 

在IDE版本中执行上面的语句,得到下面的结果:

 

Enter a number to exit the loop!

8

The number unable to exit the loop!

Enter a number to exit the loop!

-1

The number unable to exit the loop!

Enter a number to exit the loop!

0

 

从上面的结果,我们找到了如何退出while循环的条件,也就是while循环退出的条件只有一种可能,就是你的判断条件执行结果为0。

特别是我们在执行while循环时,使用的判断条件为数字的时候,他不会因为你的值为负数,他就会退出;

 

 

3.    for循环的例子

5.1 简单的for循环说明

while循环非常的灵活,它可以用来在任何条件为真的情况下重复执行一个代码块。但是有的时候,需要量体裁衣。比如要为一个集合的每个元素执行一个代码块。这个时候可以使用for语句:

words = ['this','is','an','ex','parrot']

for word in words:

print (word)

 

======================= RESTART: E:/python/pyth/for.py =======================

this

is

an

ex

parrot

可以由上面的句子看出来,一个for循环,他的循环是有一个依据的,也就是,它可能是根据你已经定好的一个列表的或者一个元组、字典里的元素来走它的循环依据;

5.2 for循环的一个关键字 range()

for number in range(0,10):

    print(number)

 

for number in range(0,10,2):

print(number)

在IDE上执行结果如下:

0

1

2

3

4

5

6

7

8

9

 

0

2

4

6

8

查看上面的结果知道,range()函数,可以迭代一些数字,让for循环以此来作为判断条件执行,其中,也包括了步长,也就是第三个参数,你可以由此来确定;

 

1.    python 中的赋值语句

赋值很简单的一个赋值语句就可以搞定,或者一片句子就可以实现的功能;但是也需要稍微的来写些内容,让你记住一些赋值的方法,在你应用的时候,你会发现一些应用时的方便;

并行赋值句子

>>> x = 1 ;y = 2

>>> y

2

>>> x

1

其实所谓的并行赋值,就是将几个变量的赋值语句用一个分号隔开,然后,写入到一行中;

序列解包赋值句子

多个赋值操作可以同时进行:

>>> x,y,z = 1,2,3

>>> x

1

>>> y

2

>>> z

3

>>> print (x,y,z)

1 2 3

而且,它竟然可以直接调换值;(在c中,需要使用一个临时值,才能实现这个功能)

>>> x,y = y,x

>>> print (x,y,z)

2 1 3

在python书中,解释道上面所做的事情,叫做序列解包(sequence unpacking) 或递归解包 – 将多个值的序列解开,然后放到变量的序列中。更形象的说明就是下面这个:

>>> values = 1,2,3

>>> values

(1, 2, 3)

>>> x,y,z = values

>>> x

1

>>> y

2

当函数或者方法返回元组(或者其他序列或可迭代对象)时,这个特性尤其有用。

假如需要获取(或删除

首页 上一页 1 2 3 4 下一页 尾页 1/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python 程序员都会喜欢的 6 个库 下一篇机器学习:Python实现最小均方算法..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目