001 基础知识

来源:互联网 发布:软件著作权评职称 编辑:程序博客网 时间:2024/05/12 13:44
一、“+”:加号和连接符
  1. print(5+3) #output:8
  2. print('hello'+'world') #output:helloworld
二、help函数
  1. help(intput) #显示出input函数的用法和说明
三、randint()函数
意义:返回随机整数
  1. temp=randint(1,10) #返回[1,10]的整型随机数
四、r字符串
例如:想输出'C:\now\now1\now2',常规方法用很多转义字符
用r字符串就简便多了:
  1. print(r'C:\now\now1\now2')
注意:print(r'C:\now\now1\now2\')会报错,可用

print(r'C:\now\now1\now2'+'\\')
五、python中没有{},只能用缩进

if 1<2:
    print(r'1<2')
else:
    print(r'1>=2')
六、数据类型及转换
整型、字符串、浮点数、布尔类型(布尔类型也能当整数用)
转换:
整型:int()
字符串:str()
浮点数:float()
int('123')     #output:123
int(5.99)      #output:5
int('5.99')     #error!!

float(123)     #output:123.0
float('123')     #output:123.0

str(123)     #output:'123'   几乎啥都行
str(123.1)     #output:'123.1'
七、获取数据类型
  • type()
type(123)
type('abc')
type(1.23)
  • isinstance()
isinstance(123,int)
isinstance('abc',str)
八、常用操作符
(1)算术操作符
  • //:地板除
10 // 8     #output:1
3.0 // 2     #output:1.0
  • **:幂运算
3 ** 2     #output:9
(2)逻辑操作符
and  or  not
3 < 4 < 5     #(3 < 4) and (4 < 5)

九、操作符优先级
** :比左高,比右低
-3 ** 2     #-(3 ** 2)=-9
3 ** -2     #3 ** (-2)=0.111111111

十、if分支
  • if-elif分支
if ###:
     ###
elif ###:
     ###
else:
     ###
尽量用以上这种形式,如果第1个条件满足,下面的就不用再执行,别用下面的形式:
if ###:
     ###
if ###:
     ###
  • python可以避免“悬挂else”问题
在python和C语言中,下面的形式具有不同的意义。
if ###:
     if ###:
          ###
else:
     ###
  • 三元操作符
x,y = 4,5
small = x if x < y else y
  • 断言(assert)

十一、循环
  • while循环
while 条件:
     循环体
  • for循环
for 目标 in 表达式:
     循环体
例如:
for i in 'abcde':
    print(i,end=',')     #打印:a,b,c,d,e,

member = ['abc','456','哈哈']
for each in member:
    print(each , len(each))

打印结果:
abc 3
456 3
哈哈 2

for i in range(5):
    print(i)

打印结果:
0
1
2
3
4
#注意#range(n)只包含[0,n-1]
for i in range(1,10,2):
    print(i)

打印结果:
1
3
5
7
9
  • break语句
tmp=input('please input a str:')
while True:
    if tmp == 'abc':
        break
    tmp=input('error.input again:')

print('right.game over')
  • continue语句
for i in range(10):
    if i % 2 != 0:
        print(i)
        continue
    i += 2
    print(i)

一、一级标题





















0 0
原创粉丝点击