day1介绍,基本语法,流程控制

本节内容

一、 Python介绍

python的创始人为吉多·范罗苏姆(Guido van Rossum)。1989年的圣诞节期间,吉多·范罗苏姆为了在阿姆斯特丹打发时间,决心开发一个新的脚本解释程序,作为ABC语言的一种继承。  

最新的TIOBE排行榜,Python赶超PHP占据第五, Python崇尚优美、清晰、简单,是一个优秀并广泛使用的语言。

二、发展史

  • 1989年,为了打发圣诞节假期,Guido开始写Python语言的编译器。Python这个名字,来自Guido所挚爱的电视剧Monty Python’s Flying Circus。他希望这个新的叫做Python的语言,能符合他的理想:创造一种C和shell之间,功能全面,易学易用,可拓展的语言。
  • 1991年,第一个Python编译器诞生。它是用C语言实现的,并能够调用C语言的库文件。从一出生,Python已经具有了:类,函数,异常处理,包含表和词典在内的核心数据类型,以及模块为基础的拓展系统。
  • Granddaddy of Python web frameworks, Zope 1 was released in 1999
  • Python 1.0 - January 1994 增加了 lambda, map, filter and reduce.
  • Python 2.0 - October 16, 2000,加入了内存回收机制,构成了现在Python语言框架的基础
  • Python 2.4 - November 30, 2004, 同年目前最流行的WEB框架Django 诞生
  • Python 2.5 - September 19, 2006
  • Python 2.6 - October 1, 2008
  • Python 2.7 - July 3, 2010
  • In November 2014, it was announced that Python 2.7 would be supported until 2020, and reaffirmed that there would be no 2.8 release as users were expected to move to Python 3.4+ as soon as possible
  • Python 3.0 - December 3, 2008
  • Python 3.1 - June 27, 2009
  • Python 3.2 - February 20, 2011
  • Python 3.3 - September 29, 2012
  • Python 3.4 - March 16, 2014
  • Python 3.5 - September 13, 2015

三、Python 2 or 3?

In summary : Python 2.x is legacy, Python 3.x is the present and future of the language

Python 3.0 was released in 2008. The final 2.x version 2.7 release came out in mid-2010, with a statement of

extended support for this end-of-life release. The 2.x branch will see no new major releases after that. 3.x is

under active development and has already seen over five years of stable releases, including version 3.3 in 2012,

3.4 in 2014, and 3.5 in 2015. This means that all recent standard library improvements, for example, are only

available by default in Python 3.x.

Guido van Rossum (the original creator of the Python language) decided to clean up Python 2.x properly, with less regard for backwards compatibility than is the case for new releases in the 2.x range. The most drastic improvement is the better Unicode support (with all text strings being Unicode by default) as well as saner bytes/Unicode separation.

Besides, several aspects of the core language (such as print and exec being statements, integers using floor division) have been adjusted to be easier for newcomers to learn and to be more consistent with the rest of the language, and old cruft has been removed (for example, all classes are now new-style, "range()" returns a memory efficient iterable, not a list as in 2.x). 

py2与3的详细区别

PRINT IS A FUNCTION

The statement has been replaced with a print() function, with keyword arguments to replace most of the special syntax of the old statement (PEP 3105). Examples:

  1 Old: print "The answer is", 2*2 New: print("The answer is", 2*2)
  2 Old: print x, # Trailing comma suppresses newline New: print(x, end=" ") # Appends a space instead of a newline
  3 Old: print # Prints a newline
  4 New: print() # You must call the function!
  5 Old: print >>sys.stderr, "fatal error" New: print("fatal error", file=sys.stderr)
  6 Old: print (x, y) # prints repr((x, y))
  7 New: print((x, y)) # Not the same as print(x, y)!
View Code

You can also customize the separator between items, e.g.:

  1 print("There are <", 2**32, "> possibilities!", sep="")
View Code

 

ALL IS UNICODE NOW

从此不再为讨厌的字符编码而烦恼

还可以这样玩: (A,*REST,B)=RANGE(5)

  1 <strong>>>> a,*rest,b = range(5)
  2 >>> a,rest,b
  3 (0, [1, 2, 3], 4)
  4 </strong>

某些库改名了

Old Name

New Name

_winreg

winreg

ConfigParser

configparser

copy_reg

copyreg

Queue

queue

SocketServer

socketserver

markupbase

_markupbase

repr

reprlib

test.test_support

test.support

还有谁不支持PYTHON3?

One popular module that don't yet support Python 3 is Twisted (for networking and other applications). Most

actively maintained libraries have people working on 3.x support. For some libraries, it's more of a priority than

others: Twisted, for example, is mostly focused on production servers, where supporting older versions of

Python is important, let alone supporting a new version that includes major changes to the language. (Twisted is

a prime example of a major package where porting to 3.x is far from trivial 

 

四、安装

windows
  1 1、下载安装包
  2     https://www.python.org/downloads/
  3 2、安装
  4     默认安装路径:C:\python27
  5 3、配置环境变量
  6     【右键计算机】--》【属性】--》【高级系统设置】--》【高级】--》【环境变量】--》【在第二个内容框中找到 变量名为Path 的一行,双击】 --> 【Python安装目录追加到变值值中,用 ; 分割】
  7     如:原来的值;C:\python27,切记前面有分号
python3.x默认安装路径改了,其他方法一样

linux、Mac

  1 无需安装,原装Python环境
  2 
  3 ps:如果自带2.6,请更新至2.7
  4 CentOS6默认是2.6,源码安装即可,添加个环境变量
  5 Ubuntu默认既是2.7了

Hello World程序

python3.x:命令行直接敲

  1 >>> print("Hello World")
  2 Hello World

各个语言的Hello World:

  1 1 #include <iostream>
  2 2 int main(void)
  3 3 {
  4 4 std::cout<<"Hello world";
  5 5 }
C++
1 #include <stdio.h>
2 int main(void)
3 {
4 printf("\nhello world!");
5 return 0;
6 }
C
1 public class HelloWorld{
2   // 程序的入口
3   public static void main(String args[]){
4     // 向控制台输出信息
5     System.out.println("Hello World!");
6   }
7 }
复制代码
JAVA
1 <?php
2             echo "hello world!";
3 ?>
PHP
1 puts "Hello world."
RUBY
1 package main
2
3 import "fmt"
4
5 func main(){
6
7     fmt.Printf("Hello World!\n God Bless You!");
8
9 }
GO

六、变量/字符编码

1.变量

Variables are used to store information to be referenced and manipulated in a computer program. They also provide a way of labeling data with a descriptive name, so our programs can be understood more clearly by the reader and ourselves. It is helpful to think of variables as containers that hold information. Their sole purpose is to label and store data in memory. This data can then be used throughout your program.

声明变量

  1 #_*_coding:utf-8_*_
  2 
  3 name = "Aige"

上述代码声明了一个变量,变量名为: name,变量name的值为:"Aige" 

变量定义的规则:

  • 变量名只能是 字母、数字或下划线的任意组合
  • 变量名的第一个字符不能是数字
  • 以下关键字不能声明为变量名
    ['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 name = "Aige"
  2 
  3 name2 = name
  4 print(name,name2)
  5 
  6 name = "Jack"
  7 
  8 print("What is the value of name2 now?")

2.字符编码

python解释器在加载 .py 文件中的代码时,会对内容进行编码(2.x默认ascill)

ASCII(American Standard Code for Information Interchange,美国标准信息交换代码)是基于拉丁字母的一套电脑编码系统,主要用于显示现代英语和其他西欧语言,其最多只能用 8 位来表示(一个字节),即:2**8 = 256-1,所以,ASCII码最多只能表示 255 个符号。

c2fdfc039245d688c56332adacc27d1ed21b2451

关于中文

为了处理汉字,程序员设计了用于简体中文的GB2312和用于繁体中文的big5。

GB2312(1980年)一共收录了7445个字符,包括6763个汉字和682个其它符号。汉字区的内码范围高字节从B0-F7,低字节从A1-FE,占用的码位是72*94=6768。其中有5个空位是D7FA-D7FE。

GB2312 支持的汉字太少。1995年的汉字扩展规范GBK1.0收录了21886个符号,它分为汉字区和图形符号区。汉字区包括21003个字符。2000年的 GB18030是取代GBK1.0的正式国家标准。该标准收录了27484个汉字,同时还收录了藏文、蒙文、维吾尔文等主要的少数民族文字。现在的PC平台必须支持GB18030,对嵌入式产品暂不作要求。所以手机、MP3一般只支持GB2312。

从ASCII、GB2312、GBK 到GB18030,这些编码方法是向下兼容的,即同一个字符在这些方案中总是有相同的编码,后面的标准支持更多的字符。在这些编码中,英文和中文可以统一地处理。区分中文编码的方法是高字节的最高位不为0。按照程序员的称呼,GB2312、GBK到GB18030都属于双字节字符集 (DBCS)。

有的中文Windows的缺省内码还是GBK,可以通过GB18030升级包升级到GB18030。不过GB18030相对GBK增加的字符,普通人是很难用到的,通常我们还是用GBK指代中文Windows内码。

显然ASCII码无法将世界上的各种文字和符号全部表示,所以,就需要新出一种可以代表所有字符和符号的编码,即:Unicode

Unicode(统一码、万国码、单一码)是一种在计算机上使用的字符编码。Unicode 是为了解决传统的字符编码方案的局限而产生的,它为每种语言中的每个字符设定了统一并且唯一的二进制编码,规定虽有的字符和符号最少由 16 位来表示(2个字节),即:2 **16 = 65536,
注:此处说的的是最少2个字节,可能更多

UTF-8,是对Unicode编码的压缩和优化,他不再使用最少使用2个字节,而是将所有的字符和符号进行分类:ascii码中的内容用1个字节保存、欧洲的字符用2个字节保存,东亚的字符用3个字节保存...

所以,python解释器在加载 .py 文件中的代码时,会对内容进行编码(2.x默认ascill),如果是如下代码的话:

报错:ascii码无法表示中文

  1 #!/usr/bin/env python
  2 
  3 print "你好,世界"

改正:应该显示的告诉python解释器,用什么编码来执行源代码,即:

  1 #!/usr/bin/env python
  2 # -*- coding: utf-8 -*-
  3 
  4 print "你好,世界"

python3.x默认支持utf-8.所以可以不用写# -*- coding: utf-8 -*-

注释

  当行注视:# 被注释内容

  多行注释:""" 被注释内容 """   (单引号也行)

  1 #!/usr/bin/env python
  2 # _*_ coding:utf-8 _*_
  3 
  4 #这是单行注释
  5 
  6 '''
  7 这是多行注释
  8 这是多行注释
  9 '''
 10 """
 11 这也是多行注释
 12 这也是多行注释
 13 """
 14 
注释代码

 

七、用户输入

  1 #!/usr/bin/env python
  2 # _*_ coding:utf-8 _*_
  3 #name = raw_input("What is your name?") #only on python 2.x
  4 name = input("What is your name?")
  5 print("name is : ",name)
  6 
  7 
  8 运行后
  9 What is your name?Aige
 10 name is :  Aige注释代码
用户输入

输入密码时,如果想要不可见,需要利用getpass 模块中的 getpass方法,即:

  1 #!/usr/bin/env python
  2 # _*_ coding:utf-8 _*_
  3 
  4 import getpass  #pycharm 不好使 在linux测试
  5 username = input("username:")
  6 password = getpass.getpass("password:")
  7 print(username,password)
暗纹密码
  1 D:\学习python\pyn\自学\day1>python3 暗纹密码模块.py
  2 username:Aige
  3 password:
  4 Aige 123abc
执行结果

 

 

八、模块初识

Python的强大之处在于他有非常丰富和强大的标准库和第三方库,几乎你想实现的任何功能都有相应的Python库支持,以后的课程中会深入讲解常用到的各种库,现在,我们先来象征性的学2个简单的。

sys

  1 #!/usr/bin/env python
  2 # -*- coding: utf-8 -*-
  3 
  4 import sys
  5 print(sys.argv)
  6 
  7 
  8 #输出
  9 $ python test.py helo world
 10 ['test.py', 'helo', 'world']  #把执行脚本时传递的参数获取到了
sys模块

os

  1 #!/usr/bin/env python
  2 # -*- coding: utf-8 -*-
  3 
  4 import os
  5 
  6 os.system("df -h") #调用系统命令
os模块

完全结合一下 

  1 import os,sys
  2 
  3 os.system(''.join(sys.argv[1:])) #把用户的输入的参数当作一条命令交给os.system来执行
结合代码

 

自己写个模块

python tab补全模块

  1 import sys
  2 import readline
  3 import rlcompleter
  4 
  5 if sys.platform == 'darwin' and sys.version_info[0] == 2:
  6     readline.parse_and_bind("bind ^I rl_complete")
  7 else:
  8     readline.parse_and_bind("tab: complete")  # linux and python3 on mac
For Mac
  1 #!/usr/bin/env python 
  2 # python startup file 
  3 import sys
  4 import readline
  5 import rlcompleter
  6 import atexit
  7 import os
  8 # tab completion 
  9 readline.parse_and_bind('tab: complete')
 10 # history file 
 11 histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
 12 try:
 13     readline.read_history_file(histfile)
 14 except IOError:
 15     pass
 16 atexit.register(readline.write_history_file, histfile)
 17 del os, histfile, readline, rlcompleter
For Linux

写完保存后即可使用

  1 localhost:~ jieli$ python
  2 Python 2.7.10 (default, Oct 23 2015, 18:05:06)
  3 [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
  4 Type "help", "copyright", "credits" or "license" for more information.
  5 >>> import tab

你会发现,上面自己写的tab.py模块只能在当前目录下导入,如果想在系统的何何一个地方都使用怎么办呢? 此时你就要把这个tab.py放到python全局环境变量目录里啦,基本一般都放在一个叫 Python/2.7/site-packages 目录下,这个目录在不同的OS里放的位置不一样,用 print(sys.path) 可以查看python环境变量列表。

 

九、.pyc是个什么鬼?

1. Python是一门解释型语言?

我初学Python时,听到的关于Python的第一句话就是,Python是一门解释性语言,我就这样一直相信下去,直到发现了*.pyc文件的存在。如果是解释型语言,那么生成的*.pyc文件是什么呢?c应该是compiled的缩写才对啊!

为了防止其他学习Python的人也被这句话误解,那么我们就在文中来澄清下这个问题,并且把一些基础概念给理清。

2. 解释型语言和编译型语言

计算机是不能够识别高级语言的,所以当我们运行一个高级语言程序的时候,就需要一个“翻译机”来从事把高级语言转变成计算机能读懂的机器语言的过程。这个过程分成两类,第一种是编译,第二种是解释。

编译型语言在程序执行之前,先会通过编译器对程序执行一个编译的过程,把程序转变成机器语言。运行时就不需要翻译,而直接执行就可以了。最典型的例子就是C语言。

解释型语言就没有这个编译的过程,而是在程序运行的时候,通过解释器对程序逐行作出解释,然后直接运行,最典型的例子是Ruby。

通过以上的例子,我们可以来总结一下解释型语言和编译型语言的优缺点,因为编译型语言在程序运行之前就已经对程序做出了“翻译”,所以在运行时就少掉了“翻译”的过程,所以效率比较高。但是我们也不能一概而论,一些解释型语言也可以通过解释器的优化来在对程序做出翻译时对整个程序做出优化,从而在效率上超过编译型语言。

此外,随着Java等基于虚拟机的语言的兴起,我们又不能把语言纯粹地分成解释型和编译型这两种。

用Java来举例,Java首先是通过编译器编译成字节码文件,然后在运行时通过解释器给解释成机器文件。所以我们说Java是一种先编译后解释的语言。

3. Python到底是什么

其实Python和Java/C#一样,也是一门基于虚拟机的语言,我们先来从表面上简单地了解一下Python程序的运行过程吧。

当我们在命令行中输入python hello.py时,其实是激活了Python的“解释器”,告诉“解释器”:你要开始工作了。可是在“解释”之前,其实执行的第一项工作和Java一样,是编译。

熟悉Java的同学可以想一下我们在命令行中如何执行一个Java的程序:

javac hello.java

java hello

只是我们在用Eclipse之类的IDE时,将这两部给融合成了一部而已。其实Python也一样,当我们执行python hello.py时,他也一样执行了这么一个过程,所以我们应该这样来描述Python,Python是一门先编译后解释的语言。

4. 简述Python的运行过程

在说这个问题之前,我们先来说两个概念,PyCodeObject和pyc文件。

我们在硬盘上看到的pyc自然不必多说,而其实PyCodeObject则是Python编译器真正编译成的结果。我们先简单知道就可以了,继续向下看。

当python程序运行时,编译的结果则是保存在位于内存中的PyCodeObject中,当Python程序运行结束时,Python解释器则将PyCodeObject写回到pyc文件中。

当python程序第二次运行时,首先程序会在硬盘中寻找pyc文件,如果找到,则直接载入,否则就重复上面的过程。

所以我们应该这样来定位PyCodeObject和pyc文件,我们说pyc文件其实是PyCodeObject的一种持久化保存方式。

 

十、数据类型初识

1、数字

  1 2 是一个整数的例子。
  2 长整数 不过是大一些的整数。
  3 3.23和52.3E-4是浮点数的例子。E标记表示10的幂。在这里,52.3E-4表示52.3 * 10-4。
  4 (-5+4j)和(2.3-4.6j)是复数的例子,其中-5,4为实数,j为虚数,数学中表示复数是什么?。

int(整型)

  在32位机器上,整数的位数为32位,取值范围为-2**31~2**31-1,即-2147483648~2147483647
  在64位系统上,整数的位数为64位,取值范围为-2**63~2**63-1,即-9223372036854775808~9223372036854775807

long(长整型)
  跟C语言不同,Python的长整数没有指定位宽,即:Python没有限制长整数数值的大小,但实际上由于机器内存有限,我们使用的长整数数值不可能无限大。
  注意,自从Python2.2起,如果整数发生溢出,Python会自动将整数数据转换为长整数,所以如今在长整数数据后面不加字母L也不会导致严重后果了。
float(浮点型)

先扫盲 http://www.cnblogs.com/alex3714/articles/5895848.html
  浮点数用来处理实数,即带有小数的数字。类似于C语言中的double类型,占8个字节(64位),其中52位表示底,11位表示指数,剩下的一位表示符号。
complex(复数)
  复数由实数部分和虚数部分组成,一般形式为x+yj,其中的x是复数的实数部分,y是复数的虚数部分,这里的x和y都是实数。

注:Python中存在小数字池:-5 ~ 257

2、布尔值

  真或假

  1 或 0

3、字符串

"hello world"

万恶的字符串拼接:

  python中的字符串在C语言中体现为是一个字符数组,每次创建字符串时候需要在内存中开辟一块连续的空,并且一旦需要修改字符串的话,就需要再次开辟空间,万恶的+号每出现一次就会在内从中重新开辟一块空间。

字符串格式化输出

  1 name = "Aige"
  2 print "I am %s " % name
  3 
  4 #输出: I am Aige

PS: 字符串是 %s;整数 %d;浮点数%f

字符串常用功能:

  • 移除空白
  • 分割
  • 长度
  • 索引
  • 切片

4、列表

创建列表:

  1 name_list = ['Aige', 'seven', 'eric']
  2  3 name_list = list(['Aige', 'seven', 'eric'])

基本操作:

  • 索引
  • 切片
  • 追加
  • 删除
  • 长度
  • 切片
  • 循环
  • 包含

5、元组(不可变列表)

创建元组:

  1 ages = (11, 22, 33, 44, 55)
  2  3 ages = tuple((11, 22, 33, 44, 55))

6、字典(无序)

创建字典:

  1 person = {"name": "mr.wu", 'age': 18}
  2  3 person = dict({"name": "mr.wu", 'age': 18})

常用操作:

  • 索引
  • 新增
  • 删除
  • 键、值、键值对
  • 循环
  • 长度

 

十一、数据运算    a=20,b=10

1.算数运算

运算符

描述

实例

+

a+b输出结果30

-

a-b输出结果10

*

a*b 输出结果200

/

a/b输出结果2

%

取模

a/b输出结果0

**

取幂

a**b输出结果20的10次方

//

取整除

9/2输出结果4,9.0/2.0输出结果4.0

  1 >>> a=20
  2 >>> b=10
  3 >>> a+b
  4 30
  5 >>> a-b
  6 10
  7 >>> a*b
  8 200
  9 >>> a/b
 10 2.0
 11 >>> a**b
 12 10240000000000
 13 >>> a//b
 14 2
算数运算

2.比较运算:

运算符

描述

实例

==

等于

(a==b)返回False

!+

不等于

(a!=b)返回True

<>

不等于

(a<>b)返回True #3.x测试错误

>

大于

(a>b)返回True

>=

大于等于

(a>=b)返回True

<

小于

(a<b)返回False

<=

小于等于

(a<=b)返回False

  1 >>> a=20
  2 >>> b=10
  3 >>> a == b
  4 False
  5 >>> a != b
  6 True
  7 >>> a <> b
  8   File "<stdin>", line 1
  9     a <> b
 10        ^
 11 SyntaxError: invalid syntax
 12 >>> a > b
 13 True
 14 >>> a >= b
 15 True
 16 >>> a < b
 17 False
 18 >>> a <= b
 19 False
比较运算

 

 

3.赋值运算

运算符

描述

实例

=

简单的赋值运算符

c=a+b,将a+b的运算结果赋值给c(30)

+=

加法赋值运算符

c+=a 等效于c=c+a

-=

减法赋值运算符

c-=a 等效于c=c-a

*=

乘法赋值运算符

c*=a 等效于c=c*a

/=

除法赋值运算符

c/=a 等效于c=c/a

%=

取模赋值运算符

c%=a 等效于c=c%a

**=

取幂赋值运算符

c**=a 等效于c=c**a

//=

取整除赋值运算符

c//=a 等效于c=c//a

  1 >>> a = 20
  2 >>> b = 10
  3 >>> c = a + b
  4 >>> c
  5 30
  6 >>> c += a
  7 >>> c
  8 50
  9 >>> c -= a
 10 >>> c
 11 30
 12 >>> c *= a
 13 >>> c
 14 600
 15 >>> c /= a
 16 >>> c
 17 30.0
 18 >>> c %= a
 19 >>> c
 20 10.0
 21 >>> c **= a
 22 >>> c
 23 1e+20
 24 >>> c //= a
 25 >>> c
 26 5e+18
赋值

 

4.逻辑运算

运算符

描述

实例

and

布尔“与”

(a and b)返回True

or

布尔“或”

(a or b)返回True

not

布尔“非”

not(a and b)返回False

  1 >>> a = 20
  2 >>> b = 10
  3 >>> a and b
  4 10
  5 >>> a or b
  6 20
  7 >>> not (a and b)
  8 False
逻辑运算

 

5.成员运算

运算符

描述

实例

in

如果再指定的序列中找到值,返回True,否则返回False

x在y序列中,如果x在y序列中返回True

not in

如果再指定的序列中找不到值,返回True,否则返回False

x在y序列中,如果x在y序列中返回False

  1 >>> a = [1,2,3,4,5,6,7,8]
  2 >>> b = 1
  3 >>> b in a
  4 True
  5 >>> b = 10
  6 >>> b not in a
  7 True
  8 >>>
成员运算

6.身份运算

运算符

描述

实例

is

is是判断两个标识符是不是引用自一个对象

x is y,如果id(x)等于id(y),is返回结果1

is not

is not是判断两个标识符是不是引用不同对象

x is not y,如果id(x)不等于id(y),is not返回1

  1 >>> a = 20
  2 >>> b = 10
  3 >>> c = a
  4 >>> id(a)
  5 1954522816
  6 >>> id(b)
  7 1954522496
  8 >>> id(c)
  9 1954522816
 10 >>> a is c
 11 True
 12 >>> a is b
 13 False
 14 >>> a is not b
 15 True
 16 >>> a is not c
 17 False
身份运算运算

7.位运算

运算符

描述

实例 a=00001010 b=00010100

&

按位与运算符

(a&b)输出结果0

|

按位或运算符

(a|b)输出结果30

^

按位异或运算符

(a^b)输出结果30

~

按位取反运算符

~10输出结果-11

<<

左移运算符

a<<2输出结果40

>>

右移运算符

a>>2输出结果2

  1 >>> 10 & 20
  2 0
  3 >>> 20 &10
  4 0
  5 >>> 1&1
  6 1
  7 >>> 15&14
  8 14
  9 >>> 10|20
 10 30
 11 >>> 10^20
 12 30
 13 >>> ~10
 14 -11
 15 >>> 10<<2
 16 40
 17 >>> 10>>2
 18 2
 19 >>>
按位运算

 

 

十二、表达式if ...else语句

场景一:用户登录

  1 #!/usr/bin/env python
  2 # _*_ coding:utf-8 _*_
  3 
  4 # !/usr/bin/env python
  5 # -*- coding: encoding -*-
  6 
  7 import getpass
  8 
  9 name = input('请输入用户名:')
 10 pwd = input('请输入密码:')
 11 
 12 if name == "Aige" and pwd == "abc":
 13     print("欢迎,Aige!")
 14 else:
 15     print("用户名和密码错误")
 
运行结果
 16 请输入用户名:Aige
 17 请输入密码:abc
 18 欢迎,Aige!

 

 

十三、表达式for 循环

简单循环10次

  1 >>> for I in range(10):
  2 ...   print(I)
  3 ...
  4 0
  5 1
  6 2
  7 3
  8 4
  9 5
 10 6
 11 7
 12 8
 13 9

十四、break and continue 

continue

  1 for I in range(10):
  2     if I<5:
  3         continue #不往下走了,直接进入下一次loop
  4     print("loop:", I )

break

  1 for I in range(10):
  2     if I>5:
  3         break #不往下走了,直接跳出整个loop
  4     print("loop:", I )

 

十五、表达式while 循环

猜年龄游戏

  1 #!/usr/bin/env python
  2 # _*_ coding:utf-8 _*_
  3 
  4 _age = 18
  5 count = 0
  6 while count<3:
  7     guess_input = int(input("Input your guess num:"))
  8     if guess_input == _age:
  9         print("bingo..")
 10         break
 11     elif guess_input < _age:
 12         print("smaller..")
 13     else:
 14         print("bigger..")
 15     count +=1
 16     if count == 3:
 17         continue_comfirm = input("do you want to continue:")
 18         if continue_comfirm != "n":
 19             count = 0
 20 #else:
 21 #    print("you also three times!!!")
猜年龄

 

矮哥:运维群93324526

 

posted @ 2017-05-29 16:03  汉克书  阅读(632)  评论(0编辑  收藏  举报