学习完c/c++这些编程语言后,想快速掌握python的基础语法,方便使用python应用
1.数字操作符
** 指数 2**3 8
// 取整 22//8 2
/ 除法 5/2 2.5 (默认浮点型)
优先级从高到低:** * / // % + -
2.基本数据类型:整型,浮点型(无单双精度),字符串(‘hello world’)
强制类型转换 str() int() float() None
>>>str(29) int('42') float('3') 类似c中null
29 42 3.0
3.单行结束一般无“;”,回车键结尾
4变量名
a,只能一个词
b,只能包含字母,数字,下划线
c,不能数字开头
注:python 代码风格支持PEP 8,即下划线 eg:look_like
5,文本输入,输出
a ,myName=input() 输入文本,input()函数返回为一个字符串
eg:用户输入 “al”,求值为myName='al'
b ,print('Hello world') 输出文本,将字符串传递到函数print()
eg:print('nice to meet you ' +myName)
c,变元end 将独立两行变成一个字符串
print ('hello',end='')
print('Alice')
helloAlice
d,变元sep 替换默认的分隔字符串
>>> print('cat','dog')
cat dog
>>>print('cat','dog',sep=',')
cat,dog
6.注释
# 注释单行文本
7.布尔值 Boolean
True False 大小写敏感
not操作符 >>>not True False
and操作符 >>> True and False False
or操作符 >>>True and False True
优先级:not>and>or
8.代码块缩进 python通过缩进控制代码块开始结束
a,缩进增加时,代码块开始
b,代码块可以包含其他代码块
c,缩进减小量小于0时,代码段结束
9,if语句 if 条件: 代码块
if name =='alice':
print('Hi,Alice.')
if name=='Alice'
print('Hi,Alice')
elif age <12:
print('you are child')
elif sex=='F':
print('girl')
else语句 else条件: 代码块
def spam(divideBy):
try:
return 42/divideBy
except ZeroDivisionError:
print('Error:Invalid argument.')
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
10.循环语句
a,while语句 while条件:代码块
b,break,continue语句
c,for语句和rang()函数 for变量名in rang(参数):代码块
注:最多传入三个参数x,y,z 【x,y) z:步长(正负皆可)
11,导入模块 import模块名,模块名
import random
for i in range(5):
print(random.randint(1,10))
12,sys.exit() 提前结束程序13,
a,def 语句 定义局部函数
def hello():
print('hello ')
print('Alice')
第一行def语句定义一个hello()函数,之后的代码块为函数体,仅在函数调用时执行s
b,gobel语句 将局部变量改为全局变量
14.异常处理 try-except
def spam(divideBy):
try:
return 42/divideBy
except ZeroDivisionError:
print('Error:Invalid argument.')
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))
21.0
3.5
Error:Invalid argument.
None
42.0
注:在try子句中发生错误,就直接跳到except子句中,向下执行。