Day1-Python入门

一、什么是Python
Python是一门计算机语言,学习它就跟学习英语一样,想学好它,就要跟学好英语一样。单词(关键字)+语法
Python解释器是使用C语言编写的。

目前Python主要应用领域

1 WEB开发——最火的Python web框架Django, 支持异步高并发的Tornado框架,短小精悍的flask,bottle;                 
2 网络编程——支持高并发的Twisted网络框架, py3引入的asyncio使异步编程变的非常简单;                                 
3 爬虫——爬虫领域,Python几乎是霸主地位,Scrapy\Request\BeautifuSoap\urllib等,想爬啥就爬啥;                 
4 云计算——目前最火最知名的云计算框架就是OpenStack,Python现在的火,很大一部分就是因为云计算                              
5 人工智能——谁会成为AI和大数据时代的第一开发语言?已是一个不需要争论的问题。Python 作为 AI 时代头牌语言的位置基本确立;                 
6 自动化运维——问问中国的每个运维人员,运维人员必须会的语言是什么?10个人相信会给你一个相同的答案,它的名字叫Python                      
7 金融分析——到目前,Python是金融分析、量化交易领域里用的最多的语言                                               
8 科学运算——Python越来越适合于做科学计算,和科学计算领域最流行的商业软件Matlab相比,Python是一门通用的程序设计语言;                
9 游戏开发——在网络游戏开发中Python也有很多应用。相比Lua or C++,Python 比 Lua 有更高阶的抽象能力,Python更适合作为一种Host语言。

二、编程语言分类
机器语言:优点是最底层,执行速度快;缺点是最复杂,开发效率低;
汇编语言:优点是比较底层,执行速度快;缺点是复杂,开发效率低;
高级语言:站在(奴隶主)的角度,说人话,即用人类的字符去编写程序,屏蔽了硬件的操作。

高级语言又分为:
编译型(需要编译器,相当于用谷歌翻译):如C语言,执行速度快,调试麻烦。语言执行速度快,不依赖语言运行环境,跨平台差;
解释型(需要解释器,相当于同声传译):如python,执行速度慢,调试方便。跨平台好,一份代码,到处使用,缺点是执行速度慢,依赖解释器运行。
这里强调下:速度不是关键(瓶颈理论),开发效率高才是王道。。。机器执行1s,考虑网络延迟10s;高级语言执行3s,网络延迟10s,同样整个过程都是10s。
三、第一个Python程序
进入解释器的交互模式:调取方便,无法永久保存代码;
脚本文件的方式(notepad++):永久保存代码;
PS. python解释器执行程序是解释执行,即打开文件读取内容,因此文件的后缀名没有硬性限制,但通常定义为.py结尾。
执行Python程序的三个阶段:

1. 启动python.exe软件,并放入内存中;

2. 由python解释器将文件内容由硬盘读取到内存中;

3. 解释执行刚刚读进来的内容。

四、变量
程序执行的本质就是一系列状态的变化,变是程序执行的直接体现,所以我们需要有一种机制能够反映或者说是保存下来程序执行时状态以及状态的变化。
变量名(相当于门牌号,指向值所在的空间),等号,变量值;

变量的定义规范

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']

实操

# print('hello world')
# age=10
# #定义一个变量,会有三个特征:id,type,value
#
# print(id(age),type(age),age)
#
# name='egon'
# print(id(name),type(name),name)

# #id不是真正的内存,是python自定义的。

# print=123
# print('abcde')
# #不能用特殊字符做变量名

#变量的命名方式:
#1:驼峰体
# AgeOfOldboy=73
#2:下划线(推荐)
# age_of_oldboy=73

# x='age_of_guoxq:18'
# y='age_of_guoxq:18'
# print(id(x),id(y))

#常量
AGE_OF_OLDBOY=73
AGE_OF_OLDBOY=72
print(AGE_OF_OLDBOY)

五、用户与程序交互

linux环境要写:  
#!/usr/bin/env python
#coding:utf-8

实操

#在python3中的input:无论用输入何种类型,都会存成字符串类型
# name=input('please input your name: ')   #name='18',仍然被认为是字符串;
# print(id(name),type(name),name)

'''
在python2中
raw_input与python3的input是一样的
name=raw_input('please input your name: ')
print(id(name),type(name),name)
'''

#python2中input,用户必须输入值,输入的值是什么类型,就存成什么类型
name=input('please input your name: ')
print(id(name),type(name),name)

#'egon'才正确;18的type会被识别为int。

六、基本数据类型

字符串

1 在python中,加了引号的字符就是字符串类型,python并没有字符类型。
2 定义:name='egon' #name=str('egon') 
3 用于标识:描述性的内容,如姓名,性别,国籍,种族

列表

1 在[]内用逗号分隔,可以存放n个任意类型的值
2 定义:students=['egon','alex','wupeiqi',] #students=list(['egon','alex','wupeiqi',]) 
3 用于标识:存储多个值的情况,比如一个人有多个爱好

字典

1 在{}内用逗号分隔,可以存放多个key:value的值,value可以是任意类型
2 定义:info={'name':'egon','age':18,'sex':18} #info=dict({'name':'egon','age':18,'sex':18})
3 用于标识:存储多个值的情况,每个值都有唯一一个对应的key,可以更为方便高效地取值

布尔

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

实操

#数字
#int整型:年纪,身份证号,qq号,等级
# age=18 #age=int(18)

#float浮点型:身高,体重,薪资
# height=1.81
# height=float(1.81)
# print(type(height),height)


#字符串类型:把一对字符放到单引号或者双引号或者三引号中
#字符串:表示一些描述性状态,人的名字,人的性别
# name="egon" #name=str("egon")
# print(type(name))
#
# comment='''
# 老男孩的alex,买了一辆tesla,然而,sb才买tesla呢
# '''
#
# msg="i'm is ok"

#字符串拼接:
#1 只能字符串之间拼接
#2 字符串之间只能用+或*
# name='egon'
# msg='hello'
# age=18
# print(name+msg+str(age))
#
# print(name*10)


# hobbies='play read music movie'
# print(hobbies)
#列表:定义在[]内,用逗号分隔开的多个元素,每个元素可以是任意类型
#表示:存取放多个值,比如存放人的爱好,人的信息,
# hobbies=['play','read','music','movie'] #hobbies=list(['play','read','music','movie'])
# print(type(hobbies))
# print(hobbies[3])
# print(hobbies[0])
# print(hobbies[-1])

# print(hobbies[10])

# l=[1,1.3,'egon',['a','b']]
# print(l[3][1])


#      id             name   sex    hobbies
# info=[12312312321312,'egon','male',['read','music',]]
# print(info[3][1])
# print(info[1])


#字典:定义的{}内,用key=value形式表示一个元素,用逗号分隔开
# info={'name':'egon','id':12312312321312,'sex':'male','hobbies':['read','music',]}
# print(info['name'])
# print(info['hobbies'][1])

"""
info={
        'name':'guoxq',
        'hobbies':['play','music'],
        'company_info':{
            'name':'oldboy',
            'type':'edu',
            '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])
"""

#布尔类型:
# print(type(True))
# # print(type('true'))
AGE=73
age=18
print(age > AGE)
print(age < AGE)

七、格式化输出
程序中经常会有这样场景:要求用户输入信息,然后打印成固定的格式
比如要求用户输入用户名和年龄,然后打印如下格式:
My name is xxx,my age is xxx.
这就用到了占位符,如:%s、%d

占位符

#%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,所以会报错

实操

#My name is xxx,my age is xxx

# name=input("user_name>>: ")
# age=input("user_age>>: ")

# print('My name is ,my age is',name,age)
# print('My name is %s,my age is %s' %(name,age))
# print('My name is %s,my age is %s' %('egon','18'))
# print('My name is %s,my age is %s' %('egon',18))
# print('My name is %s,my age is %d' %('egon',18))
print('My name is %s,my age is %d' %('egon','18'))

练习题

练习:用户输入姓名、年龄、工作、爱好 ,然后打印成以下格式
------------ info of Egon -----------
Name : Egon
Age : 22
Sex : male
Job : Teacher 
------------- end -----------------

name=input('Name>>:')
age=input('Age>>:')
sex=input('Sex>>:')
job=input('Job>>:')
print('------------ info of Egon -----------')
print('Name  : %s' %name)
print('Age   : %s' %age)
print('Sex   : %s' %sex)
print('Job   : %s' %job)
print('------------- end -----------------')

八、基本运算符

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

算术运算

比较运算

赋值运算

逻辑运算

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

身份运算

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

实操

a=100
b=31
# res=a+b

# print(a+b)
# print(a-b)
# print(a*b)
# print(a/b) #真正的除法,有整数,有小数
# print(a//b) #地板除,只取整数部分
# a=10
# b=3
# print(a%b) #地板除,只取整数部分
# print(3**2) #地板除,只取整数部分


#比较运算
age=73

# print(age > 30)
# print(age < 30)
# print(age != 30)
# print(age != 73)
# print(age == 73)


#赋值运算
# height=180
#
# height+=1 #height=height+1  变量名和运算符号移到=左边
#
# print(height)


#逻辑
# age=11
# name='egon'
# print(age > 10 and name == 'ego1111111n')
# print(age > 10 or name == 'ego1111111n')

# age=11
# print(age > 3)
# print(not age > 10)

九、流程控制之if...else
      我们编程的目的是为了控制计算机能够像人脑一样工作,那么人脑能做什么,就需要程序中有相应的机制去模拟。人脑无非是数学运算和逻辑运算,对于数学运算在上一节我们已经说过了。对于逻辑运算,即人根据外部条件的变化而做出不同的反映。

实操

# age=input('>>: ')
# age=int(age)
# if age > 30:
#     print('叫阿姨')

#
# age=input('>>: ')
# age=int(age)
# if age > 30:
#     print('叫阿姨')
# else:
#     print('叫妹妹')
#

# sex=input('sex>>: ')
# age=int(input('age>>: '))
# is_pretty=True
# if sex == 'female' and age > 18 and age < 30 and is_pretty == True:
#     print('表白中。。。')
# else:
#     print('叫阿姨')

# x='True'
# print(bool(x))   只要不是x=''结果都为True
#
# sex = input('sex>>: ')
# age = int(input('age>>: '))
# is_pretty = bool(input('is_pretty>>: '))
#
# if sex == 'female' and age > 18 and age < 30 and is_pretty == True:
#     print('表白中。。。')
# else:
#     print('叫阿姨')


#if嵌套
# age = int(input('age>>: '))
# is_pretty = bool(input('is_pretty>>: '))
#
# success=False
# if sex == 'female' and age > 18 and age < 30 and is_pretty == True:
#     if success:
#         print('在一起')
#     else:
#         print('什么尼玛的爱情,去qnmlgb的爱情啊。。。')
# else:
#     print('叫阿姨')


#if多分支
score=int(input("your score>>:"))

if score >= 90:
    print('优秀')
elif score >= 80:
    print('良好')
elif score >= 70:
    print('及格')
else:
    print('太差了')

练习题

1、用户登录验证

name='guoxq'
passowrd=123456
name=input('please input your name >>:')
passowrd=int(input('password >>:'))

if name == 'guoxq' and passowrd == 123456:
    print('登陆成功')
else:
    print('登录失败')

2、根据用户输入内容输出其权限

msg=input('请输入你的验证码:')
if msg == 'glod':
    print('你有管理权限')
elif msg == 'silver':
    print('你有副管理员权限')
elif msg == 'bronze':
    print('你有用户权限')
else:
    print('你不具备任何条件')

3、工作日与周末

Today=input('Today is ')
if Today == 'Monday' or Today == 'Tuesday' or Today == 'Wednesday' or Today == 'Thursday' or Today == 'Friday':
    print('上班')
elif Today == 'Saturday' or Today == 'Sunday':
    print('出去浪')
else:
    print('不存在的节日')

或者:
today=input('>>: ')
if today in ['Saturday','Sunday']:
    print('出去浪')
elif today in ['Monday','Tuesday','Wednesday','Thursday','Friday']:
    print('上班')
else:
    print('''必须输入其中一种:
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday
    Sunday
    ''')

十、流程控制之while
那么如何做到不用写重复代码又能让程序重复一段代码多次呢? 循环语句就派上用场啦
条件循环:while,语法如下
while 条件:
  # 循环体

  # 如果条件为真,那么循环体则执行,执行完毕后再次循环,重新判断条件。。。
  # 如果条件为假,那么循环体不执行,循环终止
PS.
break:跳出本层循环;
continue:跳出本次,直接进入下一次循环。直到代码的中间位置,后面的代码不再运行了。

break&continue

#break用于退出本层循环
while True:
    print ("123")
    break
    print ("456")

#continue用于退出本次循环,继续下一次循环
while True:
    print ("123")
    continue
    print ("456")

while+else

#与其它语言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 ------

嵌套tag的玩法

  tag=True 

  while tag:

    ......

    while tag:

      ........

      while tag:

        tag=False

实操

# AGE_OF_OLDBOY=73
#
# guess=int(input('请输入老男孩的年龄: '))
# if guess > AGE_OF_OLDBOY:
#     print('太大了')
# elif guess < AGE_OF_OLDBOY:
#     print('太小了')
# else:
#     print('蒙对了')
#
#猜测三次呢?不能把上面的程序重复写三次吧?!
#
#while:条件循环
# while 条件:
#     循环体


# count=0
# while count < 3:
#     print('loop',count)
#     count+=1

# count=0
# while True:
#     if count < 101:
#         print(count)
#     count+=1

#break:跳出本层循环
# count=0
# while True:
#     if count > 100:
#         break
#     print(count)
#     count+=1

#continue:跳出本次循环
# count=0
# while True:
#     if count > 10:
#         break
#     print(count)
#     count+=1

# count=0
# while count <= 10:
#     print(count)
#     count+=1

# count=0
# while count <= 10:
#     if count == 7:
#         count+=1
#         continue
#     print(count)
#     count+=1

# count=0
# while count < 11:
#     print(count)
#     count+=1
# else:
#     print('while正常循环完毕,没有被break打断,才会执行这里的代码')

#while+else:
# count=0
# while count <= 10:
#     if count == 3:
#         break
#     print(count)
#     count+=1
# else:
#     print('while正常结束了,没有被break打断,才会执行这里的代码')



#注意一:
# count=0
# while count <= 5:
#     print(count)
#     count+=1
#     # continue #加到这里没意义


#注意二:

# name='egon'
# password='alex3714'
# count=0
# while count < 3:
#     u=input('u>>:')
#     p=input('p>>:')
#
#     if u == name and p == password:
#         print('login sucessful')
#         break
#     else:
#         print('user nor password err')
#         count+=1

# name='guoxq'
# password='123'
# count=0
# while count < 3:
#     user=input('请输入用户名: ')
#     passw=input('请输入密码: ')
#     if user == name and passw == password:
#         print('login successful')
#         break
#     else:
#      print('login fail')
#      count+=1

# name='guoxq'
# password='123'
# count=0
# while True:
#     if  count > 2:
#         break
#     user=input('请输入用户名: ')
#     passw=input('请输入密码: ')
#     if user == name and passw == password:
#         print('login successful')
#         break
#     else:
#      print('login fail')
#      count+=1

# name='egon'
# password='alex3714'
# count=0
# while True:
#     if count == 3:
#         break
#     u = input('u>>:')
#     p = input('p>>:')
#
#     if u == name and p == password:
#         print('login sucessful')
#         while True:
#             cmd = input('>>: ')
#             if cmd == 'quit':
#                 break
#             print('run %s' % cmd)
#         break
#     else:
#         print('user nor password err')
#         count += 1

# while True:
#     print ("123")
#     break
#     print ("456")
#
# while True:
#     print ("123")
#     continue
#     print ("123")

实现用户输入用户名和密码,当用户名为 seven 或 alex 且 密码为 123 时,显示登陆成功,否则登陆失败,失败时允许重复输入三次

name='egon'
password='alex3714'
count=0
tag=True
while tag:
    if count == 3:
        break
    u = input('u>>:')
    p = input('p>>:')

    if u == name and p == password:
        print('login sucessful')
        while tag:
            cmd = input('>>: ')
            if cmd == 'quit':
                tag=False
                continue
            print('run %s' % cmd)

    else:
        print('user nor password err')
        count += 1

练习题(上):

1、打印0到10,奇数or偶数

#打印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

2、使用while循环输出1 2 3 4 5 6 8 9 10

# count=0
# while True:
#     count += 1
#     if count < 11:
#         if count == 7:
#             continue
#         print(count)

# count=0
# while count < 10:
#     count+=1
#     if  not count ==7:
#         print(count)

# count=0
# while count < 10:
#     count+=1
#     if  count !=7:
#         print(count)

# count=1
# while count <=10:
#     if count == 7:
#         count+=1
#         continue
#     print(count)
#     count+=1

3、求1-100的所有数之和

# res=0
# count=1
# while count <= 100:
#     res+=count
#     print(res)
#     count+=1

4、求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)

5、求2-3+4-5+6...+100的所有数的和

# res=0
# count=2
# while count <= 100:
#     if count % 2 == 0:
#         res+=count
#     else:
#         res-=count
#     count+=1
#     print(res)

6、用户登陆(三次机会重试)

# name='guoxq'
# password='123'
# count=0
# while count < 3:
#     usr = input('请输入用户名: ')
#     passw = input('请输入密码: ')
#     if usr == name and passw == password:
#         print('login successful')
#         break
#     else:
#         print('login fail')
#         count+=1

7、猜年龄游戏

# 要求:
#     允许用户最多尝试3次,3次都没猜对的话,就直接退出,如果猜对了,打印恭喜信息并退出
# AGE_OF_OLDBOY = 73
# count = 0
# while count < 3:
#     age=int(input('>>:'))
#     count+=1
#     if  age > 73:
#         print('bigger')
#     elif age < 73:
#         print('smaller')
#     else:
#         print('congratulation')

# age_of_oldboy=73
# count=0
# while count < 3:
#     guess=int(input('>>: '))
#     if guess == age_of_oldboy:
#         print('you got it')
#         break
#     count+=1

8、猜年龄游戏升级版

# 要求:
#     允许用户最多尝试3次
#     每尝试3次后,如果还没猜对,就问用户是否还想继续玩,如果回答Y或y, 就继续让其猜3次,以此往复,如果回答N或n,就退出程序
#     如何猜对了,就直接退出

# AGE_OF_OLDBOY = 73
# count=0
# while True:
#     if count == 3:
#         choice = input('继续(Y/N?)>>: ')
#         if choice == 'Y' or choice == 'y':
#             count = 0
#         else:
#             break
#     age = int(input('>>: '))
#     if age == AGE_OF_OLDBOY:
#         print('you got it')
#         break
#     count+=1

# for i in range(1,10):
#     for j in range(1,i+1):
#         print('%s*%s=%s' %(i,j,i*j),end=' ')
#     print()

 

  本小节完结😝

posted @ 2017-09-07 15:44  大雄猫  阅读(275)  评论(0编辑  收藏  举报