循环

本文详细介绍了Python的基础语法,包括while循环、列表操作、for循环及continue的使用方法,并提供了多个实用示例。

1 . while 循环

while condition:
    statement1
    statement2

例子:

#! /usr/bin/python
n = 0
while n < 5 :
    print (n)
    n = n + 1

[test@iZuf60gzvn9k0h3fuhr6y5Z python]$ ./test.py 
0
1
2
3
4

 

斐波那契数列

如下被以递归的方法定义:F(1)=1,F(2)=1, F(n)=F(n-1)+F(n-2)(n>=2,n∈N*   这个数列从第3项开始,每一项都等于前两项之和

#! /usr/bin/python
a,b = 0, 1
while b < 100 :
    #print (b)
    print (b,end=' ')
    a , b = b , a + b
print ()
a , b = b , a + b   先计算在赋值  a=b   b=(a+b)
print () 默认换号 ,可以更改end的类型 end =' '


乘法表

打印10以内的乘法表

#! /usr/bin/python
i = 1
print ("-"*50)
#字符串若是乘上整数 n,将返回由 n 个此字符串拼接起来的新字符串
while i < 11 :
	n = 1
	while n < 11 :
	        print ("{:4d}".format(i * n), end = ' ')  
		#print ("{:x>4d}".format(i * n), end = ' ')
		#print ("{:x<4d}".format(i * n), end = ' ')
                #:4d 左边补空格    >4d 左边补x    x<4d 右边补x
		n = n + 1
	print ()
	i = i + 1

 

打印星号

#! /usr/bin/python
n = '* '
i = 1
while i < 10 :
	x = n * (10 - i)
	y = i * '  '
	print (y + x)
	i = i + 1

 

正等登各式各样的

 

 

2.列表

 中刮号之间一列用逗号分隔的值,列表中的原始不一定事同一类型的值。

a=[1,'zw','hello','wd']

有索引 ,可以为负数   -4~3

 a[0] = 1     a[-1]='wd'

切片 用:隔开  前闭后开

>>> a[1:3]
['zw', 'hello']
>>> a[:3]
[1, 'zw', 'hello']
>>> a[2:]
['hello', 'wd']
>>> a[2:-1]
['hello']
>>> a[-1:-1]
[]
>>> a[-1:1]
[]
>>> a[1:-1]
['zw', 'hello']

Python 能够优雅地处理那些没有意义的切片索引:一个过大的索引值(即大于列表实际长度)将被列表实际长度所代替,当上边界比下边界大时(即切片左值大于右值)就返回空列表:

设置步长 ::

>>> a[0::2]
[1, 'hello']
>>> a[1::2]
['zw', 'wd']
>>> a[1::3]
['zw']
>>> a[0::3]
[1, 'wd']
>>> 

列表链接

>>> a+['YOU',999,88]
[1, 'zw', 'hello', 'wd', 'YOU', 999, 88]

列表修改

>>> a[0]=4
>>> a
[4, 'zw', 'hello', 'wd']
>>> a
[4, 'wd', 'a', 'b', 'c', 'd']
>>> a[2:4]=['5']  #改变列表 少元素默认删除
>>> a
[4, 'wd', '5', 'c', 'd']
>>> a[2:4]=[]  #空列表删除
>>> a
[4, 'wd', 'd']>>> a[:]=[]
>>> a
[]
>>> 

检查某个值是否在列表中

>>> a=['a','b','c','d','e']
>>> 'c' in a
True
>>> 'f' in a
False
>>> len(a)
5
# 判断列表是否为空
if list_name: # 列表不为空
    pass
else: # 列表为空
    pass
 
 

3.for

通过 for 语句我们可以使用 for 循环。Python 里的 for 循环与 C 语言中的不同。这里的 for 循环遍历任何序列(比如列表和字符串)中的每一个元素。下面给出示例:

#! /usr/bin/python
a = [1 ,2 ,3, 4, 5, 6]
for i in a :
    print (i ,end='|')
print()    
for i in a[::2]:
    print (i,end='|')    
print()    

[test@iZuf60gzvn9k0h3fuhr6y5Z python]$ ./test.py 
1|2|3|4|5|6|
1|3|5|

range() 

for i in range(0,10,3):
    print (i)
0 3  6 9

 

4.continue

while True :    
    a = int ( input("please input an integer:"))
    if a < 0 :
        continue
    elif a == 0 :
        break
    else :
        print ('--')

 

 


转载于:https://www.cnblogs.com/think-cl/p/9415192.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值