Python菜鸟之路基础篇(一)
学习任何一门语言,我想大家写的以一句就是hello world吧,下面我们来看看Python的hello world 创建一个hello.py的文件:Hello World
print ("Hello World")然后执行命令:python hello.py ,输出
crh:Python crh$ python3 hello.py Hello WorldPython执行过程为: 把代码读到内存 ---->词法语法分析 ---->放到编译器 ----> 生成字节码 ---->执行字节码 ---->生成机器码---->CPU执行,图示如下: [attach]1303[/attach] 指定解释器 在上面情况,我们指定Python3 来执行hello.py 如果想要类似于执行shell脚本一样执行python脚本,例: ./hello.py ,那么就需要在 hello.py 文件的头部指定解释器,如下:
crh:Python crh$ cat hello.py #!/usr/bin/env python3 print ("Hello World")像上面这样,然后给hello.py文件添加执行权限(chmod +x hello.py)就可以像执行shell脚本一样./hello.py 即可。 ***像上面是利用Linux env命令通过环境变量去找到你想用的Python命令,如果你指定用某个Python版本的话一可以写绝对路径,比如:/usr/bin/python or /usr/local/bin/python3 在交互器中执行 除了把程序写在文件里,还可以直接调用python自带的交互器运行代码,进行调试和测试
crh:Python crh$ python3 Python 3.5.1 (default, Dec 26 2015, 18:08:53) [GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin Type "help", "copyright", "credits" or "license" for more information. [quote]>> print ("Hello World") Hello World >>>
在一个计算机程序中引用变量是用来存储信息和操作的。他们还提供一种标签数据与一个描述性的名称,所以我们的程序可以被读者和我们自己更清楚地理解。它有助于认为变量保存信息的容器。他们的唯一目的是标签和数据存储在内存中。这些数据可以通过使用程序引用。 声明变量变量
#_[i]_coding:utf-8_[/i]_ name = "Lucky chen"如上面所示声明了一个变量name,他的值是"Lucky chen" 我们再来看一组连续赋值的过程:
>>> name = "crh" >>> name1 = name >>> print (name,name1) crh crh >>> name = "Lucky" >>> print (name1,name) crh Lucky如上所示,为什么name1 = name 当后续把name变量的值改变了,为什么name1的值没有随着改变呢,如下看看你就明白了:
>>> name = "crh" #首先在内存中打开一块内存空间存储name变量值 >>> id(name) #查看变量name的内存地址 4412833952 >>> name1 = name #把我们把name赋值给name1变量 >>> id(name1) #然后查看name1变量的内存地址 (跟name变量的内存地址一样) 4412833952 >>> name = "lucky" #重新打开一个内存空间存储name的变量值 >>> id(name) #查看新的name变量值的内存地址 4412834176 >>> id(name1) #查看name1变量内存地址 4412833952如上所示,我们可以看出,nama1其实就是借助name变量做一个变量的赋值,通过name变量得到值所在内存中的内存地址后,从而变成了一个正常的赋值过程。而不换随着name变量的内存空间地址的改变而改变。示意图如下: [attach]1304[/attach]
用户输入就是程序和用户的交互,程序等待用户输入一个参数然后重新继续进行:交互输入
#!/usr/bin/env python3 #Authe: Lucky.chen #_[i]_coding:utf-8_[/i]_ name = input("Please enter your name:") print ("[size=16]#",name,"[/size]#")[attach]1305[/attach] 如上图所示,默认Python3下的input函数用户输入的所有东西都当做字符串处理,所以你输入的年龄希望它是整数类型,还需要int()一下。 在python2中input这个函数,用户默认输入的是什么格式的参数,Python就当作是什么类型处理,Python2中获取用户输入参数的函数还有一个叫做raw_input(),这个函数默认也是字符串处理。可以看出Python3为了简洁统一,在Python3中已经不存在了raw_input()函数,input()一个函数完全可以做到所有使用。 平常如果我们用针对密码、密码串之类的交互的话,一般用户的输入时隐藏或者*****的,输入密码时,在Python下如果你需要你输入的东西不可见,可以利用getpass 模块中的 getpass方法来处理:
#!/usr/bin/env python3 #Authe: Lucky.chen #_[i]_coding:utf-8_[/i]_[/quote] #导入getpass模块 import getpass # 将用户输入的内容赋值给 name 变量 pwd = getpass.getpass("请输入密码:") # 打印输入的内容 print("Password is [size=16]",pwd,"***print end")[/size] #比如我输入110119,执行过程和结果如下: 请输入密码: Password is [size=16] 110119 ***print end[/size]
注释: 单行注释:# 开头就好,跟shell一样 多行注释:成对的三个单引号 ''' 注释内容 ''' 或者 成对的三个双引号 """ 注释内容 """注释和拼接
>>> ''' My name is lucky '''
' My name is lucky '
[quote]>> """ My age is 23 """
' My age is 23 '
>>> # Good Idea
...
>>> msg = """ My info is :
... age: 23
... name: lucky
... job: IT"""
>>> print (msg)
My info is :
age: 23
name: lucky
job: IT
>>>
拼接:
1、难受的 "+" >>> name = "lucky" >>> age = 23 >>> job = "IT" >>> >>> msg = """ Info of """ +name + """ ... Name:""" +name + """ ... Age:""" +age + """ ... Job:""" +job Traceback (most recent call last): File "如上所示 "+"拼接只能是字符串,如果是整型、或者是浮点都会报错。 2、百分号(%) Code:", line 4, in TypeError: Can't convert 'int' object to str implicitly >>> >>> name = "lucky" >>> age = "23" >>> job = "IT" >>> msg = """ Info of """ +name + """ ... Name:""" +name + """ ... Age:""" +age + """ ... Job:""" +job >>> print (msg) Info of lucky Name:lucky Age:23 Job:IT >>>
#!/usr/bin/env python3.5
#auther: lucky.chen[/quote]
name = input("Please input your name: ")
age = input("Please input your age:")
job = input("Please input your job:")
salary = input("Please input your salary:")
msg = """------------ info of %s
Name: %s
Age: %s
Job: %s
Salary: %s
""" % (name,name,age,job,salary)
print (msg)
Result:Please input your name: lucky Please input your age:23 Please input your job:IT Please input your salary:40000 ------------ info of lucky Name: lucky Age: 23 Job: IT Salary: 400003、使用format函数 情况一:使用变量格式化 Code:
#!/usr/bin/env python3.5 #auther: lucky.chen name = input("Please input your name: ") age = input("Please input your age:") job = input("Please input your job:") salary = input("Please input your salary:") msg = """------------ info of {_Name} Name: {_Name} Age: {_Age} Job: {_Job} Salary: {_Salary} """.format(_Name=name,_Age=age,_Job=job,_Salary=salary) print (msg)Result:
Please input your name: crh Please input your age:23 Please input your job:IT Please input your salary:45000 ------------ info of crh Name: crh Age: 23 Job: IT Salary: 45000情况二:使用下脚标
#!/usr/bin/env python3.5 #auther: lucky.chen name = input('please input your name:') age = input('please input your age:') job = input('please input your job:') salary = input('please input your salary:') msg = ''' ------------info of {0}----------- Name: {0} Age: {1} Job: {2} Salary: {3} '''.format(name,age,job,salary) print (msg)Result:
please input your name:chenronghua please input your age:23 please input your job:OPS please input your salary:50000 ------------info of chenronghua----------- Name: chenronghua Age: 23 Job: OPS Salary: 50000format是比较好的方式,有时候我们必须使用format方法,所以掌握了format就好。
一、流程控制这里先介绍 if ...... else and if ...... elif ..... else 1、if ..... else(用户认证登录) Code:流程控制
#!/usr/bin/env python3.5 #auther: lucky.chen name = input("Please input your name:") passwd = input("Please input your password:") if name == "crh" and passwd == "123456": print (" \033[32mWelcome login OPS Management platform\033[0m ") else: print ("\033[31mYour UserName or Password Error\033[0m")Result:
Please input your name:crh Please input your password:34 Your UserName or Password Error2、if ..... elfi ...... else Code:
#!/usr/bin/env python3.5 #auther: lucky.chen age = int(input("Pleast input your age:")) if age < 18: print (" \033[32m You're too young \033[0m ") elif age > 18 and age < 30: print ("\033[31m You still have many chance comes at a time when youth waiting for you \033[0m") else: print ("\033[33m Before you is too old to do \033[0m")Result:
Pleast input your age:23 You still have many chance comes at a time when youth waiting for you二、for 循环遍历
#!/usr/bin/env python3.5 #auther: lucky.chen for num in range(5): print ("loop is:",num) # Result is: loop is: 0 loop is: 1 loop is: 2 loop is: 3 loop is: 4range函数也可以设置步长值,比如我们要打印出1-10中的所有偶数(默认步长为1)
#!/usr/bin/env python3.5 #auther: lucky.chen for num in range(0,11,2): print ("loop is:",num) # Result loop is: 0 loop is: 2 loop is: 4 loop is: 6 loop is: 8 loop is: 10除掉range函数我们还可以使用xrange函数,为什么要这里要介绍xrange呢,因为xrange相对于range来说性能比较优越,因为xrange不需要一上来就开辟一块很大的内存空间,具体可以参考我之前发布的文章:Python中xrange和range的异同 ,但是好像Python3.*中没有了xrange函数。 for...else...循环介绍,不止if中有else,在for循环中也是可以用else的,在for循环中的else就是当前面的循环正常执行完后,没有跳出,后面的else代码将被执行。
crh:Python crh$ cat for.py #!/usr/bin/env python3 #Auther: lucky.chen for num in range(4): print ("Loop is:",num) else: print ("normal") crh:Python crh$ ./for.py Loop is: 0 Loop is: 1 Loop is: 2 Loop is: 3 normal crh:Python crh$
crh:Python crh$ cat for.py #!/usr/bin/env python3 #Auther: lucky.chen for num in range(4): if num > 2: break print ("Loop is:",num) else: print ("normal") crh:Python crh$ ./for.py Loop is: 0 Loop is: 1 Loop is: 2 crh:Python crh$三、while循环遍历 while 循环它的原理是:当条件为真的时候运行,当条件为假的时候停止!没有一个规定次数,不设置条件就永远循环下去。
#!/usr/bin/env python3.5 #auther: lucky.chen import time count = 0 while True: count +=1 print ("loop",count) time.sleep(3) #这个循环3秒钟自+1后,无线循环只要这个条件为”真“,就无限循环下去
#!/usr/bin/env python3.5 #auther: lucky.chen import time num = 0 while num < 3: num +=1 print ("Num is:",num) time.sleep(3) #这个循环每3秒循环一次,当条件num < 3的时候为真(自己设置的条件),当num不小于3的时候为假(false)循环停止.While ...... else
#!/usr/bin/env python3.5 #auther: lucky.chen while 1: if num == 4: print ("I think stop") break print (num) num += 1 else: print ("stop")四、break和continue介绍
break在循环中的作用是跳出所在的循环体,不在进行循环,而continue是跳出所在循环体中的本次循环,后续没有完的循环继续。Code:
#!/usr/bin/env python3.5 #auther: lucky.chen num = 1 print ("test break for loop start") for n in range(5): if n == num: break print (n) print ("\n") print ("test continue for loop start") for n in range(5): if n == num: continue print (n)Result:
test break for loop start 0 test continue for loop start 0 2 3 4猜数字游戏:
#!/usr/bin/env python3.5 #auther: lucky.chen #load module (random) import random TryNum = 0 RandNum = random.randrange(10) print (RandNum) while TryNum < 3: GuessNum = int(input("请猜测从0到9之间的一个中奖数字:")) if GuessNum >= 10: print ("你输入的数字不在中奖号码范围内,请重新输入!") continue if GuessNum == RandNum: print ("恭喜你猜对了,你将获得小米电视一台!") break elif GuessNum > RandNum: print ("你猜的数字太大了可以再往小了猜") else: print ("你猜的数字太小了可以往大了猜") TryNum += 1 else: print ("不好意思你三次机会用完了,Game over!") #先随机到0-9中筛选出以为数字,然后用户三次机会猜测一个中奖号码,如果用户输入的数字不在范围内,则让用户再次输入.Result:
4 请猜测从0到9之间的一个中奖数字:11 你输入的数字不在中奖号码范围内,请重新输入! 请猜测从0到9之间的一个中奖数字:11 你输入的数字不在中奖号码范围内,请重新输入! 请猜测从0到9之间的一个中奖数字:11 你输入的数字不在中奖号码范围内,请重新输入! 请猜测从0到9之间的一个中奖数字:11 你输入的数字不在中奖号码范围内,请重新输入! 请猜测从0到9之间的一个中奖数字:2 你猜的数字太小了可以往大了猜 请猜测从0到9之间的一个中奖数字:5 你猜的数字太大了可以再往小了猜 请猜测从0到9之间的一个中奖数字:4 恭喜你猜对了,你将获得小米电视一台!五、嵌套循环 While for:
#!/usr/bin/env python3.5 #auther: lucky.chen count = 1 while count < 4: print("count var lt 4") print ("#########################[size=16]#")[/size] for n in range(3): print ("for num is:",n) print ("****************************") count += 1Result:
count var lt 4 #########################[size=16]#[/size] for num is: 0 for num is: 1 for num is: 2 **************************** count var lt 4 #########################[size=16]#[/size] for num is: 0 for num is: 1 for num is: 2 **************************** count var lt 4 #########################[size=16]#[/size] for num is: 0 for num is: 1 for num is: 2 ****************************死循环:
#!/usr/bin/env python3.5 #auther: lucky.chen import time while True: print ("One Loop") time.sleep(1) while True: print ("Two Loop") time.sleep(1) while True: print ("Three Loop") time.sleep(1) #这是一个死循环,第一次执行这段code的时候,依次往下执行,单到了第三个while的时候,就一直是true,所以一直在执行第三个while下的code. #结果如下: One Loop Two Loop Three Loop Three Loop Three Loop Three Loop .......... ..........如上我们给出了一个死循环的例子,但是如果如果我们需要跳出循环应该怎么做,如果用break可以做到吗? 1、第一个while后加break分析 [attach]1306[/attach] 2、第二个while后加break分析 [attach]1307[/attach] 3、第三个while后加break分析 [attach]1308[/attach] 既然存在这种死循环的那我们有什么办法可以跳出呢?那就是打标志,标志位 Code:
#!/usr/bin/env python3.5 #auther: lucky.chen count = 0 while True: print ("我是第一层") jump_1_flag = False while True: print ("我是第二层") jump_2_flag = False while True: count += 1 print ("我是第三层") if count > 3: jump_2_flag = True break if jump_2_flag: print ("第三层跳到我这里来了,我也要跳到第一层") jump_1_flag = True break if jump_1_flag: print ("第二层和第三层跳到第一层了,我也要跳") break分析和结果: [attach]1309[/attach]