[雪峰磁针石博客]python3快速入门教程2数据结构1变量与赋值

语法基础

解释器像简单的计算器:可以输入表达式,它会返回值。表达式语法很简单:运算符 + , - , * 和 / 与其它语言一样(例如Pascal或C);括号用于分组。例如:

>>> 2 + 2
4
>>> 50 - 5*6
20
>>> (50 - 5.0*6) / 4
5.0
>>> 8 / 5.0
1.6

整数(例如2、4、20 )的类型是 int,带有小数部分的数字(例如5.0、1.6)的类型是 float。

除法(/)永远返回浮点数。地板除使用 // 运算符;要计算余数你可以使用 %。

>>> 17 / 3  # classic division returns a float
5.666666666666667
>>>
>>> 17 // 3  # floor division discards the fractional part
5
>>> 17 % 3  # the % operator returns the remainder of the division
2
>>> 5 * 3 + 2  # result * divisor + remainder
17

"**"表示乘方:

>>> 5 ** 2  # 5 squared
25
>>> 2 ** 7  # 2 to the power of 7
128

在Python中,名称( 标识符)只能由字母、数字和下划线(_)构成,且不能以数字打头。因此 Plan9 是合法的变量名,而 9Plan 不是。在某种程度上说,标识符命名规则基于Unicode标准,详情请参阅“Python语言参考手册”(https://docs.python.org/3/reference/lexical_analysis.html)。也就是说中文变量名也是可以的。

>>> 你好 = '你好'
>>> print(你好)
你好

等号( '=' )用于给变量赋值:

>>> width = 20
>>> height = 5*9
>>> width * height900

同一值可以同时赋给几个变量:

>>> x = y = z = 0  # Zero x, y and z
>>> x
0
>>> y
0
>>> z
0

变量在使用前必须"定义"(赋值),否则会出错:

>>> n
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined

支持浮点数,混合计算时会自动整型转为浮点数:

>>> 4 * 3.75 - 1
14.0

交互模式中,最近表达式的值赋给变量 _ 。更方便连续计算把Python当作桌面计算器,例如:

>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
12.5625
>>> price + _
113.0625
>>> round(_, 2)
113.06

此变量对于用户是只读的。

除了int和float,还有fractions(https://docs.python.org/2/library/fractions.html#fractions.Fraction)和decimal(https://docs.python.org/2/library/decimal.html#decimal.Decimal)。

下面的复数部分很少使用,通常可以不阅读。

支持复数,虚数带有后缀j或J,有非零实部的复数写为(real+imagj),或者用complex(real, imag)函数创建。

>>> 1j * 1J
(-1+0j)
>>> 1j * complex(0,1)
(-1+0j)
>>> 3+1j*3
(3+3j)
>>> (3+1j)*3
(9+3j)
>>> (1+2j)/(1+1j)
(1.5+0.5j)

复数的实部和虚部总是记为两个浮点数。要从复数z中提取实部和虚部,使用z.real和 z.imag。

>>> a=1.5+0.5j
>>> a.real
1.5
>>> a.imag
0.5

浮点数和整数转换函数(float(), int()和long())不适用于复数。没有方法把复数转成实数。函数abs(z)用于取模(为浮点数)或z.real取实部:

>>> a=3.0+4.0j
>>> float(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float
>>> a.real
3.0
>>> a.imag
4.0
>>> abs(a)  # sqrt(a.real**2 + a.imag**2)
5.0

变量与赋值

自己实现求最大值。

代码:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author:    xurongzhong#126.com wechat:pythontesting qq:37391319
# 技术支持 钉钉群:21745728(可以加钉钉pythontesting邀请加入) 
# qq群:144081101 591302926  567351477
# CreateDate: 2018-6-12 
# mymax2.py
# Write max function without built-in max().

def mymax2(x, y):
    """Return larger of x and y."""
    largest_so_far = x
    if y > largest_so_far:
        largest_so_far = y
    return largest_so_far

def main():
    print("MyMax: Enter two values to find the larger.")
    first = float(input("First value: "))
    second = float(input("Second value: "))
    print("The larger value is", mymax2(first, second))

main()

执行:

$ python3 mymax2.py 
MyMax: Enter two values to find the larger.
First value: 3
Second value: 89
The larger value is 89.0

注意赋值是=,判断是否等于是==。

实际上python的内置函数max已经很好的实现了这个功能。数值相关的内置函数如下:

方法 | 功能 | --- | --- | abs(x) | 绝对值。 max(x, y) | 最大值 min(x, y)| 最小值 pow(x, y) | x的次方

参考资料: [雪峰磁针石博客]python3标准库-中文版2:内置函数

输入输出的内置函数

方法 | 功能 | --- | --- | input(prompt) | 打印可选prompt并将用户输入的值作为字符串返回。 print(value1, value2, ...) | 打印value1, value2等,以空格分隔。

python的基础数据类型有bool、float、int、str

类型 | 描述 | --- | --- | bool | True或False float | 带小数点浮点数值,如3.141,-23.8,7.0或5.92e7 = 5.92×10 7 int | 如847,-19或7 str | 单,双或三引号内的字符串。如“abc”,“它在这里!”或文档字符串等

这四种类型同时还有可以进行类型转换的内置函数。

  • 学英文、练python题目:

计算机等级考试python二级 浙江高考 全国中学生奥赛模拟题

Write a function grade(score) to return the corresponding letter grade for a given numerical score. That is, for 90 or above, return the string "A" , for 80 or above, return "B", etc. Include a main() to test your function.

计算

计算投资收益

代码:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author:    xurongzhong#126.com wechat:pythontesting qq:37391319
# 技术支持 钉钉群:21745728(可以加钉钉pythontesting邀请加入) 
# qq群:144081101 591302926  567351477
# CreateDate: 2018-6-12 
# balance_table.py
# Print table of account balances earning interest.

def balance(p, r, t):
    """Return new balance using compound annual interest."""
    return p*(1 + r)**t

def main():
    print("Calculates compound interest over time.")
    principal = float(input("Principal: "))
    rate = float(input("Interest rate (as a decimal): "))
    years = int(input("Number of years: "))
    for year in range(years + 1):
        print(year, balance(principal, rate, year))

main()

执行:

$ python3 balance_table.py 
Calculates compound interest over time.
Principal: 1000
Interest rate (as a decimal): 0.055
Number of years: 5
0 1000.0
1 1055.0
2 1113.0249999999999
3 1174.2413749999998
4 1238.8246506249998
5 1306.9600064093747
In [1]: 17/5 # 除
Out[1]: 3.4

In [2]: 17//5 #整除
Out[2]: 3

优先级 | 运算符 | --- | --- | 高 | * 中 | , /, //, % 低 | +, -

math模块还有一些增强:

函数 | 功能 | --- | --- | sqrt(x) | x的平方根 floor(x) | 地板:小于或等于x的最大整数 ceil(x) | 天花板:大于或等于x最小的整数 log(x) | 自然对数 exp(x) | 指数 pi | 指数

符合运算符

优先级 | 运算符 | --- | --- | += | x = x + y

类似的有-=、*=、/=、//=、 %=

>>> a = 10
>>> a -= 1
>>> a
9
>>> a  += 2 * 3 - 1
>>> a
14
>>> a //=2
>>> a
7
>>> a %=2
>>> a
1

内置函数bin、hex、int可用于进制转换,请在[雪峰磁针石博客]python3标准库-中文版2:内置函数学习。后面的习题会覆盖这3个函数。

习题

1.python3.6+中下面哪个对于int内置函数的使用不合法

A. int('16',base=10) B. int('1.6') C. int(1.6) D. int('16_6',base=10)

  1. hex(25)、 int("0x1C", 16)、int("0b10101", 2)、int("0x1C", 16)的返回值各是多少?

参考资料

links