python (一)

系统自带文本编辑器IDLE,我使用的是Sublime Text,python文件执行步骤类似shell,首先cd到目录,之后分别执行执行chmod +x ./test.py./test.py

目录:

  • 输入和输出
  • 基本数据类型
  • list
  • tuple
  • dict
  • set
  • 条件判断
  • 循环

输入和输出

输出

用print()在括号中加上字符串,就可以向屏幕上输出指定的文字
示例:

print("hello world!")

print()函数也可以接受多个字符串,用逗号“,”隔开,就可以连成一串输出:
示例:

print("123", "456", "789")

输出:

123 456 789

print()会依次打印每个字符串,遇到逗号“,”会输出一个空格.
也可以打印整数
示例:

print(100)
print("1 + 2 = ", 3)
输入

Python提供了一个input(),可以让用户输入字符串,并存放到一个变量里.
示例:

name = input()
#name = input("please enter your name:")
print('hello,', name)

当你输入name = input()并按下回车后,Python交互式命令行就在等待你的输入了。这时,你可以输入任意字符,然后按回车后完成输入.

基本数据类型

整数、浮点数

整数、浮点数和其他语言中一样,不再阐述
示例:

age = 10
weight = 60.1
字符串

字符串在python是以单引号'或双引号"括起来的任意文本,比如'abc',"xyz"等等,
示例:

print('I\'m \"OK\"!')

\\表示转义

布尔值

布尔值和布尔代数的表示完全一致,一个布尔值只有TrueFalse两种值,注意代大小写,也可以通过布尔运算计算出来:
示例:

#!/usr/bin/env python3
print(True)
print(2>1)
print(3<2)

输出:

True
True
False

布尔值可以用and、or和not运算,and运算是与运算,or运算是或运算, not运算是非运算
示例:

print("True and True : ", True and True)
print("True and 3<2 : ", True and 3<2)
print("True or 3<2 : ", True or 3<2)
print("False or 3<2 : ", False or 3<2)
print("not True : ", not True)
print("not 3<2 : ", not 3<2)

输出:

True and True :  True
True and 3<2 :  False
True or 3<2 :  True
False or 3<2 :  False
not True :  False
not 3<2 :  True
数据类型转换
>>> int('123')
123
>>> int(12.34)
12
>>> float('12.34')
12.34
>>> str(1.23)
'1.23'
>>> str(100)
'100'
>>> bool(1)
True
>>> bool('')
False

变量

示例:

a = 10
b = "abc"
c = True
a = "hello world!"

多个变量赋值:

#a、b、b的值为1
a = b = c = 1
#1、2、john分别赋值给a、b、b
a, b, c = 1, 2, "john"

可以把任意数据类型赋值给变量,同一个变量可以反复赋值,而且可以是不同类型的变量。这种变量本身类型不固定的语言称之为动态语言,与之对应的是静态语言。静态语言在定义变量时必须指定变量类型,如果赋值的时候类型不匹配,就会报错。
您也可以使用del语句删除一些对象的引用:
del语句的语法是:

del var1[,var2[,var3[....,varN]]]]

示例:

var = '123'
print('前:', var)
del var
print('后:', var)

输出:

前: 123
Traceback (most recent call last):
  File "./test.py", line 7, in <module>
    print('后:', var)
NameError: name 'var' is not defined

提示变量var未定义
也可以删除多个变量:

del var_a, var_b
常量

所谓常量就是不能变的变量,比如常用的数学常数π就是一个常量。在Python中,通常用全部大写的变量名表示常量:
PI = 3.14159265359

但事实上PI仍然是一个变量,Python根本没有任何机制保证PI不会被改变,所以,用全部大写的变量名表示常量只是一个习惯上的用法.
Python中的除法、取整、取余:

print('结果:', 10 / 3)
print('取整:', 10 // 3)
print('取余:', 10 % 3)```
输出:

结果: 3.3333333333333335
取整: 3
取余: 1```
附:
字符串的一些其它操作:

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

#1、去除空格,strip()去除字符串的两边空格,rstrip()去除右边的空格,lstrip()去除左边的空格
str0 = '  123456789 '
print('str0 : ', str0.strip())

#2、字符串复制
str1 = '字符串1'
str2 = str1
str2 = '字符换2'
print('str1 = ', str1)
print('str2 = ', str2)

#3、字符串的连接
str3 = 'hello '
str4 = 'world'
print('str3 + str4 : ', str3 + str4)

#4、查找子字符串的索引
str5 = 'hello world'
str6 = 'llo'
#如果没找到,则报错:ValueError: substring not found
subIndex = str5.index(str6)
#和index方法类似,不同:找不到返回的是-1
subIndex2 = str5.find(str6)
print ('子字符串索引:', subIndex)

#5、比较
print('123 = 456 吗?:','123' == '456')
print('123 = 123 吗?:','123' == '123')

#6、字符串长度
print('字符串str5长度:', len(str5))

#7、字符串中的大小写转换
str7 = str8 = str9 = str10 = 'ABcdEf'
#大小写互换
print('大小写互换: ', str7.swapcase())
#首字母大写
print('首字母大写:', str8.capitalize())
#小写
print('小写:', str9.lower())
#大写
print('大写:', str10.upper())

#8、字符串前后颠倒
str12 = 'hello world'
print('字符串前后颠倒:', str12[::-1])

#9、字符串的分割
str13 = 'ab,cde,fgh,ijk'
print('字符串分割:', str13.split(','))

#10、字符串的连接
delimiter = ','
mylist = ['Brazil', 'Russia', 'India', 'China']
print('list -> 字符串:', delimiter.join(mylist))

#11、字符串的替换
str14 = 'hello world'
str15 = 'python'
print('字符串的替换:', str14.replace('world', str15))

#12、字符串的截取
str16 = 'hello world'
#截取前三位字符组成新的字符串,包括索引0,不包括索引3,结果:hel
print('截取前三位字符 :', str16[0:3])
print('截取字符串所有字符 :', str16[:])
print('截取第三个字符开始到结尾:', str16[3:])
print('截取从第0个字符开始到倒数第三个字符结束 :', str16[:-3])
print('截取第三个字符:', str16[2])
#0代表正数第一个字符,-1代表最后一个字符,-2代表倒数第二个字符,以此类推
print('截取倒数第一个个字符:', str16[-1])
print('截取倒数第三位到倒数第二位字符 :', str16[-3:-1])
print('截取倒数三位字符:', str16[-3:])

#13、子字符串出现的次数
str17 = 'hello world'
str18 = 'ell'
print('字符\'l\'出现的次数:', str17.count('l'))

#14、编码
print('编码:', '中文'.encode('utf-8'))

输出:

str0 :  123456789
str1 =  字符串1
str2 =  字符换2
str3 + str4 :  hello world
子字符串索引: 2
123 = 456 吗?: False
123 = 123 吗?: True
字符串str5长度: 11
大小写互换:  abCDeF
首字母大写: Abcdef
小写: abcdef
大写: ABCDEF
字符串前后颠倒: dlrow olleh
字符串分割: ['ab', 'cde', 'fgh', 'ijk']
list -> 字符串: Brazil,Russia,India,China
字符串的替换: hello python
截取前三位字符 : hel
截取字符串所有字符 : hello world
截取第三个字符开始到结尾: lo world
截取从第0个字符开始到倒数第三个字符结束 : hello wo
截取第三个字符: l
截取倒数第一个个字符: d
截取倒数第三位到倒数第二位字符 : rl
截取倒数三位字符: rld
字符'l'出现的次数: 3
编码: b'\xe4\xb8\xad\xe6\x96\x87'

list

Python内置的一种数据类型是列表:listlist是一种有序的集合,可以随时添加和删除其中的元素。
示例:

fruit = ['apple', 'banana', 'strawberry']
print(fruit)

输出:

['apple', 'banana', 'strawberry']

用len()函数可以获得list元素的个数:

len(fruit)

用索引来访问list中每一个位置的元素,记得索引是从0开始的:

print(fruit[0])
print(fruit[1])
print(fruit[2])

输出

apple
banana
strawberry
Traceback (most recent call last):
  File "./test.py", line 8, in <module>
    print(fruit[3])
IndexError: list index out of range

当索引超出了范围时,Python会报一个IndexError错误,所以,要确保索引不要越界,记得最后一个元素的索引是len(classmates) - 1
list常见操作总结:

#创建list
fruit = ['apple', 'banana', 'strawberry', 'apple', 'banana', 'strawberry']

#获取最后一个元素
fruit[-1]

#取前3个元素,如果第一个索引是0,可以省略
fruit[:3]

#后两个元素
fruit[-2:]

#前五个数,每两个取一个
fruit[:5:2]

#所有数,每5个取一个:
fruit[::5]

#[:]可以原样复制一个list
fruit[:]

#添加元素
fruit.append('tangerine')

#制定位置插入元素,如:第一个位置
fruit.insert(1, 'tomato')

#删除最后一个元素
fruit.pop()

#删除指定位置的元素
#fruit.pop(1)
del fruit[0]

#元素替换
fruit[1] = 'durian'

#数组的截取
subFruit = fruit[0:2]

#list的拼接
newFruit = fruit + subFruit

#判断元素是否在list中,下面代码输出True
print('durian' in newFruit)

#取得最大值
print(max(fruit))

#取得最小值
print(min(fruit))

#元素在数组中出现的次数
print(newFruit.count('durian'))

#列表中找出某个值第一个匹配项的索引位置
print(newFruit.index('durian'))

#移除列表中某个值的第一个匹配项
newFruit.remove('durian')

#反向列表中元素
newFruit.reverse()

# *号用于重复列表, 结果[12, 12, 12, 12]
ages = [12]*4

list里面的元素的数据类型也可以不同,比如:

L = ['Apple', 123, True]

tuple

另一种有序列表叫元组:tupletuplelist非常类似,但是tuple一旦初始化就不能修改,比如同样是列出水果:

fruit = ('apple', 'banana', 'strawberry')

现在,fruit这个tuple不能变了,它也没有append(),insert()这样的方法。其他获取元素的方法和list是一样的,你可以正常地使用classmates[0],classmates[-1],但不能赋值成另外的元素。
不可变的tuple有什么意义?因为tuple不可变,所以代码更安全。如果可能,能用tuple代替list就尽量用tuple
tuple的陷阱:当你定义一个tuple时,在定义的时候,tuple的元素就必须被确定下来,比如:

t = (1, 2)

如果要定义一个空的tuple,可以写成():

t = ()

但是,要定义一个只有1个元素的tuple,如果你这么定义:t = (1), 定义的不是tuple,是1这个数!这是因为括号()既可以表示tuple,又可以表示数学公式中的小括号,这就产生了歧义,因此,Python规定,这种情况下,按小括号进行计算,计算结果自然是1,所以,只有1个元素的tuple定义时必须加一个逗号,,来消除歧义:t = (1, )

dict

Python内置了字典:dict的支持,dict全称dictionary
示例:

d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}

dict的常见操作

#更新数据
d['Tracy'] = 100

#添加数据, key不存在,就创建
d['joy'] = '70'

#判断某个元素是否存在,可以通过key判断
print('joy' in d)

#删除元素
d.pop('joy')

set

setlist类似,只是在set中没有重复的元素,要创建一个set,需要提供一个list作为输入集合.
set常见操作:

x = set('abcdefg')
y = set(['d', 'i', 'm', 'i', 't', 'e'])
#输出{'f', 'd', 'g', 'c', 'b', 'e', 'a'}
print(x)
#输出:{'d', 'm', 'e', 'i', 't'}
print(y)

#x、y的交集,一下两种方式都可以
print(x & y)
#print(x.intersection(y))

#x、y的并集
print(x | y)
#print(x.union(y))

# x - y 差集,即从y中减去存在于x中的元素
print(y - x)
#print(y.difference(x))

#对称差:x和y的交集减去并集
print(y ^ x)
#print(x.symmetric_difference(y))

# 函数操作 ------------------------------
#x中元素个数
print(len(x))

#判断元素i是否在x中
print('i' in x)

s = set('adb')
#s是否是x的子集, True
print(s.issubset(x))

#s中增加x中的元素
s.update(x)

#添加元素
s.add(1)

#删除元素,如果没有这个元素,返回异常
s.remove(1) 

#如果存在元素,就删除;没有不报异常
s.discard(2)   

#清空元素
s.clear()

#随机删除一个元素,注意:和list不同,list删除删除最后一个元素,set没得元素是无序的,随机删除一个元素
x.pop() 

集合操作符号:


条件判断

if语句实现,
示例:

num = 20
if num >= 20:
    print('num 大于等于20')

注意不要少写了冒号:
增加else语句
示例:

num = 20
if num >=20:
    print('num 大于等于20')
else:
    print('num 小于20')

增加elif语句
示例:

num = 20
if num > 20:
    print('num 大于20')
elif num == 20:
    print('num 等于20')   
else:
    print('num 小于20')

if判断条件还可以简写,比如写:

num = 20
if num:
    print('default')

只要num非零(可以为负数)即为True,就会输出default
input()结合if示例:

birth = input('birth: ')
if birth < 2000:
    print('00前')
else:
    print('00后')

运行结果:

birth: 1999
Traceback (most recent call last):
  File "./test.py", line 5, in <module>
    if birth < 2000:
TypeError: '<' not supported between instances of 'str' and 'int'

这是因为input()返回的数据类型是strstr不能直接和整数比较,必须先把str转换成整数。Python提供了int()函数来完成这件事情:

s = input('birth: ')
birth = int(s)
if birth < 2000:
    print('00前')
else:
    print('00后')

循环

Python提供了for循环while循环(在Python中没有do..while循环).

while循环示例:
count = 0
while count < 4:
    print('count: ', count)
    count = count + 1

输出:

count:  0
count:  1
count:  2
count:  3
while … else

示例:

count = 0
while count < 4:
    print('count: ', count)
    count = count + 1
else:
    print('count已经等于4,退出循环')

输出:

count:  0
count:  1
count:  2
count:  3
count已经等于4,退出循环
for循环示例
for letter in 'Python':     # 第一个实例
   print ('当前字母 :',letter)
 
fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        # 第二个实例
   print ('当前水果 :', fruit)
 
print ("Good bye!")

输出:

当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : h
当前字母 : o
当前字母 : n
当前水果 : banana
当前水果 : apple
当前水果 : mango
Good bye!

另外一种执行循环的遍历方式是通过索引,如下实例:

fruits = ['banana', 'apple',  'mango']
for index in range(len(fruits)):
   print ('当前水果 :', fruits[index])
 
print ("Good bye!")

输出:

当前水果 : banana
当前水果 : apple
当前水果 : mango
Good bye!

dict的遍历:

d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
    print(key)

输出:

a
b
c

也可以同时输出keyvalue

d = {'a': 1, 'b': 2, 'c': 3}
for (key, value) in d.items():
    print(key, value)

字符串的遍历:

for ch in 'ABC':
     print(ch)

输出:

A
B
C

当我们使用for循环时,只要作用于一个可迭代对象,for循环就可以正常运行,而我们不太关心该对象究竟是list还是其他数据类型。那么,如何判断一个对象是可迭代对象呢?方法是通过collections模块的Iterable类型判断:

from collections import Iterable
print(isinstance('abc', Iterable)) # str是否可迭代
print(isinstance([1,2,3], Iterable)) # list是否可迭代
print(isinstance(123, Iterable)) # 整数是否可迭代

输出:

True
True
False

Python内置的enumerate函数可以把一个list变成索引-元素对,这样就可以在for循环中同时迭代索引和元素本身:

for i, value in enumerate(['A', 'B', 'C']):
        print(i, value)

输出:

0 A
1 B
2 C
continue、break

while语句时还有另外两个重要的命令 continue,break 来跳过循环,continue用于跳过该次循环,break 则是用于退出循环,此外"判断条件"还可以是个常值,表示循环必定成立
continue示例:

fruits = ['banana', 'apple',  'mango', 'durian']
for index in range(len(fruits)):
    if index == 2:
        continue    
    else:   
        print ('当前水果 :', fruits[index])
print ("Good bye!")

输出:

当前水果 : banana
当前水果 : mango
Good bye!

break示例:

fruits = ['banana', 'apple',  'mango', 'durian']
for index in range(len(fruits)):
    if index == 2:
        break   
    else:   
        print ('当前水果 :', fruits[index])
print ("Good bye!")

输出:

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

推荐阅读更多精彩内容

  • 一、python 变量和数据类型 1.整数 Python可以处理任意大小的整数,当然包括负整数,在Python程序...
    绩重KF阅读 1,509评论 0 1
  • 最近在慕课网学习廖雪峰老师的Python进阶课程,做笔记总结一下重点。 基本变量及其类型 变量 在Python中,...
    victorsungo阅读 1,595评论 0 5
  • http://python.jobbole.com/85231/ 关于专业技能写完项目接着写写一名3年工作经验的J...
    燕京博士阅读 7,484评论 1 118
  • 个人笔记,方便自己查阅使用 Py.LangSpec.Contents Refs Built-in Closure ...
    freenik阅读 67,641评论 0 5
  • 参考 problem solving with algorithms and data structures 细节...
    lifesmily阅读 1,855评论 0 1