现在,我们知道了如何编写程序。接下来,就是干货了。
今天我们学什么呢?变量。
像这些,就是变量:
>>> str_ = "Python"
>>> int_ = 100
>>> float_ = 1.25
你可能发现了,我们把一个单词和两个数定义给了x。
这个单词,在Python这儿叫单词字符串。
这个100,在Python这儿叫自然数整数。
这个1.25,在Python这儿叫小数浮点数。
变量只能被这三种数据类型赋值。
这时可能有人说了:谢pro,变量也能这样啊:
>>> formula = 1 + 2
那你用print看看他是多少。
#Program_2
formula = 1 + 2 #将1 + 2的值赋值给变量formula
print(formula) #输出变量formula的值
"""
控制台:
3
"""
结果是3,对不对?
大家也发现了,我们能给变量赋值一个算式,它会自动计算,并将结果作为变量真正的值。
那算式如果有不同级运算怎么办?
优先运算等级高的运算呗。
1级运算:加(+)减(-)
2级运算:乘(*)除(/)
3级运算:乘方(**)
注意乘方在Python是**,不是^!
哦对了,Python变量命名也有规则!
1、变量名只能有数字、下划线和各语言的字符(这着实令我大吃一惊),建议用英语字母、数字和下划线作为变量名。
2、变量名的开头只能是下划线或各语言的字符,建议使用英语字母或下划线作为变量名的开头。
3、Python关键词和函数绝对不能作为变量名!!!!!实在想用它们的名字做变量名,请在后面加下划线作区分。
4、变量名尽量起得有意义,让懂英语的人一看就知道这个变量是干吗的。
5、如果变量首字母为字母,尽量使用小写字母(这样符合Python写作风格,也叫PEP 8)。
下面是Python所有的关键词和函数的方法:
>>> import keyword #导入keyword库
>>> print(keyword.kwlist) #输出Python所有关键词
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
>>> print("__builtin__")
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> print(__builtins__)
['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']
总之就是:看到变色的或后面带括号的,那就绝对不能当变量名。
最后,我再介绍几个函数和一个库,都对数学很有用。
int():将浮点数、数字字符串化成整数。欲转化对象放在括号里。例如:
>>> int1 = int("1") #将"1"强制转换为整数,将结果赋值给变量int1
>>> int2 = int(1.0) #将1.0强制转换为整数,将结果赋值给变量int2
>>> print(int1, int2) #输出变量int1和int2的值
1 1
float():将整数、数字字符串化成浮点数。欲转化对象放在括号里。例如:
>>> float1 = float("1.0") #将"1.0"强制转换为浮点数,将结果赋值给变量float1
>>> float2 = float(1) #将1强制转换为整数,将结果赋值给变量float2
>>> print(float1, float2)
1.0 1.0
round():使用Banker's Rounding(银行家舍入)概念(四舍六入五考虑,五后非空就进一,五后为空看奇偶,五前为偶应舍去,五前为奇要进一),第二个参数表示处理位数,省略则表示处理位数为十分位(1是十分位,以此类推)。例如:
>>> print(round(1.55)) #输出1.55用银行家舍入概念得到个位近似值的结果
2
>>> print(round(2.55)) #输出2.55用银行家舍入概念得到个位近似值的结果
3
>>> print(round(2.5555, 1)) #输出2.5555用银行家舍入概念得到十分位近似值的结果
2.6
>>> print(round(2.6555, 1)) #输出2.6555用银行家舍入概念得到十分位近似值的结果
2.7
abs():返回括号内数字的绝对值。例如:
>>> print(abs(10)) #输出10的绝对值
10
>>> print(abs(-10)) #输出-10的绝对值
10
pow():有两个参数,返回第一个参数的第二个参数次方。例如:
>>> print(pow(2, 3)) #输出2³的结果
8
>>> print(pow(4, 2)) #输出4²的结果
16
eval():计算字符串式子。例如:
>>> print(eval("3*5 - 2*5")) #输出3*5 - 2*5的值
5
complex():创造复数对象。前面的数是实数,后面的数是虚数。我们可以用real和imag获得复数的实数和虚数部分。
>>> complex_ = complex(1, 2) #将1+2j赋值给变量complex_
>>> print(complex_.real) #获得变量complex_的实数
1.0
>>> print(complex_.imag) #获得变量complex_的虚数
2.0
库叫math,使用前先得导入此库,方法为:
import math #导入math库
导入其他库,只需将math换成其他模块即可。
math模块涉及三角函数等高深的数学方法,各位自己去网上查怎么用吧(毕竟秋季开学我才读初一) 。
作业:用Python计算一个式子的结果
可使用math模块、四则运算、乘方和绝对值。
好了,我是谢pro,在评论区等你哦~