Python 入门一

环境

我是使用vs code作为本地的开发环境,关于如何setup可参考 Getting Started with Python in VS Code

关于多版本的问题,如果机器上有2.x版本又有3.x版本,可以通过pyenv 这个工具进行管理的,这个工具非常好的解决了版本切换的问题,关于如何安装与使用可以参考pyenv github库

安装Python可以是独立的Python版本,也可以是集成Anaconda, 如果使用Anaconda安装,它自带了许多包例如:Numpy,Pandas,matplotlib,还有后文提到的Jupyter 等,不需要再独立安装了

关于安装包的问题,国内下载Python第三方包比较慢,可以使用国内的镜像来提高速度

清华:https://pypi.tuna.tsinghua.edu.cn/simple

阿里云:http://mirrors.aliyun.com/pypi/simple/

中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/

豆瓣:http://pypi.douban.com/simple/

使用方法:
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple 库名

Jupyter 是一个学习Python很棒的工具,关于如何在VS Code里使用可参考Working with Jupyter Notebooks in Visual Studio Code

基础

数字 Numbers

由于Python是一种弱类型语言,所以在都需要生命变量类型,可以直接使用,例如

i=1
f=2.5

Python解释器会判处出i为整数类型,f为浮点类型,如果运行下面的代码

print(type(i))
print(type(f))

我们会得到
<class 'int'>
<class 'float'>

布尔类型

Pyton中的布尔类型是True 和 False, 布尔类型的计算可以使用and, or 和not

字符串 Strings

字符串可以使用单引号,双引号,如果是多行声名,可以使用三个单引号。例如

str1 = 'I am a string in single quotes'
str2 = "I am a string in double quotes"
str3 = '''I am a string with
multiple lines'''

就像.net的字符串一样,Python中的字符串也是不可变的(Immutable)

在开发程序的过程中,我们会经常用到字符串格式化,Python的格式化有下面几种方法

age = 20
name = 'Tom'
str_format1 = 'My name is '+name+', I am '+str(age)
str_format2 = 'My name is {0}, I am {1}'.format(name,age)
str_format3 = 'My name is {name}, I am {age}'.format(name=name,age=age)

Python 3.6引入了一种新的方式

str_format4 = f'My name is {name}, I am {age}'

Raw string

如果我们不需要Python替我们处理字符串中的任何字符,例如换行符\n, 我们可以再字符串的前面加个r

另外Python 3的字符串使用Unicode,直接支持多语言,默认我们应该使用utf-8的编码方式

代码块

如果你使用过<span>.net</span>,会知道每一代码行是通过";"分割的,代码块是用过”{}"表示的,然而在Python中代码块是通过缩进来表示的

i = 1
 print('This line will cause an error',i)#由于缩进问题,在运行是代码会报错
print('This line is good',i)

运算符及表达式

  • +(plus) 加 3 + 5 = 8. 'a' + 'b' = 'ab'.

  • -(minus) 减或负数

  • *(multiply) 相乘 2 * 3 = 6. 'la' * 3 = 'lalala'.

  • **(power) x的y次方
    3 ** 4 = 81 (i.e. 3 * 3 * 3 * 3)

  • / (divide) 除法
    13 / 3 = 4.333333333333333

  • // (divide and floor) 相除并取整,如果有float类型,那么结果也会是float
    13 // 3 = 4
    -13 // 3 = -5
    9//1.81 = 4.0

  • % (modulo) 取余数(remainder)
    13 % 3 gives 1. -25.5 % 2.25 gives 1.5.

  • << (left shift) 按位左移

    2 << 2 会得到 8. 相当于二进制0010左移两位变成1000 即8

  • <span>>></span> (right shift) 按位右移

    11 >> 1 得到 5. 1101右移一位变成0110 即5

  • & (bit-wise AND) 按位与

    Bit-wise AND of the numbers: if both bits are 1, the result is 1. Otherwise, it's 0.
    5 & 3 gives 1 (0101 & 0011 gives 0001)

  • | (bit-wise OR) 按位或

    Bitwise OR of the numbers: if both bits are 0, the result is 0. Otherwise, it's 1.
    5 | 3 gives 7 (0101 | 0011 gives 0111)

  • ^ (bit-wise XOR) 按位异或

    Bitwise XOR of the numbers: if both bits (1 or 0) are the same, the result is 0. Otherwise, it's 1.
    5 ^ 3 gives 6 (O101 ^ 0011 gives 0110)

  • ~ (bit-wise invert)

    The bit-wise inversion of x is -(x+1)
    ~5 gives -6. More details at http://stackoverflow.com/a/11810203

  • <span><</span> (less than)

    Returns whether x is less than y. All comparison operators return True or False. Note the capitalization of these names.
    5 < 3 gives False and 3 < 5 gives True.
    Comparisons can be chained arbitrarily: 3 < 5 < 7 gives True.

  • <span>></span> (greater than)

    Returns whether x is greater than y
    5 > 3 returns True. If both operands are numbers, they are first converted to a common type. Otherwise, it always returns False.

  • <span><=</span> (less than or equal to)

    Returns whether x is less than or equal to y
    x = 3; y = 6; x <= y returns True

  • <span>>=</span> (greater than or equal to)

    Returns whether x is greater than or equal to y
    x = 4; y = 3; x >= 3 returns True

  • == (equal to)

    Compares if the objects are equal
    x = 2; y = 2; x == y returns True
    x = 'str'; y = 'stR'; x == y returns False
    x = 'str'; y = 'str'; x == y returns True

  • != (not equal to)

    Compares if the objects are not equal
    x = 2; y = 3; x != y returns True

  • not (boolean NOT)

    If x is True, it returns False. If x is False, it returns True.
    x = True; not x returns False.

  • and (boolean AND)

    x and y returns False if x is False, else it returns evaluation of y
    x = False; y = True; x and y returns False since x is False. In this case, Python will not evaluate y since it knows that the left hand side of the 'and' expression is False which implies that the whole expression will be False irrespective of the other values. This is called short-circuit evaluation.

  • or (boolean OR)

    If x is True, it returns True, else it returns evaluation of y
    x = True; y = False; x or y returns True. Short-circuit evaluation applies here as well.

流程控制

下面的内容相对简单,有点编程经验的看下就明白

  • if

    条件控制语句 if

    str=input('enter a string:')
    if len(str)>5:
        print('the length of input string is greater than 5')
    elif len(str)>2:
        print('the length of input string is greater than 2 but less than 5')
    else:
        print('the length of input string is less than 2')
    
  • while

    running = True
    while running:
        str = input('Enter a strig:')
        if str=="quit":
           print('quit the loop')
           running=False
        else:
             print(f"You entered {str}, you can enter 'quit' to exit" )
    else:
        print('the while loop is ended')
        
    
  • for

    for i in range(1, 5):
        print(i)
    else:
        print('The for loop is over')
    

数据结构

Python内置的数据结构有List,Tuple,Dictionary,Set
List是一个有序项的数据集合,可以添加,删除数据项,List数据集使用中括号表示

namelist = ['Tom', 'Bob', 'Sam']
print('There are ',len(namelist),'items in the list')
print('Sort the name list')
namelist.sort()
print('Sorted name list is',namelist)
print('The first name in the list is',namelist[0])
namelist.append('Amy')
print('Added a new name to the list',namelist)

Tuple也是一种有序列表,和list类似,只不过tuple初始化后就不能再修改

#这段代码会报错,因为第二行试图去修改这个tuple集合
tuplelist=('Tom','Bob')
namelist[0]='Sam'

Dictionary字典类型,使用键-值(key-value)存储

name_email={
    'Tom':'tom@email.com',
    'Bob':'bob@email.com',
    'Sam':'sam@email.com'
}
print("Bob's email is",name_email['Bob'])
del name_email['Bob']
for name,email in name_email.items():
    print('name: {} email: {}'.format(name,email))
#add a new item
name_email['Amy']='amy@email.com'
if 'Amy' in name_email:
    print("Amy's email is ",name_email['Amy'])

Set是一种无序不重复集合

country=set(['china','japan','us'])
print('us' in country)#True
country.add('india')
country.remove('us')
print(country)#{'india','china','japan'}
x=set('three')
print(x)#{'h','r','t','e'}

函数

Python的函数定义非常简单,参数可以没有,也可以是固定参数,可变参数,关键字参数,参数的定义非常灵活, 我们用例子加以说明

def fun():
    return 'fun 1'
def power(x):
    return x*x
def power(x,n=2):
    return x**n
#可变参数
def calc(*numbers):
    sum=0
    for n in numbers:
        sum+=n
    return sum
#关键字参数,dictionary
def combine(**kw):
    for k,v in kw:
        prin("key:{} value:{}".format(k,v))

文章参考

https://python.swaroopch.com/

https://www.liaoxuefeng.com/wiki/1016959663602400/1017063826246112

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335