"Hello_Python"_基础语法1

变量

变量定义

# 动态语言变量定义时不需要指明变量的数据类型
# 字符串类型变量可以使用""或'',""和''在Python中没有区别,不加""或''的字符串系统默认为变量名
name = "young"
age = 25
print("My name is", name, "...I'm", age, "years old!")

输出结果如下:
My name is young ...I'm 25 years old!

Python中没有常量的概念,如果需要表示某一固定不变的量,例如数学中的π,一般习惯将变量名全大写表示:

PIE = 3.1415926

当变量被定义时,内存中会开辟一块区域存放该变量的值,同时变量名指向存放该值的区域

name_1 = "young"
name_2 = name_1     # name_2通过name_1找到内存中存放字符串"young"的地址,并直接指向
print("name_1 = ", name_1, "name_2 = ", name_2)
name_1 = "old"      # name_1改为指向内存中存放字符串"old"的地址,而name_2指向不变
print("name_1 = ", name_1, "name_2 = ", name_2)

输出结果如下:
name_1 =  young name_2 =  young
name_1 =  old name_2 =  young

代码注释

被注释部分在代码执行时会被系统略过

  • 单行注释

使用#进行单行注释

# print("My name is", name, "...I'm", age, "years old!")
  • 多行注释

使用'''注释内容'''或者"""注释内容"""进行多行注释

"""
print("Please call me", name_1, "......say again", name_2)
name_1 = "yang sir"
print("Please call me", name_2, "or", name_1)
"""
# 或
'''
print("Please call me", name_1, "......say again", name_2)
name_1 = "yang sir"
print("Please call me", name_2, "or", name_1)
'''

字符编码

  • ASCII码

支持英语和其他西欧语言,用 8 位(1个字节)来表示某一字符的编码,ASCII码最多只能表示2**8 = 256-1=255 个字符

  • GB2312

相比于ASCII码增加了中文字符的编码,使用16位(2个字节)来表示某一字符的编码,支持中文

  • GBK1.0

相比于GB2312增加了更多中文字符的编码,用16位(2个字节)来表示某一字符的编码

  • GB18030

相比于GBK1.0增加了更多中文字符以及其他少数名族语言的编码,用16位(2个字节)来表示某一字符的编码

从ASCII、GB2312、GBK 到GB18030,这些编码方法是向下兼容的,即同一个字符在这些方案中总是有相同的编码

  • Unicode

世界统一码,为各个不同国家的语言字符设定了统一并且唯一的二进制编码,规定所有的字符和符号最少由 16 位(2个字节)来表示

  • UTF-8

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

Python2默认字符编码是ASCII码,不支持中文,Python3默认支持中文,如果要让Python2支持中文,需要在代码文件首行中加入以下内容:

# _*_ coding:utf-8 _*_
# 或
# -*- coding:utf-8 -*-

如果使用PyCharm作为编译环境,无论是Python2还是Python3,都建议做如下编码设置:

"Hello_Python"_基础语法1

用户输入

name = input("Please input your name  :")

输出结果如下:
Please input your name  :     # 在此处输入赋予变量name的值并键入回车

Python2和Python3的区别

# Python2中raw_input()功能和Python3中input()功能相同
name = raw_input("please input your name:")

# Python2中的input()不推荐使用
name = input("Please input your name:")

输出结果如下:
Please input your name:young      
# 输入时如果不带"",系统会将输入的内容当作变量名处理
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'young' is not defined
    
name = input("Please input your name:")
Please input your name:"young"

格式化输出

多行格式化输出

多行注释还具备多行格式化输出的功能

# 跨越多行的字符串打印
hello = '''
Hello Word!
Hello Python!
'''
print(hello)

输出结果如下:
Hello Word!
Hello Python!
# 用户输入(经用户输入的变量默认类型为字符串)
name = input("name  :")
age = int(input("age   :"))    # 如果需要检验输入的有效性,建议强制类型转换(str to int)
job = input("job   :")
salary = int(input("salary:")) # 如果需要检验输入的有效性,建议强制类型转换(str to int)

# 打印变量的类型
print("name   type is", type(name))
print("age    type is", type(age))
print("job    type is", type(job))
print("salary type is", type(salary))

# 格式化打印
# 方式1:拼接字符串(需要开辟多块内存保存多个字符串变量,效率低,不推荐使用),参与字符串拼接的变量类型只能是字符串
info_1 = '''
**********Info of ''' + name + '''**********
name  : ''' + name + '''
age   : ''' + str(age) + '''
job   : ''' + job + '''
salary: ''' + str(salary)

print(info_1)

# 方式2: %s表示输入的数据类型为字符出串,%d可暂时理解为数字
info_2 = '''
**********Info of %s**********
name  : %s
age   : %d
job   : %s
salary: %d
''' % (name, name, age, job, salary)

print(info_2)

# 方式3: 官方推荐格式化输出使用这种方式,{}中的内容不一定要是变量名,{}中变量前后不能有空格
info_3 = '''
**********Info of {_name}**********
name  : {_name}
age   : {_age}
job   : {_job}
salary: {_salary}
'''.format(_name=name,
           _age=age,
           _job=job,
           _salary=salary)

print(info_3)

# 方式4:
info_4 = '''
**********Info of {0}**********
name  : {0}
age   : {1}
job   : {2}
salary: {3}
'''.format(name, age, job, salary)

print(info_4)

输出结果如下:
name  :young
age   :25
job   :IT
salary:50000
name   type is <class 'str'>
age    type is <class 'int'>
job    type is <class 'str'>
salary type is <class 'int'>

**********Info of young**********
name  : young
age   : 25
job   : IT
salary: 50000

**********Info of young**********
name  : young
age   : 25
job   : IT
salary: 50000


**********Info of young**********
name  : young
age   : 25
job   : IT
salary: 50000


**********Info of young**********
name  : young
age   : 25
job   : IT
salary: 50000

单行格式化输出

# 与多行格式化输出相同
money = 5000000
print("I want to earn " + str(money) + " dollars one day.")
print("I want to earn %d dollars one day." % money)
print("I want to earn {_money} dollars one day.".format(_money=money))
print("I want to earn {0} dollars one day.".format(money))

输出结果如下:
I want to earn 5000000 dollars one day.
I want to earn 5000000 dollars one day.
I want to earn 5000000 dollars one day.
I want to earn 5000000 dollars one day.

Python2和Python3区别

name = "young"
age = 25
# Python2中print无()
print "I'm {_name},I have {_age} years old.".format(_name=name, _age=age)

输出结果如下:
I'm young,I have 25 years old.

判断语句

可根据需求组合if,if...else,if...elif...elif...else等逻辑判断语句

# 导入Python标准库中的getpass模块
import getpass

username = "young"
password = "123456"

_username = input("Please input your username:")
# getpass输入时不显示任何输入的字符,input()输入时明文显示输入的字符,
# getpass在PyCharm中运行会卡住,需要到CMD中利用命令运行Python文件
_password = getpass.getpass("Please input your password:")

# Python使用强制缩进来区分不同级别的语句,位于*的语句必须顶格写,不然会出现"IndentationError"缩进错误
# =表示赋值,==表示判断是否相等
if _username == username and _password == password:
    print("Welcome {login_name} login !" .format(login_name=username))
else:
    print("Invalid username or password !")

循环语句

while循环

# 猜年龄,只允许猜3次
age_of_mine = 25
count = 0

while True:
    # 只允许循环猜3次
    if count >= 3:
        # 直接跳出停止循环
        count = 0
        break

    # 做大小关系比较需转换成数字
    age = int(input("Please guess my age:"))

    if age == age_of_mine:
        print("Yes,you got it !")
        count = 0
        break
    elif age > age_of_mine:
        print("Please think smaller !")
    else:
        print("Please think bigger !")

    # 每循环一次count计数加1,也可写为count = count + 1
    count += 1

# 以上程序优化
while count < 3:
    age = int(input("Please guess my age:"))

    if age == age_of_mine:
        print("Yes,you got it !")
        break

    elif age > age_of_mine:
        print("Please think smaller !")

    else:
        print("Please think bigger !")

    count += 1

# 当while循环每次开始时,while中的条件不成立时执行
else:
    print("you have tried too many times...fuck off!")
    
输出结果如下:
Please guess my age:22
Please think bigger !
Please guess my age:20
Please think bigger !
Please guess my age:26
Please think smaller !
you have tried too many times...fuck off!
Please guess my age:22
Please think bigger !
Please guess my age:20
Please think bigger !
Please guess my age:26
Please think smaller !
you have tried too many times...fuck off!
# 猜过3次后,询问是否继续,是则继续,否则停止
age_of_mine = 25
count = 0

while count < 3:
    age = int(input("Please guess my age:"))

    if age == age_of_mine:
        print("Yes,you got it !")
        break

    elif age > age_of_mine:
        print("Please think smaller !")

    else:
        print("Please think bigger !")

    count += 1

    if count == 3:
        continue_confirm = input("Do you want to keep guessing?(yes/no)")
        if continue_confirm != "no":
            count = 0
else:
    print("Game Over!")
    
输出结果如下:
Please guess my age:22
Please think bigger !
Please guess my age:26
Please think smaller !
Please guess my age:20
Please think bigger !
Do you want to keep guessing?(yes/no)no
Game Over!
*****************************************
Do you want to keep guessing?(yes/no)yes
Please guess my age:

for循环

# 循环10次,0-9
for a in range(10):
    print("a =:", a)
# range(起始[默认0],循环次数,步长[默认1])
for b in range(0, 10, 2):
    print("b =:", b)

age_of_mine = 25

for i in range(3):
    age = int(input("Please guess my age:"))

    if age == age_of_mine:
        print("Yes,you got it !")
        break

    elif age > age_of_mine:
        print("Please think smaller !")

    else:
        print("Please think bigger !")
# 当for循环每次开始时,i的范围不在rang()规定的范围内执行
else:
    print("You have tried too many times...fuck off!")

break和continue

for i in range(10):
    print("loop times: ", i+1)
    if i < 3:
        print("I have been printed: i =", i)
    else:
        # continue表示直接跳出本次循环,开始下一次循环
        continue
    # i>=3时不会被执行,程序经continue后直接开启下一次循环,共循环10次
    print("Program didn't skip me!")
    
输出结果如下:
loop times:  1
I have been printed: i = 0
Program didn't skip me!
loop times:  2
I have been printed: i = 1
Program didn't skip me!
loop times:  3
I have been printed: i = 2
Program didn't skip me!
loop times:  4
loop times:  5
loop times:  6
loop times:  7
loop times:  8
loop times:  9
loop times:  10
for a in range(10):
    print("loop times: ", a+1)
    if a < 3:
        print("I have been printed: a =", a)
    else:
        # break表示直接结束整个循环程序
        break
    # i=3时程序经break后结束整个循环,共循环3次
    print("Program didn't skip me!")
    
输出结果如下:
loop times:  1
I have been printed: a = 0
Program didn't skip me!
loop times:  2
I have been printed: a = 1
Program didn't skip me!
loop times:  3
I have been printed: a = 2
Program didn't skip me!
loop times:  4
for a in range(5):
    print("***********:a =", a)
    for b in range(5):
        if b > 3:
            # break只结束当前所在的整个循环程序
            break
        print("b =", b)
        
输出结果如下:
***********:a = 0
b = 0
b = 1
b = 2
b = 3
***********:a = 1
b = 0
b = 1
b = 2
b = 3
***********:a = 2
b = 0
b = 1
b = 2
b = 3
***********:a = 3
b = 0
b = 1
b = 2
b = 3
***********:a = 4
b = 0
b = 1
b = 2
b = 3
上一篇:java:堆


下一篇:jvm 结构分析