Python基础

1.变量

2.用户与程序交互

3. 注释

4.基本数据类型

5.格式化输出

6.基本运算

7.流程控制值 if...else语句

8.流控制之while循环

9.流程控制之for循环

10.练习题

一.变量

什么是变量:

变量即变化的量,核心是‘变’与‘量’二字,变及变化,量即衡量状态。

为什么要有变量:

程序执行的本质就是一系列状态的变化,便是程序执行的直接体现,所以我们需要有一种机制能够反映或者说是保存下来程序执行是的状态以及状态的变化。

如何定义变量:

#变量名(相当于门牌号,指向值所在的空间),等号,变量值。
name = 'grape.lee'
sex = 'male'
age = 17
level = 99

变量的定义规范:

#1.变量名只能是字母、数字、下划线的任意组合。
#2.变量名的第一个字符不能是数字。
#3.关键字不能声明为变量名,如下:
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

变量的定义方式:

#1.驼峰体
AgeOfOldboy = 56
NumberOfStudents = 80
#2.下划线方式:(推荐使用这种)
age_of_oldboy = 56
number_of_students = 80

定义变量名的不好的方式:

#1.变量名为中文、拼音
#2.变量名过长
#3.变量名词不达意

定义变量会有的属性:id,type,value

#1.等号比较的是value
#2.is比较的是id

#强调:
#1.id相同,意味着type和value必定相同。
#2.value相同,type可定仙童,单id不一定相同,如下:
>>> x = 'Info grape'
>>> y = 'Info grape'
>>> id(x)
4363562928
>>> id(y)
4363583792
>>> x == y
True
>>> x is y
False

常量

常量即指不变的量,如 pi 3.141592653...,或者在程序运行过程中不会改变的量。
举例:例如一个人的年龄会变,那就是一个变量,但是在一些情况下,他的年龄是不变的,这时候就是常量。
在python中没有一个专门的语法代表常量,程序员约定俗成用全部大写的变量名带便常量。
AGE_OF_OLDBOY = 56

二.用户与程序交互

#在python3中
input:用户输入的任何值,都会存成字符串类型。
#在python2中
input:用户输入什么类型,就存成什么类型。
raw_input:等于python3中的input

三.注释

代码注释分单行注释,多行注释,单行注释用#号,多行注释用三引号“”“”“”

代码注释的原则:

#1.不用全部加注释,只需要在自己觉的重要的地方或者不好理解的地方加注释就行了。
#2.注释可以是中文或者英文,不要用拼音。

文件头:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

四.基本数据类型

什么是数据,为什么要有多种类型的数据。

#数据即变量的值,如age=18,18则是我们保存的数据。
#变量是用来反映/保持状态以及状态变化的,毫无疑问针对不同的状态就应该用不同类型的数据去标识

数字

#int整型
定义:age = 10 #age = int(10)
用于标识:年龄,等级,省份证号,QQ号,个数等。

#float浮点型
定义:salary = 3.1 #salary = float(3.1)
用于标识:工资,身高,体重等等。

字符串

#在python中,加了引号的字符就是字符串类型,Python并没有字符类型。
定义:name = 'grape'  #name = str('grape')
用于标识:描述性的内容,如姓名,性别,国籍,等。
#单引号,双引号没有区别,只有在单双引号同时存在的特殊情况下才有区别的配合使用。
如:
msg = "My name is Grape , I'm 18 years old."
这里里边的只能用单引号。
#多行字符串的时间用三引号
msg = '''
我欲成仙 快乐齐天
最终还是那些念
缠缠绵绵总不变
写尽了从前以后
'''
print(msg)
View Code
#字符串可以相加 、相乘操作。
>>> name = 'grape'
>>> age = '18'
>>> name + age
'grape18'
>>> name * 5
'grapegrapegrapegrapegrape'

#注意1:字符串的相加操作效率不高
字符串1 + 字符串3,并不会在字符串1的基础之上添加字符串3,而是申请一个全新的内存空间存入字符串1和3,相当于字符串1与字符串3的空间被复制了一份。
#注意2:只能字符串加字符串,不能字符串加其他类型。
View Code

列表

#在[]内用逗号分隔,可以存放多个任意类型的值。
定义:
students = ['wukong','bajie','tangseng']
用于标识:存储多个值的情况,比如一人有多重爱好。
#存放多个学生的信息:姓名,年龄,爱好
>>> students_info=[['egon',18,['play',]],['alex',18,['play','sleep']]]
>>> students_info[0][2][0] #取出第一个学生的第一个爱好
'play'
列表嵌套,取值

字典

#为何还要用字典?
存放一个人的信息:姓名,性别,年龄,很明显是多个值,既然是存多个值,我们完全可以基于刚刚学习的列表去存放,如下
>>> info=['egon','male',18]
定义列表的目的不单单是为了存,还要考虑取值,如果我想取出这个人的年龄,可以用
>>> info[2]
18
但这是基于我们已经知道在第3个位置存放的是年龄的前提下,我们才知道索引2对应的是年龄
即:
        #name, sex, age
info=['egon','male',18]
而这完全只是一种假设,并没有真正意义上规定第三个位置存放的是年龄,于是我们需要寻求一种,即可以存放多个任意类型的值,又可以硬性规定值的映射关系的类型,比如key=value,这就用到了字典
#在{}内用逗号分隔,可以存放多个key:value的值,value可以是任意类型
定义:info={'name':'egon','age':18,'sex':18} #info=dict({'name':'egon','age':18,'sex':18})
用于标识:存储多个值的情况,每个值都有唯一一个对应的key,可以更为方便高效地取值
info={
    'name':'egon',
    'hobbies':['play','sleep'],
    'company_info':{
        'name':'Oldboy',
        'type':'education',
        'emp_num':40,
    }
}
print(info['company_info']['name']) #取公司名


students=[
    {'name':'alex','age':38,'hobbies':['play','sleep']},
    {'name':'egon','age':18,'hobbies':['read','sleep']},
    {'name':'wupeiqi','age':58,'hobbies':['music','read','sleep']},
]
print(students[1]['hobbies'][1]) #取第二个学生的第二个爱好
字典取值

布尔值

#布尔值,一个True一个False
#计算机俗称电脑,即我们编写程序让计算机运行时,应该是让计算机无限接近人脑,或者说人脑能干什么,计算机就应该能干什么,人脑的主要作用是数据运行与逻辑运算,此处的布尔类型就模拟人的逻辑运行,即判断一个条件成立时,用True标识,不成立则用False标识
>>> a=3
>>> b=5
>>> 
>>> a > b #不成立就是False,即假
False
>>> 
>>> a < b #成立就是True, 即真
True

接下来就可以根据条件结果来干不同的事情了:
if a > b 
   print(a is bigger than b )

else 
   print(a is smaller than b )
上面是伪代码,但意味着, 计算机已经可以像人脑一样根据判断结果不同,来执行不同的动作。 
#所有数据类型都自带布尔值
1、None,0,空(空字符串,空列表,空字典等)三种情况下布尔值为False
2、其余均为真 
布尔值,注意项

重点:

#1.可变类型:在id不变的情况下,value可以变,则称为可变类型,如列表,字典

#2. 不可变类型:value一旦改变,id也改变,则称为不可变类型(id变,意味着创建了新的内存空间) 

五.格式化输出

#%s字符串占位符:可以接收字符串,也可接收数字
print('My name is %s,my age is %s' %('egon',18))
#%d数字占位符:只能接收数字
print('My name is %s,my age is %d' %('egon',18))
print('My name is %s,my age is %d' %('egon','18')) #报错

#接收用户输入,打印成指定格式
name=input('your name: ')
age=input('your age: ') #用户输入18,会存成字符串18,无法传给%d

print('My name is %s,my age is %s' %(name,age))

#注意:
#print('My name is %s,my age is %d' %(name,age)) #age为字符串类型,无法传给%d,所以会报错
练习:用户输入姓名、年龄、工作、爱好 ,然后打印成以下格式
------------ info of Egon -----------
Name  : Egon
Age   : 22
Sex   : male
Job   : Teacher 
------------- end -----------------

#答案1.:
info = '''
------------ info of %s -----------
Name  : %s
Age   : %s
Sex   : %s
Job   : %s
------------- end -----------------
''' % ('Egon','Egon',18,'male','Teacher')


print(info)
#答案2:
info = '''
------------ info of {0} -----------
Name  : {1}
Age   : {2}
Sex   : {3}
Job   : {4}
------------- end -----------------
'''.format('Egon','Egon',18,'male','Teacher')
print(info)

#答案3:
info = '''
------------ info of {name} -----------
Name  : {name}
Age   : {age}
Sex   : {sex}
Job   : {job}
------------- end -----------------
'''.format(name='Egon',age=18,sex='male',job='Teacher')
print(info)
字符串格式化练习

六.基本运算

    计算机可以进行的运算有很多种,可不只加减乘除这么简单,运算按种类可分为算数运算、比较运算、逻辑运算、赋值运算、成员运算、身份运算、位运算,今天我们暂只学习算数运算、比较运算、逻辑运算、赋值运算

算数运算

以下假设变量:a=10,b=20

比较运算

以下假设变量:a=10,b=20

赋值运算

以下假设变量:a=10,b=20

逻辑运算

>>> True or Flase and False
True
>>> (True or Flase) and False
False

身份运算

#is比较的是id
#而==比较的是值

七.流程控制值 if...else语句

#1 如果:女人的年龄>30岁,那么:叫阿姨
age_of_girl=31
if age_of_girl > 30:
    print('阿姨好')
#2 如果:女人的年龄>30岁,那么:叫阿姨,否则:叫小姐
age_of_girl=18
if age_of_girl > 30:
    print('阿姨好')
else:
    print('小姐好')
#3 如果:女人的年龄>=18并且<22岁并且身高>170并且体重<100并且是漂亮的,那么:表白,否则:叫阿姨
age_of_girl=18
height=171
weight=99
is_pretty=True
if age_of_girl >= 18 and age_of_girl < 22 and height > 170 and weight < 100 and is_pretty == True:
    print('表白...')else:
    print('阿姨好')
#在表白的基础上继续:
#如果表白成功,那么:在一起
#否则:打印。。。

age_of_girl=18
height=171
weight=99
is_pretty=True

success=True

if age_of_girl >= 18 and age_of_girl < 22 and height > 170 and weight < 100 and is_pretty == True:
    if success:
        print('表白成功,在一起')
    else:
        print('什么爱情不爱情的,爱nmlgb的爱情,爱nmlg啊...')
else:
    print('阿姨好')
'''    4 如果:成绩>=90,那么:优秀

       如果成绩>=80且<90,那么:良好

       如果成绩>=70且<80,那么:普通

       其他情况:很差
'''

score=input('>>: ')
score=int(score)

if score >= 90:
    print('优秀')
elif score >= 80:
    print('良好')
elif score >= 70:
    print('普通')
else:
    print('很差')
#!/usr/bin/env python

name=input('请输入用户名字:')
password=input('请输入密码:')

if name == 'egon' and password == '123':
    print('egon login success')
else:
    print('用户名或密码错误')
用户登录验证功能
#!/usr/bin/env python
#根据用户输入内容打印其权限

'''
egon --> 超级管理员
tom  --> 普通管理员
jack,rain --> 业务主管
其他 --> 普通用户
'''
name=input('请输入用户名字:')

if name == 'egon':
    print('超级管理员')
elif name == 'tom':
    print('普通管理员')
elif name == 'jack' or name == 'rain':
    print('业务主管')
else:
    print('普通用户')
根据用户输入功能输出权限

八.流控制之while循环

为了能够多次的运行同一段代码,while循环就该出场了。

#while循环语法
while 条件:    
    # 循环体
 
    # 如果条件为真,那么循环体则执行,执行完毕后再次循环,重新判断条件。。。
    # 如果条件为假,那么循环体不执行,循环终止
#打印0-10
count=0
while count <= 10:
    print('loop',count)
    count+=1

#打印0-10之间的偶数
count=0
while count <= 10:
    if count%2 == 0:
        print('loop',count)
    count+=1

#打印0-10之间的奇数
count=0
while count <= 10:
    if count%2 == 1:
        print('loop',count)
    count+=1
#死循环
import time
num=0
while True:
    print('count',num)
    time.sleep(1)
    num+=1 
#循环嵌套与tag
  tag=True 
  while tag:
    ......
    while tag:
      ........
      while tag:
        tag=False
#练习,要求如下:
#   1 循环验证用户输入的用户名与密码
#   2 认证通过后,运行用户重复执行命令
#   3 当用户输入命令为quit时,则退出整个程序 

name = 'grape'
password = '123'
while True:
    inp_name = input("请输入用户名:")
    inp_pass = input("请输入密码:")
    if inp_name == name and inp_pass == password:
        print("恭喜你登陆成功")
        while True:
            cmd = input("请输入你想要的操作:")
            if not cmd:continue
            if cmd == 'quit':
                break
            else:
                print(cmd)
    else:
        print("用户名密码错误")
        continue
    break
while练习题
#实现二:使用tag
name='egon'
password='123'

tag=True
while tag:
    inp_name=input('用户名: ')
    inp_pwd=input('密码: ')
    if inp_name == name and inp_pwd == password:
        while tag:
            cmd=input('>>: ')
            if not cmd:continue
            if cmd == 'quit':
                tag=False
                continue
            print('run <%s>' %cmd)
    else:
        print('用户名或密码错误')
View Code
#break用于退出本层循环
while True:
    print "123"
    break
    print "456"

#continue用于退出本次循环,继续下一次循环
while True:
    print "123"
    continue
    print "456"
break continue
#与其它语言else 一般只与if 搭配不同,在Python 中还有个while ...else 语句,while 后面的else 作用是指,当while 循环正常执行完,中间没有被break 中止的话,就会执行else后面的语句
count = 0
while count <= 5 :
    count += 1
    print("Loop",count)

else:
    print("循环正常执行完啦")
print("-----out of while loop ------")
输出
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
循环正常执行完啦
-----out of while loop ------

#如果执行过程中被break啦,就不会执行else的语句啦
count = 0
while count <= 5 :
    count += 1
    if count == 3:break
    print("Loop",count)

else:
    print("循环正常执行完啦")
print("-----out of while loop ------")
输出

Loop 1
Loop 2
-----out of while loop ------
while...else
#1. 使用while循环输出1 2 3 4 5 6     8 9 10
#2. 求1-100的所有数的和
#3. 输出 1-100 内的所有奇数
#4. 输出 1-100 内的所有偶数
#5. 求1-2+3-4+5 ... 99的所有数的和
#6. 用户登陆(三次机会重试)
#7:猜年龄游戏
要求:
    允许用户最多尝试3次,3次都没猜对的话,就直接退出,如果猜对了,打印恭喜信息并退出
#8:猜年龄游戏升级版 
要求:
    允许用户最多尝试3次
    每尝试3次后,如果还没猜对,就问用户是否还想继续玩,如果回答Y或y, 就继续让其猜3次,以此往复,如果回答N或n,就退出程序
    如何猜对了,就直接退出
#使用while循环输出1 2 3 4 5 6     8 9 10
count = 1
while count < 11:
    print(count)
    count += 1
    if count == 7:
        count += 1

count = 1
while count < 11:
    if count != 7:
        print(count)
    count += 1

#求1-100的所有数的和
count = 1
res = 0
while count <= 100:
    res += count
    count += 1
print(res)

#输出 1-100 内的所有奇数
count = 1
while count <= 100:
    if count % 2 != 0:
        print(count)
    count += 1

#输出 1-100 内的所有偶数
count = 1
while count <= 100:
    if count %2 == 0:
        print(count)
    count += 1

#求1-2+3-4+5 ... 99的所有数的和
res = 0
count = 1
while count <= 99:
    if count %2 != 0:
        res += count
    else:
        res -= count
    count += 1
print(res)

#用户登陆(三次机会重试)
uername = 'lrg'
password = '123'
count = 1
while count < 4:
    uinput = input("Please inupt your name:")
    pinput = input("Please input your password:")
    if uinput == uername and pinput == password:
        print("恭喜你登录成功")
        break
    else:
        print("你的用户名密码有误,请重试。")
        count += 1

#7:猜年龄游戏
要求:
    允许用户最多尝试3次,3次都没猜对的话,就直接退出,如果猜对了,打印恭喜信息并退出
'''
count = 1
while count < 4:
    age = input("请输入年龄:")
    if int(age) == 18:
        print("恭喜你猜对了")
        break
    count += 1

#8:猜年龄游戏升级版 
要求:
    允许用户最多尝试3次
    每尝试3次后,如果还没猜对,就问用户是否还想继续玩,如果回答Y或y, 就继续让其猜3次,以此往复,如果回答N或n,就退出程序
    如何猜对了,就直接退出 
'''
count = 0
while True:
    if count == 3:
        res = input("你答错了,是否继续:")
        if res == 'Y' or res == 'y':
            count = 0
        else:
            break
    age = int(input("请输入你猜的年龄:"))
    if age == 18:
        print("恭喜你答对了")
        break
    count += 1
View Code

九.流程控制之for循环

1 迭代式循环:for,语法如下

  for i in range(10):

    缩进的代码块

2 break与continue(同上)
3 循环嵌套
for i in range(1,10):
    for j in range(1,i+1):
        print('%s*%s=%s' %(i,j,i*j),end=' ')
    print()
九九乘法表
1*1=1 
2*1=2 2*2=4 
3*1=3 3*2=6 3*3=9 
4*1=4 4*2=8 4*3=12 4*4=16 
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25 
6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36 
7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49 
8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64 
9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81
for i in range(1,10):
    for j in range(1,i+1):
        if i <= j:
            print('%s*%s=%s' %(i,j,i*j),end=' ')
        else:
            print('%s*%s=%s' %(j,i,i*j),end=' ')
    print()
改良版九九乘法表
1*1=1 
1*2=2 2*2=4 
1*3=3 2*3=6 3*3=9 
1*4=4 2*4=8 3*4=12 4*4=16 
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25 
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36 
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49 
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64 
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
#分析
'''

             #max_level=5
    *        #current_level=1,空格数=4,*号数=1
   ***       #current_level=2,空格数=3,*号数=3
  *****      #current_level=3,空格数=2,*号数=5
 *******     #current_level=4,空格数=1,*号数=7
*********    #current_level=5,空格数=0,*号数=9

#数学表达式
空格数=max_level-current_level
*号数=2*current_level-1

'''

max_level = 5
for current_level in range(1,max_level+1):
    print((max_level - current_level) * ' ' + (2*current_level -1)*'*')
    print()
打印金字塔
    *

   ***

  *****

 *******

*********
金字塔输出结果

十.练习题

1 练习题

简述编译型与解释型语言的区别,且分别列出你知道的哪些语言属于编译型,哪些属于解释型
执行 Python 脚本的两种方式是什么
Pyhton 单行注释和多行注释分别用什么?
布尔值分别有什么?
声明变量注意事项有那些?
如何查看变量在内存中的地址?
写代码
实现用户输入用户名和密码,当用户名为 seven 且 密码为 123 时,显示登陆成功,否则登陆失败!
实现用户输入用户名和密码,当用户名为 seven 且 密码为 123 时,显示登陆成功,否则登陆失败,失败时允许重复输入三次
实现用户输入用户名和密码,当用户名为 seven 或 alex 且 密码为 123 时,显示登陆成功,否则登陆失败,失败时允许重复输入三次
写代码
a. 使用while循环实现输出2-3+4-5+6...+100 的和
b. 使用 while 循环实现输出 1,2,3,4,5, 7,8,9, 11,12 使用 while 循环实现输出 1-100 内的所有奇数

e. 使用 while 循环实现输出 1-100 内的所有偶数

现有如下两个变量,请简述 n1 和 n2 是什么关系?

      n1 = 123456
      n2 = n1
1.#1. 编译型(需要编译器,相当于用谷歌翻译):如C,执行速度快,调试麻烦
    #2. 解释型(需要解释器,相当于同声传译):如python,执行速度慢,调试方便
2.交互模式和脚本模式。
3.单行注释用‘#’号,多行注释用三引号'''''',""""""
4.布尔值包括True,False
5.变量有字母、数字、下划线组成,开头不能用数字,变量不能使用关键字。
6.id(name)
练习题答案
'''
升级需求:
可以支持多个用户登录 (提示,通过列表存多个账户信息)
用户3次认证失败后,退出程序,再次启动程序尝试登录时,还是锁定状态(提示:需把用户锁定的状态存到文件里)
'''

dic={
    'egon1':{'password':'123','count':0},
    'egon2':{'password':'123','count':0},
    'egon3':{'password':'123','count':0},

}
while True:
    name = input("请输入用户名:")
    if not name in dic:
        print("\033[31;1m用户名不存在\033[0m")
        break
    with open('db.txt', 'r') as f:
        lock_file = f.read()
        if name in lock_file.split(','):
            print("\033[31;1m该账号已经被锁定\033[0m")
            break
    pwd = input("请输入密码:")
    if dic[name]['count'] == 2:
        print("\033[31;1m失败次数太多,已经被锁定\033[0m")
        with open('db.txt', 'a') as f:
            f.write(name+',')
        break
    if pwd == dic[name]['password']:
        print("\033[31;1m恭喜你登录成功\033[0m")
        break
    else:
        print("\033[31;1m密码错误\033[0m")
        dic[name]['count'] += 1
练习题升级

 

 

 

 

posted @ 2018-04-04 21:38  grape_lee  阅读(167)  评论(0编辑  收藏  举报