Python应用范围
- 操作系统
- WEB
- 3D动画
- 企业应用
- 云计算
Python3.0和以前的版本有大量的不兼容问题
用IDLe界面写的Python代码:
Python 3.8.6 (tags/v3.8.6:db45529, Sep 23 2020, 15:52:53) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> print("Hello World")
Hello World
>>> print(5+3)
8
>>> print(1000000000*10000)
10000000000000
>>> print("Hello"+"World")
HelloWorld
>>> print("Hello World"*3)
Hello WorldHello WorldHello World
>>> print("Hello World\n"*3)
Hello World
Hello World
Hello World
IDLe提示功能:Tab键
Python不像C、Java一样有严格的程序定界括号,但是需要用缩进来分辨程序边界。
print("第一个游戏");
temp=input("猜数字:")
guess=int(temp)
if guess ==5:
print("You Win!")
else:
print("You Lose!")
print("Game Over!")
BIF == Build-in functions内置函数
查询Python内置函数命令:
>>> dir(__builtins__)
[‘ArithmeticError’, ‘AssertionError’, ‘AttributeError’, ‘BaseException’, ‘BlockingIOError’, ‘BrokenPipeError’, ‘BufferError’, ‘BytesWarning’, ‘ChildProcessError’, ‘ConnectionAbortedError’, ‘ConnectionError’, ‘ConnectionRefusedError’, ‘ConnectionResetError’, ‘DeprecationWarning’, ‘EOFError’, ‘Ellipsis’, ‘EnvironmentError’, ‘Exception’, ‘False’, ‘FileExistsError’, ‘FileNotFoundError’, ‘FloatingPointError’, ‘FutureWarning’, ‘GeneratorExit’, ‘IOError’, ‘ImportError’, ‘ImportWarning’, ‘IndentationError’, ‘IndexError’, ‘InterruptedError’, ‘IsADirectoryError’, ‘KeyError’, ‘KeyboardInterrupt’, ‘LookupError’, ‘MemoryError’, ‘ModuleNotFoundError’, ‘NameError’, ‘None’, ‘NotADirectoryError’, ‘NotImplemented’, ‘NotImplementedError’, ‘OSError’, ‘OverflowError’, ‘PendingDeprecationWarning’, ‘PermissionError’, ‘ProcessLookupError’, ‘RecursionError’, ‘ReferenceError’, ‘ResourceWarning’, ‘RuntimeError’, ‘RuntimeWarning’, ‘StopAsyncIteration’, ‘StopIteration’, ‘SyntaxError’, ‘SyntaxWarning’, ‘SystemError’, ‘SystemExit’, ‘TabError’, ‘TimeoutError’, ‘True’, ‘TypeError’, ‘UnboundLocalError’, ‘UnicodeDecodeError’, ‘UnicodeEncodeError’, ‘UnicodeError’, ‘UnicodeTranslateError’, ‘UnicodeWarning’, ‘UserWarning’, ‘ValueError’, ‘Warning’, ‘WindowsError’, ‘ZeroDivisionError’, ‘build_class’, ‘debug’, ‘doc’, ‘import’, ‘loader’, ‘name’, ‘package’, ‘spec’, ‘abs’, ‘all’, ‘any’, ‘ascii’, ‘bin’, ‘bool’, ‘breakpoint’, ‘bytearray’, ‘bytes’, ‘callable’, ‘chr’, ‘classmethod’, ‘compile’, ‘complex’, ‘copyright’, ‘credits’, ‘delattr’, ‘dict’, ‘dir’, ‘divmod’, ‘enumerate’, ‘eval’, ‘exec’, ‘exit’, ‘filter’, ‘float’, ‘format’, ‘frozenset’, ‘getattr’, ‘globals’, ‘hasattr’, ‘hash’, ‘help’, ‘hex’, ‘id’, ‘input’, ‘int’, ‘isinstance’, ‘issubclass’, ‘iter’, ‘len’, ‘license’, ‘list’, ‘locals’, ‘map’, ‘max’, ‘memoryview’, ‘min’, ‘next’, ‘object’, ‘oct’, ‘open’, ‘ord’, ‘pow’, ‘print’, ‘property’, ‘quit’, ‘range’, ‘repr’, ‘reversed’, ‘round’, ‘set’, ‘setattr’, ‘slice’, ‘sorted’, ‘staticmethod’, ‘str’, ‘sum’, ‘super’, ‘tuple’, ‘type’, ‘vars’, ‘zip’]
以上纯小写的部分为BIF
用help命令可以获得bif的具体解释:
>>> help(input)
Help on built-in function input in module builtins:
input(prompt=None, /)
Read a string from standard input. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a
trailing newline before reading input.
If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
On *nix systems, readline is used if available.
Python变量
大多数编程语言都是“把值放在变量中”,Python更像是“把名字贴在值上”。
>>> name="张三"
>>> print(name)
张三
>>> name="李四"
>>> print(name)
李四
>>> first=3
>>> second=5
>>> third=first+second
>>> print(third)
8
>>> name="张三"
>>> word="你好"
>>> outWord=name+word
>>> print(outWord)
张三你好
变量使用需注意:
- 变量使用前需要先赋值
- 变量命名包括字母、数字、下划线,但不能以数字开头
- 字母可以是大小写,但是Python需要区分大小写
字符串
字符串的定界符可以为单引号或双引号,如果需要在字符串中输出单引号‘或双引号“,可以使用转义字符 \ '或 \ "
>>> "5"+"8"
'58'
>>> "\"Hello\""
'"Hello"'
原始字符串
当输出的字符串中含有反斜杠\时,我们可以使用反斜杠进行转义:
>>> print("C:\now")
C:
ow
>>> print("C:\\now")
C:\now
>>>
当一个字符串中有很多个反斜杠时,在每一个将每一个反斜杠符号进行转义非常麻烦,可以在字符串前加上一个r即可。
>>> print(r"C:\now\aa\bb\cc")
C:\now\aa\bb\cc
但是原始字符串如果最后一个字符是反斜杠符会报错,可以尝试将原始字符串和转义字符结合输出:
>>> print(r"C:\now"+"\\")
C:\now\
长字符串
如果要输出一个跨越多行的字符串,需要用到三重引号字符串
>>> str="""1111
2222
3333
4444
5555
"""
>>> str
'1111\n2222\n3333\n4444\n5555\n'
>>> print(str)
1111
2222
3333
4444
5555
条件分支
python的比较操作符 | 代表意义 |
---|---|
> | 大于 |
>= | 大于等于 |
< | 小于 |
<= | 小于等于 |
== | 等于 |
!= | 不等于 |
>>> 1<2
True
>>> 3>4
False
条件分支语法
if 条件:
条件=true的执行语句
else:
条件=false的执行语句
循环结构
while循环
while 条件:
条件=true的执行语句
and逻辑操作符
>>> 3>2 and 10>1
True
>>> 2<3 and 9>10
False
引入外援(产生随机数)
IDLe的Run菜单下Run Model功能->Model模块
比如为了产生一个随机数,我们需要引入外援:random模块
random模块中的randint()函数会返回一个随机的整数
条件语句、循环语句、引用外援的简单例子:
import random
num=random.randint(1,10)
print("Game Start!")
temp=input("猜数字:")
guess=int(temp)
count=int(1)
while guess!=num and count<3:
count=count+1
if guess>num :
print("猜大了")
else :
print("猜小了")
temp=input("猜数字:")
guess=int(temp)
if count>=3 :
print("猜错3次,游戏结束")
else :
print("猜对了!")
Python数据类型
- 整形
- 浮点型
- 布尔型
python浮点数的科学计数法形式
>>> 0.0000000000000035
3.5e-15
>>> 6e09
6000000000.0
布尔型数据
True=int(1)
False=int(0)
>>> True+False
1
>>> True*2+False
2
>>> True*False
0
数据类型转换
整数:int()
如果转化的数据后面有小数,证书转换直接把小数部分去除
>>> a=3.5
>>> b=int(a)
>>> b
3
字符串:str()
>>> num1=str(1)
>>> num2=str(2)
>>> num1+num2
'12'
>>> a=str(3e10)
>>> a
'30000000000.0'
浮点数:float()
>>> a=float(1234)
>>> a
1234.0
int、str、float都可以作为变量名,但如果已经存在以其命名的变量时,再使用类型转换会报错,不推荐使用。
type函数
type(变量名)可以返回变量的数据类型
>>> a="111"
>>> type(a)
<class 'str'>
>>> type(122)
<class 'int'>
>>> type(1.2)
<class 'float'>
>>> type(True)
<class 'bool'>
isinstance函数
boolean isinstance(变量名, 指定数据类型)
如果变量类型和指定数据类型相符合,返回True,否则返回False
>>> isinstance(1,int)
True
>>> a="123456"
>>> isinstance(a,float)
False
>>> isinstance(a,str)
True
Python常用操作符
算术操作符
>>> a=b=c=d=10
>>> a+=5
>>> b-=5
>>> c*=5
>>> d/=5
>>> a
15
>>> b
5
>>> c
50
>>> d
2.0
注意普通除法(/)和整数除法(//)的区别
>>> 9/10
0.9
>>> 9//10
0
幂运算符:**
>>> 3**2
9
求余运算符:%
>>> 11%3
2
比较操作符
与其他语言不同的是,Python可以使用如下比较形式
>>> 3<4<5
True
逻辑操作符
与and
或or
非not
操作符优先级(从上到下优先级递减)
幂运算
正负号
算术运算符
比较运算符
逻辑运算符(not>and>or)