python:小甲鱼

 

第1章

# 注释

 

>>> print("I Love 小霸王")
I Love 小霸王
>>> 
>>> 
>>> print(5 + 3)
8
>>> 5 + 3
8
>>> 123456789 + 987654321
1111111110
>>> 
>>> 
>>> print("养乐多" + "乐多")               #字符串拼接
养乐多乐多
>>> print("养乐多 " + "love " + "乐多")
养乐多 love 乐多
>>> 
>>> 
>>> print("I love 小霸王\n" * 3)           #字符串和数字做乘法,显示N个字符串
I love 小霸王
I love 小霸王
I love 小霸王

>>> print("I love 小霸王" + 3)
Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    print("I love 小霸王" + 3)
TypeError: can only concatenate str (not "int") to str
>>> 
 

 

 

 

 

第2章

 

"""--- 第一个小游戏 ---"""

temp = input("养乐多现在在干嘛呢?在想乐多吗?回答是(1)或不是(0):")
guess = int(temp)

if guess == 1:
    print("乐多也在想养乐多!")
else:
    print("养乐多居然不想乐多,生气!\n")

print("Game over! ^_^ ")

"""--- 第一个小游戏 ---"""

temp = input("养乐多现在在干嘛呢?在想乐多吗?回答是(1)或不是(0):")
guess = int(temp)

if guess == 1:
    print("乐多也在想养乐多!")
else:
    print("养乐多居然不想乐多,生气!\n")

print("Game over! ^_^ ")

 

 

>>> 
======================= RESTART: G:/python/小甲鱼/p2_1.py =======================
养乐多现在在干嘛呢?在想乐多吗?回答是(1)或不是(0):1
乐多也在想养乐多!
Game over! ^_^ 
>>> 
>>> 
======================= RESTART: G:/python/小甲鱼/p2_1.py =======================
养乐多现在在干嘛呢?在想乐多吗?回答是(1)或不是(0):0
养乐多居然不想乐多,生气!

Game over! ^_^ 
>>> 

 

 

 

 

 

ctrl+N  新建

F5进行   (Run -> Run Module)

 

要注意缩进:输入冒号(:)

 

BIF:Built-in Functions,内置函数

python的变量是不需要事先声明的,直接给一个合法的名字赋值,这个变量就生成了。

 

>>> dir(__builtins__)     #Python提供的内置函数列表
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
>>> 
>>> help(print)     #help()这个BIF用于显示BIF的功能描述
Help on built-in function print in module builtins:

print(...)
    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
    
    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

>>> 

 

第3章

3.1 变量

 

>>> 
>>> myname = "乐多"
>>> yourname = "养乐多"
>>> ourname = myname + yourname
>>> print(ourname)
乐多养乐多
>>> 

 

3.2 字符串

 

>>> 
>>> 5 + 8
13
>>> 
>>> '5' + '8'
'58'
>>> 
>>> 
>>> "Let's go"
"Let's go"
>>> 
>>> 'Let's go'
SyntaxError: invalid syntax
>>> 
>>> 'Let\'s go'
"Let's go"
>>> 

 

3.3 原始字符串

 

>>> 
>>> str = '安安\now'
>>> str
'安安\now'
>>> print(str)
安安
ow
>>> 
>>> 
>>> str = '安安\\now'   #加转义字符
>>> str
'安安\\now'
>>> print(str)
安安\now
>>> 
>>> 
>>> 
>>> str = r'安安\now'   #使用原始字符串, 在字符串前边加一个英文字母r
>>> str
'安安\\now'
>>> print(str)
安安\now
>>> 
>>> 

 


>>> 
>>> str = '安安\now\'
SyntaxError: EOL while scanning string literal
>>> str = '安安\now\\'
>>> str
'安安\now\\'
>>> print(str)
安安
ow\
>>> str = r'安安\now\'
SyntaxError: EOL while scanning string literal
>>> 

 

3.4 长字符串

问题:像这种长字符串,一直用\n太麻烦了
      
>>> print("""
今天是来所的第二天

早上在冠寓那边买了早餐
买了一个火腿鸡蛋饼和一杯豆浆
但是豆浆没有吸管
自己一下子也喝不完
所以就端了一路
下次不买了

还发生了一个超级有趣的事情
我上车坐到了一个位置上
我发现那个位置前面那个靠背上勾着一个耳机
拿起来一看
天哪
竟然是我的耳机
惊不惊喜
意不意外
我找到我的耳机了

翔哥今天上午给设置好了有线
网速比我自己的热点快多了
自己也意外地找到了师兄接显示器的线
自己还倒腾了一下
成功连接显示器
虽然自己好像也用不到
但是接上了就是很开心

希望今天可以喝8杯水
希望今天身体可以好一点
希望自己的病快好起来吧
天天生病的自己
自己看着都难受
这还是我吗

想我的养乐多
爱你
""")
      

今天是来所的第二天

早上在冠寓那边买了早餐
买了一个火腿鸡蛋饼和一杯豆浆
但是豆浆没有吸管
自己一下子也喝不完
所以就端了一路
下次不买了

还发生了一个超级有趣的事情
我上车坐到了一个位置上
我发现那个位置前面那个靠背上勾着一个耳机
拿起来一看
天哪
竟然是我的耳机
惊不惊喜
意不意外
我找到我的耳机了

翔哥今天上午给设置好了有线
网速比我自己的热点快多了
自己也意外地找到了师兄接显示器的线
自己还倒腾了一下
成功连接显示器
虽然自己好像也用不到
但是接上了就是很开心

希望今天可以喝8杯水
希望今天身体可以好一点
希望自己的病快好起来吧
天天生病的自己
自己看着都难受
这还是我吗

想我的养乐多
爱你

>>> 

3.9 数据类型

Python的变量是没有类型的

带了引号的,无论是双引号还是单引号还是三引号,都是字符串

不带引号的,就是数字

 

Python的数值类型包含整型、浮点型、布尔类型、复数类型

 

3.9.4 类型转换

我们人类思维是习惯于“四舍五入”法,你有什么办法使得 int() 按照“四舍五入”的方式取整吗?

int() 固然没那么“聪明”,但机器是死的,鱼油是活的!
5.4 “四舍五入”结果为:5,int(5.4+0.5) == 5
5.6 “四舍五入”结果为:6,int(5.6+0.5) == 6

大家看明白了吗?


      
>>> a = '520'      
>>> b = int(a)     
>>> a, b      
('520', 520)
>>> 
      
      
>>> a = 5.99      
>>> b = int(a)      
>>> a, b      
(5.99, 5)
>>> 
      
>>> 
      
>>> a = '520'      
>>> b = float(a)     
>>> a, b      
('520', 520.0)
>>> 
      
     
>>> a = 520      
>>> b = float(b)      
>>> a, b      
(520, 520.0)
>>> 
      
>>> a = 5.99      
>>> b = str(a)      
Traceback (most recent call last):
  File "<pyshell#147>", line 1, in <module>
    b = str(a)
TypeError: 'str' object is not callable
>>> b     
520.0
>>> 
      

      
>>> c = str(5e15)      
Traceback (most recent call last):
  File "<pyshell#151>", line 1, in <module>
    c = str(5e15)
TypeError: 'str' object is not callable
>>> c      
Traceback (most recent call last):
  File "<pyshell#152>", line 1, in <module>
    c
NameError: name 'c' is not defined
>>> 

 

random模块

我们编写的程序实际上就是一个模块

random module里边有一个函数叫做randint(),它会返回一个随机的整数

利用:secret = random.randint(1, 10)

 

 

3.9.5 变量类型

>>> 
      
>>> type(520)
      
<class 'int'>
>>> type('520')
      
<class 'str'>
>>> type(520.0)
      
<class 'float'>
>>> 
    

可以使用isinstance()这个BIF来确定变量的类型 
>>> isinstance(520, int)
      
True
>>> isinstance(520.0, int)
      
False
>>> 

 

第4章

 

 

if 100 >= score >= 90:
    print('A')
elif 90 >= score >= 80:
    print('B')
else:
    print('输入错误')

 

 

 

三元操作符:

a = x if 条件 else y

 

 

断言(assert),关键字,当这个关键字后边的条件为假的时候,程序自动崩溃并抛出AssertionError的异常。

测试程序时可以用

>>> assert 3>4
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    assert 3>4
AssertionError
>>> assert 4>3
>>> 

 

range()内建函数:生成一个从start参数的值开始,到stop参数的值结束的数字序列

range(5):第一个参数默认为0,生成0~5的所有数字(包括0但是不包括5)

range(2, 9):步长为1

range(2, 9, 2)

for i in range(10):
    if i%2 != 0:
        print(i)
        continue
    i += 2
    print(i)
======================= RESTART: G:/python/小甲鱼/p4_5.py =======================
2
1
4
3
6
5
8
7
10
9
>>> 

第5章 列表、元祖和字符串

5.1 列表

python的变量没有数据类型,python没有数组

如果把数组比作是一个集装箱的话,python的列表就是一个工厂的仓库了

 

5.1.1 创建列表

创建列表和创建普通变量一样,用中括号扩起一堆数据就可以了,数据之间用逗号隔开。

>>> number = [1, 2, 3, 4, 5]
>>> mix = [1, '小甲鱼', 3.14, [1, 2, 3]]
>>> empty = []

 

5.1.2 向列表添加元素

1)用append()方法

>>> number.append(6)
>>> number
[1, 2, 3, 4, 5, 6]
>>> nummber.append(7, 8)
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    nummber.append(7, 8)
NameError: name 'nummber' is not defined

number.append(6)

append()不是一个BIF,它是属于列表对象的一个方法

中间那个".",可以暂时可以理解为范围的意思:append()这个方法是属于一个叫作number的列表对象的

 

2)用extend()方法向列表末尾添加多个元素

extend()使用一个列表来扩展另一个列表,参数应该是一个列表

>>> number.extend(7, 8)
Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    number.extend(7, 8)
TypeError: extend() takes exactly one argument (2 given)
>>> number.extend([7, 8])
>>> number
[1, 2, 3, 4, 5, 6, 7, 8]

3)用insert()方法往列表的任意位置添加数据

两个参数,第一个参数代表在列表中的位置,第二个参数是在这个位置处插入一个元素

凡是顺序索引,python均从0开始

>>> number.insert(0, 0)
>>> number
[0, 1, 2, 3, 4, 5, 6, 7, 8]

 

5.1.3 从列表中获取元素

>>> number[3]
3
>>> number[5]
5
>>> number[3], number[5] = number[5], number[3]      #列表中的两个元素位置互调
>>> number
[0, 1, 2, 5, 4, 3, 6, 7, 8]

5.1.4 从列表删除元素

1)remove()

不需要知道元素在列表中的具体位置,只需要知道该元素存在列表中就可以了

>>> number.remove(8)     #8是元素
>>> number
[0, 1, 2, 5, 4, 3, 6, 7]

 

2)del   del是一个语句,不是一个列表的方法,所以不必在del后面加上小括号

可以删除某个位置的元素

>>> del number[2]         #2是位置
>>> number
[0, 1, 5, 4, 3, 6, 7]

可以删除整个列表 del加列表名
>>> del number
>>> number
Traceback (most recent call last):
  File "<pyshell#30>", line 1, in <module>
    number
NameError: name 'number' is not defined
>>> 

3)pop()方法

默认弹出列表中的最后一个元素

>>> number = [1, 2, 3, 4, 5]
>>> number.pop()
5
>>> number.pop()
4
>>> number
[1, 2, 3]

以索引值作为参数的时候,弹出这个索引值对应的元素

>>> number.pop(2)     #2是位置
3
>>> number
[1, 2]

 

5.1.5 列表分片

一次性获取列表中的多个元素

用冒号隔开两个索引值,左边是开始位置,右边是结束位置。结束位置上的元素是不包含的。

使用列表分片,得到一个原来列表中的拷贝,原来列表并没有发生改变。

>>> num = [0, 1, 2, 3, 4, 5, 6]
>>> num[0:2]
[0, 1]
>>> num[:2]
[0, 1]
>>> num[1:]
[1, 2, 3, 4, 5, 6]
>>> num[:]
[0, 1, 2, 3, 4, 5, 6]

5.1.6 列表分片的进阶玩法

加入了步长

>>> num = [0, 1, 2, 3, 4, 5, 6]
>>> num[0:5:2]
[0, 2, 4]
>>> num[::2]
[0, 2, 4, 6]

>>> num[::-1]          #步长设置成-1,相当于复制一个反转的列表
[6, 5, 4, 3, 2, 1, 0]
>>> 

5.1.7 一些常用操作符

1)比较

>>> num1 = [123]
>>> num2 = [456]
>>> num1 >num2
False
>>> num1 < num2
True
 


>>> str1 = 'abc'
>>> str2 = 'cde'
>>> str1 > str2
False
>>> str1 < str2
True
 

2)加号(+)进行拼接

>>> num1 = [123, 456]
>>> num2 = [789, 987]
>>> num3 = num1 + num2
>>> num3
[123, 456, 789, 987]

 

3)乘号(*)重复操作符

>>> num = [123]
>>> num *3
[123, 123, 123]
>>> 

 

4)复合赋值运算符

>>> num = [123]
>>> num * 3
[123, 123, 123]
>>> num *= 5
>>> num
[123, 123, 123, 123, 123]     #说明上一操作结束之后,num本身并没有变化

5)成员关系操作符in     not in

>>> num = [1, 2, 3, 4, 5]
>>> 5 in num
True
>>> 6 in num
False
>>> 6 not in num
True

>>> num = [1, 2, 3, 4, [5, 6]]     #列表里面包含另一个列表,进行测试
>>> 5 in num
False
>>> [5, 6] in num
True
 

6)对于列表中的列表的元素,如何访问?  跟C语言访问二维数组的方法相似

>>> num = [1, 2, 3, 4, [5, 6]]
>>> num[1]
2
>>> num[4]
[5, 6]
>>> num[4][1]
6

5.1.8 列表中的小伙伴们

>>> dir(list)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> 

 

1)count() :计算它的参数在列表中出现的次数

>>> num = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2]
>>> num.count(1)
3
>>> num.count(3)
2

 

 

2)index():返回它的参数在列表中的位置

>>> num.index(1)
0                #第一次出现的位置
>>> start = num.index(1)+1
>>> end = len(num)
>>> num.index(1, start, end)

5             #第二次出现的位置

 

 

3)reverse():将整个列表原地翻转

>>> num
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2]
>>> num.reverse()
>>> num
[2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1]

 

 

 

 

4)sort():用指定的方式对列表的成员进行排序,默认不需要参数,从小到大排队

>>> num
[2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1]
>>> num.sort()
>>> num
[1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5]

 

 

从大到小排序

方法1

>>> num
[2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1]
>>> num.sort()
>>> num
[1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5]
>>> num.reverse()
>>> num
[5, 5, 4, 4, 3, 3, 2, 2, 2, 1, 1, 1]

 

方法2

>>> num = [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2]
>>> num.sort(reverse = True)
>>> num
[5, 5, 4, 4, 3, 3, 2, 2, 2, 1, 1, 1]

 

 

5.1.9 关于分片“拷贝”概念的补充

Python的变量就像一个标签,就一个名字而已

为一个列表指令另一个名字的做法,只是向同一个列表增加一个新的标签而已,真正的拷贝是要使用分片的方法。

>>> num1 = [1, 9, 3, 7, 2, 1]
>>> num2 = num1[:]
>>> num2
[1, 9, 3, 7, 2, 1]
>>> num3 = num1
>>> num3
[1, 9, 3, 7, 2, 1]
>>> 
>>> 
>>> num1.sort()
>>> num1
[1, 1, 2, 3, 7, 9]
>>> num2
[1, 9, 3, 7, 2, 1]
>>> num3
[1, 1, 2, 3, 7, 9]

 

5.2 元组

元组和列表的区别:可以任意修改列表中的元素,可以任意插入或者删除一个元素,但对元组是不行的,元组是不可改变的(像字符串一样),所以也不可以对元组进行排序

创建列表用中括号,创建元组大部分用小括号

 

5.2.1 创建和访问一个元组

>>> tmp = 1
>>> type(tmp)
<class 'int'>
>>> 

>>> tmp = (1)
>>> type(tmp)
<class 'int'>
>>> 
>>> 
>>> tmp = 1, 2, 3      元组类型逗号才是关键,小括号只是起到补充的作用
>>> type(tmp)
<class 'tuple'>
>>> 
>>> tmp = ()     创建一个空元祖
>>> type(tmp)
<class 'tuple'>
>>> tmp
()
>>> 
>>> 
>>> tmp1 = (1)
>>> type(tmp1)
<class 'int'>
>>> tmp2 = (1, )     
>>> type(tmp2)
<class 'tuple'>
>>> tmp3 = 1,    
>>> type(tmp3)
<class 'tuple'>
>>> 
>>> 

如果要创建的元组中只有一个元素,在它后边加一个逗号,这样可以明确告诉python要的是一个元素,而不是一个什么整型、浮点型
>>> 8 * (8)
64
>>> 8 * (8, )
(8, 8, 8, 8, 8, 8, 8, 8)
>>> 

5.2.2 更新和删除元组

更新

>>> tmp = (1, 2, 3, 4, 5)
>>> tmp = tmp[:2] + ("安安") + tmp[2:]
Traceback (most recent call last):
  File "<pyshell#236>", line 1, in <module>
    tmp = tmp[:2] + ("安安") + tmp[2:]
TypeError: can only concatenate tuple (not "str") to tuple
>>> 
>>> tmp = (1, 2, 3, 4, 5)
>>> tmp = tmp[:2] + ("安安",) + tmp[2:]     #逗号是必需的,小括号是必需的
>>> tmp
(1, 2, '安安', 3, 4, 5)
>>> 
>>> 

 

删除元素
>>> tmp = tmp[:4] + tmp[5:]
>>> tmp
(1, 2, '安安', 3, 5)
>>>

 

 删除整个元组

>>> del tmp
>>> tmp
Traceback (most recent call last):
  File "<pyshell#249>", line 1, in <module>
    tmp
NameError: name 'tmp' is not defined
 

元组中的操作符:拼接 重复 关系 逻辑 成员

 

 

 

形参:parameter

实参:argument

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安安csdn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值