python基础-编码_if条件判断

时间:2021-11-07 03:05:52

一、第一句Python代码

在 /home/dev/ 目录下创建 hello.py 文件,内容如下:

 [root@python-3 scripts]# cat hello.py
#!/usr/bin/env python print("Hello World!")

输出结果:

 [root@python-3 scripts]# python hello.py
Hello World!

python基础-编码_if条件判断

二、解释器

上一步中执行 python /home/dev/hello.py 时,明确的指出 hello.py 脚本由 python 解释器来执行。

如果想要类似于执行shell脚本一样执行python脚本,例: ./hello.py ,那么就需要在 hello.py 文件的头部指定解释器,如下:

#!/usr/bin/env python

print "hello,world"

如此一来,执行: ./hello.py 即可。

ps:执行前需给予 hello.py 执行权限,chmod 755 hello.py 否则会报错!

三、内容编码

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

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

python基础-编码_if条件判断

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

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

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

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

报错:ascii码无法表示中文

 #!/usr/bin/env python       #python3.0的格式

 print "你好,世界"

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

 #!/usr/bin/env python       #python2.7的格式
# -*- coding: utf-8 -*- #Python2.7 每个文件中只要出现中文,头部必须加 print "你好,世界"

编码解释如下:

 8位:所有英文,字符,数字,ASCII

 01001010    - 2**8 =256
A 65 '0b1000001' 万国码 unicode
A 65 '000000000b1000001'
最少用2个字节(16):
1byte = 8bit =01010101
2 16 0101010101010101 =2**16 汉字占3个字节:
刘小明
三个汉字=9字节
010101010101010101010100 UTF-8
unicode加工
英文:8位
欧洲:16位
中文:24位

四、注释

  当行注视:# 被注释内容

  多行注释:""" 被注释内容 """

ps:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: huzhihua ''' #这就是注释 a = "alex"
b = a.capitalize()
print(a)
print(b) ''' #这就是注释

五、执行脚本传入参数

Python有大量的模块,从而使得开发Python程序非常简洁。类库有包括三中:

  • Python内部提供的模块
  • 业内开源的模块
  • 程序员自己开发的模块

Python内部提供一个 sys 的模块,其中的 sys.argv 用来捕获执行执行python脚本时传入的参数.

 #!/usr/bin/env python
# -*- coding: utf-8 -*- import sys print sys.argv

六、 pyc 文件

执行Python代码时,如果导入了其他的 .py 文件,那么,执行过程中会自动生成一个与其同名的 .pyc 文件,该文件就是Python解释器编译之后产生的字节码。

ps:代码经过编译可以产生字节码;字节码通过反编译也可以得到代码。

七、变量

1、声明变量

 #!/usr/bin/env python      #解释器

 # -*- coding: utf-8 -*-    #写python2.7必须把这段代码加上,因为2.7默认用的是ASCII码。如果是python3.0就不需要这段代码,因为他默认就是utf-8,utf-8默认就支持中文。

 name = "nulige"

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

变量的作用:昵称,其代指内存里某个地址中保存的内容

python基础-编码_if条件判断

变量定义的规则:

  • 变量名只能是 字母、数字或下划线的任意组合
  • 变量名的第一个字符不能是数字
  • 以下关键字不能声明为变量名
    ['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']
  • 最好不好和python内置的东西重复

2、变量的赋值

 #!/usr/bin/env python
# -*- coding: utf-8 -*- name1 = "nulige"
name2 = "alex"

python基础-编码_if条件判断

 #!/usr/bin/env python
# -*- coding: utf-8 -*- name1 = "nulige"
name2 = name1

python基础-编码_if条件判断

3、变量的赋值示例

 #Author: huzhihua
name = "Alex li"
name2 = name
print("My name is " ,name,name2) name = "PaoChe Ge"
print(name,name2)

执行结果:

 My name is Alex li Alex li
PaoChe Ge Alex li

4、变量的几种常用用法

 1)
_name = "Alex li" 2)
name = "Alex li" 3)
gf_gf_oldboy ="Chen rong hua" 4)
GFOfOldboy = "Chen rong hua"

八、输入

执行一个操作
提醒用户输入:用户和密码
获取用户名和密码,检测:用户名=root 密码=root
正确:登录成功
错误:登陆失败

input的用法,永远等待,直到用户输入了值,就会将输入的值赋值给一个东西

 n1 = input('请输入用户名:')
n1 = input('请输入密码:') print(n1)
print(n2)

判断用户输入用户名和密码

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige n1 = input("请输入用户名:")
n2 = input("请输入密码:")
if n1 == "root" and n2 == "root!23":
print("登录成功")
else:
print("登录失败")

执行结果:

 请输入用户名:root
请输入密码:root!23
登录成功

python2.7 和3.0 inpu用法的区别

 #!/usr/bin/env python
# -*- coding: utf-8 -*- # 将用户输入的内容赋值给 name 变量
name = raw_input("请输入用户名:") #python2.7的用法
#name = input("请输入用户名:") #python3.0的用法
 # 打印输入的内容  print name

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

ps1:

 #!/usr/bin/env python
# -*- coding: utf-8 -*- import getpass # 将用户输入的内容赋值给 name 变量
pwd = getpass.getpass("请输入密码:") # 打印输入的内容
print pwd

ps2:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige #写各种各样的功能
#找到lib.py,将文件内容替换 import lib
#import lib #print('index')
import getpass #等待用户输入用户名,用户输入之后
#将输入的用户名 赋值给i1,即:i1代指用户名 i1 = raw_input("UserName:") #python2.7 #i2 =raw_input("请输入密码:")
#等待用户输入密码,用户输入之后
#将输入的密码,赋值给i2,即:i2代指密码,
i2 = getpass.getpass("PassWord:")
print(i1)
print(i2)

创建一个基本的py文件的流程如下:

1、创建xxx.py 文件

ps:不要有中文路径

2、写代码

a、头部两行

b、写功能代码

3、执行代码

a、打开终端

功能键+R

b、python 代码文件的路径

九、流程控制和缩进

 条件语句
缩进用4个空格
a.
n1 = input('>>>') if "alex" == "alex":
n2 = input('>>>')
if n2 == "确认":
print('alex SB')
else:
print('alex DB')
else:
print('error') 注意:
n1 = "alex" 赋值
n1 == 'alex' 比较, b.
if 条件1:
pass
elif 条件2:
pass
elif 条件3:
pass
else:
pass print('end') c.条件1
and or if n1 == "alex" or n2 == "alex!23":
print('OK')
else:
print('OK') PS:
pass 代指空代码,无意义,仅仅用于表示代码块

需求一、用户登陆验证

 #!/usr/bin/env python
# -*- coding: encoding -*- # 提示输入用户名和密码 # 验证用户名和密码
# 如果错误,则输出用户名或密码错误
# 如果成功,则输出 欢迎,XXX! import getpass name = raw_input('请输入用户名:')
pwd = getpass.getpass('请输入密码:') if name == "alex" and pwd == "cmd":
print "欢迎,alex!"
else:
print "用户名和密码错误"

需求二、根据用户输入内容输出其权限

 # 根据用户输入内容打印其权限

 # alex --> 超级管理员
# eric --> 普通管理员
# tony,rain --> 业务主管
# 其他 --> 普通用户 name = raw_input('请输入用户名:') if name == "alex":
print "超级管理员"
elif name == "eric":
print "普通管理员"
elif name == "tony" or name == "rain":
print "业务主管"
else:
print "普通用户"

需求三: 判断输入用户和密码是否正确

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: huzhihua
#import getpass _username = 'nulige'
_password = ''
username = input("username:")
#password = getpass.getpass("password:")
password = input("password:")
if _username == username and _password == password:
print("Welcome user {name} login...".format(name=username))
else:
print("Invalid username or password!")

执行结果:

输入正确的用户名和密码,提示:Welcome user nulige login...

 username:nulige
password:123456
Welcome user nulige login...

输入错误的用户名和密码,提示:Invalid username or password!

 username:nulige
password:321211
Invalid username or password!

需求四:判断年龄

示例1

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: huzhihua age_of_oldboy = 56
guess_age = int(input("guess age:"))
if guess_age == age_of_oldboy:
print("yes, you got it. ")
elif guess_age > age_of_oldboy:
print("think smaller... ")
else:
print("think bigger!")

执行结果:

 guess age:23
think bigger!
 guess age:58
think smaller...
 guess age:56
yes, you got it.

示例2

输入三次,就会打印出 you have tried too many times..fuck off 这段话

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige age_of_oldboy = 56
count = 0 while count <3:
guess_age = int(input("guess age:"))
if guess_age == age_of_oldboy :
print("yes, you got it. ")
break
elif guess_age > age_of_oldboy:
print("think smaller... ")
else:
print("think bigger!")
count +=1
if count == 3:
print("you have tried too many times..fuck off")

执行结果:

 guess age:1
think bigger!
guess age:2
think bigger!
guess age:3
think bigger!
you have tried too many times..fuck off

示例3

输入三次进行条件判断

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige age_of_oldboy = 56
count = 0 while count <3:
guess_age = int(input("guess age:"))
if guess_age == age_of_oldboy :
print("yes, you got it. ")
break
elif guess_age > age_of_oldboy:
print("think smaller... ")
else:
print("think bigger!")
count +=1
else:
print("you have tried too many times..fuck off")

执行结果:

 guess age:23
think bigger!
guess age:45
think bigger!
guess age:67
think smaller...
you have tried too many times..fuck off

原理图:

python基础-编码_if条件判断

十、while循环

1、基本循环

 while 条件:

     # 循环体

     # 如果条件为真,那么循环体则执行
# 如果条件为假,那么循环体不执行

示例

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: huzhihua count = 0
while True:
print("count:",count)
count = count +1 #count +=1

2、break

break用于退出所有循环

示例1:

 while True:
print ("")
break
print ("")

执行结果:

 123

示例2:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige count = 0
while True:
print("count:",count)
count = count +1 #count +=1

执行结果:

 count: 605452
count: 605453
count: 605454
count: 605455
count: 605456
count: 605457
count: 605458
count: 605459
count: 605460
count: 605461
后面省略.....

示例3:

意思是:执行到10就中间(从0-9)

 count = 0
while True:
print("count:",count)
count = count +1 #count +=1
if count == 10:
break

执行结果:

 count: 0
count: 1
count: 2
count: 3
count: 4
count: 5
count: 6
count: 7
count: 8
count: 9

练习题

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

法一:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige n = 1
while n < 11:
if n == 7:
pass
else:
print(n)
n = n + 1

法二:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige i = 1
while i<=10:
if i==7:
i += 1
else:
print(i)
i+=1

执行结果:

 1
2
3
4
5
6
8
9
10

2、求1-100的所有数的和

法一:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige n = 1
s = 0
while n < 101:
s = s + n
n = n + 1 print(s)

法二:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige i = 1
sum = 0
while i<=100:
sum += i
i += 1
print(sum)

执行结果:

 5050

法三:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige n = 0
for x in range(101):
n = n + x
print(n)

执行结果:

 5050

法四:

用求和函数方法实现

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige print (sum(range(1, 101)))

执行结果:

 5050

Linux的实现方法:

 [root@python-3 scripts]# awk 'BEGIN{i=1;do{sum+=i;i++}while (i<=100);print sum}'
5050
[root@python-3 scripts]# awk 'BEGIN{i=1;while (i<=100){sum+=i;i++};print sum}'
5050
[root@python-3 scripts]# awk 'BEGIN{sum=0;for (i=1;i<=100;i++)sum+=i;print sum}'
5050
[root@python-3 scripts]# declare sum=0;for i in `seq 1 100`;do let sum+=$i;done;echo $sum
5050

3、输出 1-100 内的所有奇数

知识点:整数中,能被2整除的数是偶数,不能被2整除的数是奇数

ps:

奇数就是单数、如:1,3,5,7,9,11等。

法一:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige n = 1
while n < 101:
temp = n % 2
if temp == 0:
pass
else:
print(n)
n = n + 1

法二:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige count = 1
while count < 101:
num=count%2
if num == 1:
print(count)
count += 1

执行结果:

 1
3
5
7
9
11
13
15
17
19
21
23
25
27
29
31
33
35
37
39
41
43
45
47
49
51
53
55
57
59
61
63
65
67
69
71
73
75
77
79
81
83
85
87
89
91
93
95
97
99

法三:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige inte = 1
#输出1到100间的奇数
while inte <= 100:
if inte % 2 == 1:
print (inte)
inte = inte + 1

执行结果:

 1
3
5
7
9
11
13
15
17
19
21
23
25
27
29
31
33
35
37
39
41
43
45
47
49
51
53
55
57
59
61
63
65
67
69
71
73
75
77
79
81
83
85
87
89
91
93
95
97
99

4、输出 1-100 内的所有偶数

知识点:整数中,能被2整除的数是偶数,不能被2整除的数是奇数

ps:

双数就是偶数、如:0,2,4,6,8,10等。

法一:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige n = 1
while n < 101:
temp = n % 2
if temp == 0:
print(n)
else:
pass
n = n + 1

法二:

 count = 1
while count < 101:
num=count%2
if num == 0:
print(count)
count += 1

执行结果:

 2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40
42
44
46
48
50
52
54
56
58
60
62
64
66
68
70
72
74
76
78
80
82
84
86
88
90
92
94
96
98
100

5、求1-2+3-4+5 ... 99的所有数的和

法一:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige n = 1
s = 0 # s是之前所有数的总和
while n < 100:
temp = n % 2
if temp == 0:
s = s - n
else:
s = s + n
n = n + 1 print(s)

法二:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige count = 1
while count < 100:
if count == 1:
num = count
elif count%2 == 1:
num = num + count
elif count%2 == 0:
num = num - count
count += 1
print(num)

执行结果:

 50

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

流程图

python基础-编码_if条件判断

法一:

 count = 0
while count < 3:
user = input('>>>')
pwd = input('>>>')
if user == 'alex' and pwd == '':
print('欢迎登陆')
print('..........')
break
else:
print('用户名或者密码错误')
count = count + 1

法二:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
#Author: nulige _username,_password,i = "nulige","",1
while i < 4:
input_name = input("Username:")
input_passwd = input("Password:")
if input_name == _username and input_passwd == _password:
print("login is successful!")
break
else:
print("The user name or password you entered is incorrect. Please enter again.")
i += 1
continue
print("Enter more than 3 times, This program will exit")

执行结果:

输入错误的用户名和密码

 Username:111
Password:2222
The user name or password you entered is incorrect. Please enter again.
Username:2222
Password:2222
The user name or password you entered is incorrect. Please enter again.
Username:2222
Password:222
The user name or password you entered is incorrect. Please enter again.
Enter more than 3 times, This program will exit

输入正确的用户名和密码

 Username:nulige
Password:123456
login is successful!
Enter more than 3 times, This program will exit

法三:

 #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author: nulige count = 3
while count > 0:
username = input("Please enter your username:")
pwd = input("Please enter your password:")
if username == "nulige" and pwd == "":
print("User:",username,",Login successful ! ")
break
else:
count -= 1
if count != 0:
print("Login failed",count)
else:
print("Enter more than 3 times, This program will exit")

执行结果:

输入错误的用户名和密码

 Please enter your username:111
Please enter your password:222
Login failed 2
Please enter your username:111
Please enter your password:222
Login failed 1
Please enter your username:111
Please enter your password:222
Enter more than 3 times, This program will exit

输入正确的用户名和密码

 Please enter your username:nulige
Please enter your password:123456
User: nulige ,Login successful !