Python基本概念
- 2020 年 1 月 13 日
- 笔记
一 基本概念
1 字面意义上的常量,如2、‘This is ok'这样的字符串
>>> print('a,2,3')
a,2,3
2 字符串
- 单引号(‘) 使用单引号指示字符串,类似shell中的强引用,所有的空格、制表符照原样保留。
>>> print('This is ok')
This is ok
print 'I'd mouch you 'not'.' 也可以这样表示: print "I'd mouch you 'not'."
print 'I "said" do not touch this.'
备注:注意单引号和双引号的混合使用
- 双引号(“) 在双引号中的字符串与单引号中的字符串使用完全相同
>>> print("This is ok")
This is ok
- 三引号(''') 利用三引号,可以指示一个多行的字符串,可以在三引号中自由的使用单引号和双引号。
>>> '''This is am string.This is the first line.
… This is the second line.
… "What's your name?" Lasked.
… He said "Bond,JamesBond."'''
'This is am string.This is the first line.nThis is the second line.n"What's your name?" Lasked.nHe said "Bond,JamesBond."'
- 转义符
>>> 'what 's your name' #在单引号中实现单引号的使用
"what 's your name"
或使用双引号
>>> "what'your name"
"what'your name"
>>> "This is "ok"," #双引号中实现双引号的引用
'This is "ok",'
备注:行尾单独反斜杠,表示字符串在下一行继续,如:
>>> 'This is ok
… ,hello'
'This is ok,hello'
- 自然字符串 如果不需要转义符那样特别处理的字符串,那么可以给字符串加上前缀r或R来指定一个自然字符串
>>> r'New line are by n'
'New line are by \n'
3 对象:python在程序中把用到的任何东西都称为对象。
4 变量:
>>> i=100;print(i);
100
5 缩进:每个缩进层次使用2个或4个空格或单个制表符,使用其中的一种风格并且一值使用它。
二 表达式:Python大多数语句都包含表达式,如2+3,一个表达式可以分解为运算符和操作数。在上面的例子中,+为运算符,2和3为操作数。
示例:
>>> 2+3
5
>>> 3+3*2
9
三 控制流:
1 if语句
#!/bin/env python
number=23
guess=int(raw_input('Enter an integer: '))
if guess==number:
print 'Congratulations,you guessed it.'
print "(but you do not win any prizes!)"
elif guess<number:
print 'No,it is a little highers than that'
else:
print 'No,it is a little lower than that'
print 'Done'
2 for语句:
#!/bin/env python
for i in range(1,5):
print i
else:
print 'The for loop is over'
3 while语句
#!/bin/env python
number=23
running=True
while running:
guess=int(raw_input('Enter an integer:'))
if guess==number:
print 'Congratulations,you guessedit.'
running=False
elif guess<number:
print 'No,it is a little higher than that'
else:
print 'No,it is a little lower than that'
else:
print 'The while loop is over.'
print 'Done'
四 函数:函数是重复使用的程序段,并且可以在你的程序的任何地方使用,这被称为调用函数。在Python中有许多的内建函数,如len()。
函数通过def定义,示例如下:
#!/bin/env python
def abc():
print'This is abc'
abc()
五 关于编码:通常情况下,在Python程序中,不应有中文,如果要有的话,需要添加以下参数:
#!/bin/env python
#– coding:utf-8 —
#chickents:
print "I will now count my chickents:"
#计算数值:
print "Hens", 25 + 30 /6
print "Roosters", 100 – 25 * 3 % 4