Python学习笔记1

可使用当下较为流行的Pycharm作为Python的集成开发环境,安装好Pythom和Pycharm后即可开始正式学习。
一、字符串
字符串由引号引用。单引号' '与双引号" "效果等同,还可使用三对单引号''' '''使引用内的字符串可随意换行(三对双引号"""  """效果与三对单引号等同)。
字符串的合并:(只有同类型才能合并)

what he does = 'plays'
his instrument = ' guitar '
his name = 'Robert johnson'
artist intro = his name + what he does + his instrument   
print(artist intro)
输出结果实现三字符串的合并:
Robert Johnson plays guitar

编程时应注意细节,英文中逗号和句号后加空格,运算符前后均加上空格,这些都是良好的编程习惯。

因为只有同类型才能合并,我们有时需要查看变量类型和数据类型转换。查看变量类型可用此法:

Print(type(word))
数据类型转换:
num = 1
string = '1'
num2 =  int(string)
print(num + num2)
中文注释报错的解决方法有两种:
法一:文件开头加#coding: utf-8
法二:找到设置-File Encoding 设置为UTF-8
字符串“相乘”:
words = 'words' * 3
输出words结果为:
wordswordswords
字符串分片与索引:分片与索引可以看做从字符串中找出要截取的东西,然后复制储存到另一个地方,并能够保持源文件不变。
分片的编号从前至后依次为0、1、2、3……  而索引的编号是从后至前依次为-1、-2、-3……
举例说明,一个"My name is Mike"的分片与索引:
name [0]  #代表首字符'M'
name [-4]  #代表倒数第四个字符'M'
name [11:14]  #分片序号11到14,不包含14,代表'Mik'
name [11:15]  #合法,分片序号11到15,不包含15,所以没有分片15也无妨,代表'Mike'
name [5:]  #省略,从分片5到结束,代表'me is Mike'
name [:5]  #省略,从开始到分片5,不包含分片5,代表'My Na'
name [-10:]  #从索引-10到结束,代表'me is Mike'
字符串替换使用replace函数:
replace(original, new)
字符串格式化可使用format函数:
blahblah.format( )
举例说明:
(  ) a word she can get what she (  ) for.
        A. with    B. came
法一:
print('{ } a word she can get what she { } for.'.format('with', 'came'))
法二:
print('{preposition} a word she can get what she {verb} for.'.format(preposition = 'with' , verb = 'came'))
法三:
print('{0} a word she can get what she {1} for.'.format('with','came'))


二、函数
def 定义
arg 参数 (argument 参数)
return 返回结果
def function (arg1 , arg2) :
    ...   return '  '
return是可选的,无return时返回值是none.
注意:冒号‘:'很重要,首先,冒号必不可少,因为冒号后面回车会自动得到缩进,缩进后的语句称为语句块(block),语句块表明了从属关系,事关程序的层次;其次,冒号要用英文输入,中文输入会报错。
函数中传递参数有两种方式,以计算梯形面积的函数为例说明:
def trapezoid area(base up , base down , height):
      return 1/2 * (base up + base down) * height
法一:位置参数
trapezoid area(1 , 2 , 3)
法二:关键词参数
trapezoid area(base up = 1 , base down = 2 , height = 3)
省略关键词则该参数应对应定义时的相关位置,否则出错。
分清参数的命名和变量的命名一定要区分开:
按上面的程序运行,输出结果为1/2*(1+2)*3=4.5无疑,再看下面的程序:
base up = 1
base down = 2
height = 3
trapezoid area(height, base down, base up)
该程序运行结果则为1/2*(3+2)*1=2.5
在计算机世界,所谓base up、base down、height并没有人类世界的意义,它们只是形式上的占位符,按函数传递方式之一的位置参数传递来看,函数的作用是返回值1/2(位置1+位置2)*位置3,因而输出结果为2.5。
给参数设定默认值:定义时赋值即可。(与传递参数的方式区别开)
设定默认值有时可带来方便,例如,可选参数 sep的默认值为空格(ser为seperate缩写,顾名思义为分隔符),将sep的默认值设为'\n',起到换行的作用。
再例如:
request.get(url, headers = head)
该语句常出现于请求网站时,设置headers栏的默认值为head,意为header栏选填。
注意,设定默认值并不意味着被设默认值的变量的值就再也不变了,毕竟是变量而不是常量。
设计自己的函数:
open函数和write函数:
open('C://Users/Hou/Desktop/')
file = open('C://Users/Hou/Desktop/text.txt','w')  #最后面的w代表写入模式,意思是:如果文件不存在则创建,文件存在则覆盖
file.write('hello world')
实例:敏感词替换
def text_create(name, msg):    #注意下划线不可被空格替代,下划线将要定义的text create函数连成一体,这样才能作为整体被定义
    desktop_path = '/Users/Hou/Desktop/'  #open函数要打开一个路径,首先是桌面路径
    full_path = desktop_path + name + '.txt'  #打开桌面路径后加上文件名和后缀即完整路径
    file = open(full_path,'w')  #打开文件
    file.write(msg)  #写入传入参数
    file.close( )  #关闭文本
    print('Done')  #运行完成后的提示
text_create('hello', 'hello world')  #函数调用


def text_filter(word , censored_word = 'lame', changed_word = 'awesome'):
    return word.replace(censored_word , changed_word)
text_filter('Python is lame!')


def Censored_text_create(name,msg):
    clean_msg = text_filter(msg)
    text_create(name,clean_msg)
Censored_text_create('try','lame!lame!lame!)

三、循环与判断
布尔表达式中,True等价于1,False等价于0。
Python对大小写敏感。
比较运算:数值比较、多条件比较、变量比较、字符串比较……
注意:不同型的对象不能用> 、<、>=、<=来比较,但可用==、!=、<>来比较(<>等价于!=)。
例外:浮点型和整数型比较时,类型的不同不影响比较运算。
成员运算符:in/not in 表归属关系
身份运算符:is/is not 表身份鉴别
布尔运算符:not/and/or
条件控制:即if...else的使用。elif用于多条件判断时,置于if和else之间。(else if)
示例:重置密码
password list = ['*#*#','12345']  #列表中存储重置密码口令和用户密码,之后如果需要,还会往里附上用户新密码
def account login( ):
    password = input('password:')
    password correct = password == password list[-1]  #与用户密码匹配
    password reset = password == password list[0]  #触发重置口令
    if password reset:
        print('login success')
    elif password reset:
        new password = input('Enter a new password:')
        password list.append(new password)  #使用append函数附加新密码信息
        print('Your password has changed successfully!')
        account login( )
    else:
        print('Wrong password or invalid input!')
        account login( )  
account login( )
循环(Loop):Python中有两种循环——for循环和while循环。
for循环形式:“如果变量在范围内,就干点什么。 ”
for item in iterable:
      do something
举例:
for num in range(1, 11):
      print(str(num))'+1 = ',num+1)  #str()为str函数,返回括号内数值或数值表达式
嵌套循环(Nested loop)
直接举例:九九乘法表的实现:
for i in range(1, 10)
     for j in range(1, 10)
          print('{ }*{ }={ }'.format(i, j, i*j))
while循环形式:“只要条件成立,就一直做。”
while condition:
         do sth
else ...   (可选)
为避免死循环,要在循环过程中制造某种可使循环终止的条件。使循环终止的方法有两种:
法一:break
count=0
while True:
    print('repeat this line')
    count=count+1
    if count=5:
        break
法二:改变使循环成立的条件
例:改进之前的密码程序,加入功能:输入密码错误三次则禁止输入。
password list = ['*#*#', '12345']  #列表中存储重置密码口令和用户密码,之后如果需要,还会往里附上用户新密码
def account login( ):
    tries = 3
    while tries > 0:
        password = input('password:')
        password correct = password == password list[-1]
        password reset = password == password list[0]
        if password reset:
            print('login success')
        elif password reset:
            new password = input('Enter a new password: ')
            password list.append(new password)
            print('Your password has changed successfully!')
            account login( )
        else:
            print('Wrong password or invalid input!')
            tries = tries-1
            print(tries,' times left')
            account login( ) 
    else:
        print('Wrong password, your password has been suspended')
account login( )








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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值