大家好,从本文开始将逐渐更新Python教程指南系列,为什么叫指南呢?因为本系列是参考《Python3程序设计指南》,也是作者的学习笔记,希望与读者共同学习。
.py文件中的每个估计都是顺序执行的,从第一行开始,逐行执行的。
不需要预先的声明语句,也不需要指定数据类型
Python使用 “动态类型” 机制,也就是说,在任何时刻,只要需要,某个对象引用都可以重新引用一个不同的对象(可以是不同的数据类型)。
temp = 123
print(temp, type(temp))
temp = 'hello'
print(temp, type(temp))
output:
123 <class 'int'>
hello <class 'str'>
a = [1, 'abc']
b = [1, 'abc']
print(a is b)
a = (1, 'abc')
b = (1, 'abc')
print(a is b)
a = b
print(a is b)
output:
False
False
True
a = [1, 'abc']
b = [1, 'abc']
print(a is b)
a = (1, 'abc')
b = (1, 'abc')
print(a is b)
a = b
print(a is b)
output:
True
True
True
a = 9
print(0 <= a <= 10)
output:
True
in来测试成员关系,用not in来测试非成员关系。
# in运算符
a = (3, 45, 'hello', {'name': 'lisi'})
print(45 in a)
string = 'zhangsan|wanger'
print('|' in string)
output:
True
True
在Python中,一块代码,也就是说一条或者多条语句组成的序列,称为suit。
语法:
if boolean_expression1:
suite1
elif boolean_expression2:
suite2
else:
suite3
while语句用于0次或多次执行某个suite,循环执行的次数取决于while循环中布尔表达式的状态,其语法为:
while boolean_expression:
suite
for循环语句重用了关键字in,其语法为:
for variable in iterable:
suite
Python的很多函数与方法都会产生异常,并将其作为发生错误或重要事件的标志。其语法为:
try:
try_suite
except exception1 as variable1:
exception_suite1
...
except exceptionN as variableN:
excetpion_suiteN
其中as variable部分是可选的。
int数据类型是固定的,一旦赋值就不能改变
创建函数语法:
def functionName(arguments):
suite
为了熟悉以上关键要素,我们用一个实例来练习一下:
创建一个生成随机整数组成的网格程序,用户可以规定需要多少行、多少列,以及整数所在的区域。
import random
构建获取用户输入函数
该函数需要3个参数:msg为提示信息,minimum为最小值,default为默认值。该函数的返回值有两种情况:default(用户没有输入直接按Enter键),或者一个有效的整数。
def get_int(msg, minimum, default):
while True:
try:
line = input(msg)
# 如果输入值为空并且default不为None
if not line and default is not None:
return defalut
# 将输入转为整形
i = int(line)
# 如果输入值小于最小值,提示用户
if i < minimum:
print("must be >=", minimum)
else:
return i
# 异常处理
except ValueError as e:
print(e)
# 用户输入行数
rows = get_int('rows:', 1, None)
# 用户输入列数
columns = get_int('columns', 1, None)
# 用户输入最小值
minimum = get_int('minimum(or Enter for 0):', -10000, 0)
default = 1000
# 如果最小值大于default,default设置为最小值的2倍
if default < minimum:
default = 2 * minimum
# 用户输入最大值
maximum = get_int('maximum (or Enter for' + str(default) + ')', minimum, default)
row = 0
while row < rows:
line = ''
column = 0
while column < columns:
# 生成一个大于minimum,小于maximum的随机整数
i = random.randint(minimum, maximum)
s = str(i)
# 让每个数占10个字符,为了输出整齐
while len(s) < 10:
s = ' ' + s
line += s
column += 1
print(line)
row += 1
以下为输出信息:
rows:5
columns7
minimum(or Enter for 0):-1000
maximum (or Enter for1000)1000
-871 -205 426 820 986 369 238
-389 485 388 -907 243 346 -912
-885 528 50 -572 744 519 -128
785 -747 -565 -390 522 -357 933
-144 947 -949 -409 105 954 708
注:本文知识介绍Python的8个关键要素,但是并没有完全介绍,比如数据类型不只包括整形和字符串,后面的文章中还会详细介绍。
本文由博客一文多发平台 OpenWrite 发布!
原文:https://www.cnblogs.com/fatcat01/p/11688346.html