Python学习笔记 2

1.python语句

1. python条件语句:

if 判断条件:
    执行语句……
else:
    执行语句……

if 语句的判断条件可以用>(大于)、<(小于)、==(等于)、>=(大于等于)、<=(小于等于)来表示其关系。

当判断条件为多个值时,可以使用以下形式:

if 判断条件1:
    执行语句1……
elif 判断条件2:
    执行语句2……
elif 判断条件3:
    执行语句3……
else:
    执行语句4……

2. Python while循环语句

Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其基本形式为:

while 判断条件:
    执行语句……

循环使用 else 语句

在 python 中,while … else 在循环条件为 false 时执行 else 语句块:

#!/usr/bin/python

count = 0
while count < 5:
   print count, " is  less than 5"
   count = count + 1
else:
   print count, " is not less than 5"

3. Python for循环语句
Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。

for循环的语法格式如下:

for iterating_var in sequence:
   statements(s)

示例如下:
#!/usr/bin/python
# -*- coding: UTF-8 -*-

for letter in 'Python':     # 第一个实例
   print '当前字母 :', letter

fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        # 第二个实例
   print '当前水果 :', fruit

print "Good bye!"

4.Python break 语句

Python break语句,就像在C语言中,打破了最小封闭for或while循环。

break语句用来终止循环语句,即循环条件没有False条件或者序列还没被完全递归完,也会停止执行循环语句。

break语句用在while和for循环中。

如果您使用嵌套循环,break语句将停止执行最深层的循环,并开始执行下一行代码。

5.Python continue 语句

Python continue 语句跳出本次循环,而break跳出整个循环。

continue 语句用来告诉Python跳过当前循环的剩余语句,然后继续进行下一轮循环。

continue语句用在while和for循环中。

6.Python pass 语句

Python pass是空语句,是为了保持程序结构的完整性。

pass 不做任何事情,一般用做占位语句。

2.练习小记

1.python字符串分割

一般情况下直接使用string.split()函数即可解决,对于复杂分割就需要以下方法了:

import re
result=re.split(r'[;,.\s]\s*',halo)
#对多个不同字符连接的字符串进行分割

2. python切片
这里写图片描述

halo='halo'
halo[::-1]#反转字符串
halo[::2]#每隔两个字符切去一片

3.判断包含

halo='halololololo world'
if 'lo' in halo:
    print('yes')
else:
    print('no')

4. 重复输出

print('****'*10)

5.解决整数除法没有小数位(python2.X)

from __future__ import division
print '{} + {} = {}'.format(num1,num2,num1/num2)

6.密码隐藏

>>> import getpass
>>> password=getpass.getpass('please input password: ')
Password: 
>>> print password
halo
>>> 

7. 字符串分割反转

>>> halo="hi halo world zhang ce you are great"
>>> halolst=halo.split(' ')
>>> halorev=halolst[::-1]
>>> result=' '.join(halorev)
>>> print result
great are you ce zhang world halo hi
>>> 

8. 字符串两端填充

>>> halo.center(50,'*')
'*******hi halo world zhang ce you are great*******'
>>> 

9.提取字符串中的特定类型的字符并且组合输出:
对于一般字符有以下方法可以使用(示例halo为字符)

halo.capitalize  halo.endswith    halo.index       halo.isspace     halo.lower       halo.rindex      halo.split       halo.title
halo.center      halo.expandtabs  halo.isalnum     halo.istitle     halo.lstrip      halo.rjust       halo.splitlines  halo.translate
halo.count       halo.find        halo.isalpha     halo.isupper     halo.partition   halo.rpartition  halo.startswith  halo.upper
halo.decode      halo.format      halo.isdigit     halo.join        halo.replace     halo.rsplit      halo.strip       halo.zfill
halo.encode      halo.html        halo.islower     halo.ljust       halo.rfind       halo.rstrip      halo.swapcase    
halo='halo23halo43haloYYY2342'
num = ''
for i in halo:
    if i.isdigit():
        if not num:
            num = i
        else:
            num = num + i
print 'The picked number string is: %s' %num

Result:
The picked number string is: 23432342

9. 句子反转
要求:传入多组数据,每组一行,由多个单词组成的句子,请把所有输入的数据按组按单词反转输出:

def rev(lst):
    for item in lst:
        splitstr=item.split(' ')
        reverstr=splitstr[::-1]
        result=' '.join(reverstr)
        print(result)
lst=['halo the world','good the world','he ha he hei ya']
rev(lst)

这里写图片描述
10.判断用户输入的变量名称是否合规:

# -*- coding: UTF-8 -*-
import string
import sys
def parTest(par):
    headcontain=string.letters+'_'
    bodycontain=string.digits+'_'+string.letters
    parhead=par[0:1]
    parbody=par[1:]
    if parhead in headcontain:
        print 'head ok'
    else:
        print 'The head of a par can only start with alpha or "_"'
        sys.exit(0)
    for i in parbody:
        if i in bodycontain:
            pass
        else:
            print 'The body of a par can only contain number/alpah or "_"'
    print 'oooo'
print 'test1***************'
parTest('ha?lo')
print 'test2***************'
parTest('ha*lo')
print 'test3***************'
parTest('ha!lo')
print 'test head***************'
parTest('!ha!lo')

这里写图片描述
11.质数判断:

基本判断思路:
在一般领域,对正整数n,如果用2到之间的所有整数去除,均无法整除,则n为质数。
质数大于等于2 不能被它本身和1以外的数整除
# -*- coding: UTF-8 -*-
from math import sqrt
def is_prime(n):
    if n == 1:
        return False
    for i in range(2, int(sqrt(n))+1):
        if n % i == 0:
            print 'number {} is not prime!'.format(n)
            return False
    print 'number {} is  prime!'.format(n)

is_prime(7)
is_prime(9)
is_prime(19)
is_prime(59)
is_prime(79)
is_prime(177)

这里写图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值