a = input('please input your name:') # 要求使用者通过键盘输入内容
please input your name:ruoning
a
'ruoning'
print(a) # 将a显示出来
ruoning
print(a,1,2)
ruoning 1 2
print('hello world')
hello world
变量命名规则:
2x = 1 # 不能以数字开头
Input In [7] 2x = 1 # 不能以数字开头 ^ SyntaxError: invalid syntax
my name = 'ruoning' # 变量名中间不能含空格
Input In [9] my name = 'ruoning' # 变量名中间不能含空格 ^ SyntaxError: invalid syntax
Python内部有很多关键字,比如
type
:查看数据类型help
:寻求帮助len
:求数据长度type(1)
int
#help(type)
len(a)
7
常用的起名的方式
myName = 'ruoning' # 驼峰式
myFirstName = 'ruoning' # 驼峰式
my_name = 'ruonig'
#
表示单行注释,#
后面的一行内容不被当做代码运行'''
括起来的内容表示多行注释,其内部的内容不会当作代码运行# 下面是一行代码
x = 2
下面是一行代码
x = 2
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Input In [19], in <cell line: 1>() ----> 1 下面是一行代码 2 x = 2 NameError: name '下面是一行代码' is not defined
'''
多行注释
多行注释
'''
'\n多行注释\n多行注释\n'
可以将Python当作一个高级的计算器,它可以运算加减乘除、开方、绝对值、三角函数、指数对数等数学运算;它还可以进行逻辑运算、比较运算等运算。
type(20)
int
type(20.0)
float
type(True)
bool
type(False)
bool
2 + 3
5
2 -3
-1
2*3
6
2 / 3
0.6666666666666666
15%4 # 取15除以4的余数
3
15//4 # 取15除以4的整数部分
3
2**5 # 2的5次方
32
2**(1/2)
1.4142135623730951
2**0.5
1.4142135623730951
import math # 引入math库
math.log(20)
2.995732273553991
math.log10(100)
2.0
math.log(5,7)
0.8270874753469162
math.sin(math.pi)
1.2246467991473532e-16
math.pi
3.141592653589793
import matplotlib.pyplot as plt # 引入绘图库
import numpy as np # 引入函数库
x = np.linspace(0,2*math.pi,100)
y = np.sin(x)
plt.plot(x,y)
plt.scatter([math.pi],[0],marker='*',color='red',s=100)
<matplotlib.collections.PathCollection at 0x15a08745e20>
math.radians(30) #把30°角度转换为弧度
0.5235987755982988
math.degrees(math.pi) # 将弧度转换为角度
180.0
math.sin(math.radians(30))
0.49999999999999994
def linear(x):
return 2*x+3
linear(20)
43
def area(a,b):
return a*b/2
area(3,4)
6.0
help(math)
Help on built-in module math: NAME math DESCRIPTION This module provides access to the mathematical functions defined by the C standard. FUNCTIONS acos(x, /) Return the arc cosine (measured in radians) of x. The result is between 0 and pi. acosh(x, /) Return the inverse hyperbolic cosine of x. asin(x, /) Return the arc sine (measured in radians) of x. The result is between -pi/2 and pi/2. asinh(x, /) Return the inverse hyperbolic sine of x. atan(x, /) Return the arc tangent (measured in radians) of x. The result is between -pi/2 and pi/2. atan2(y, x, /) Return the arc tangent (measured in radians) of y/x. Unlike atan(y/x), the signs of both x and y are considered. atanh(x, /) Return the inverse hyperbolic tangent of x. ceil(x, /) Return the ceiling of x as an Integral. This is the smallest integer >= x. comb(n, k, /) Number of ways to choose k items from n items without repetition and without order. Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates to zero when k > n. Also called the binomial coefficient because it is equivalent to the coefficient of k-th term in polynomial expansion of the expression (1 + x)**n. Raises TypeError if either of the arguments are not integers. Raises ValueError if either of the arguments are negative. copysign(x, y, /) Return a float with the magnitude (absolute value) of x but the sign of y. On platforms that support signed zeros, copysign(1.0, -0.0) returns -1.0. cos(x, /) Return the cosine of x (measured in radians). cosh(x, /) Return the hyperbolic cosine of x. degrees(x, /) Convert angle x from radians to degrees. dist(p, q, /) Return the Euclidean distance between two points p and q. The points should be specified as sequences (or iterables) of coordinates. Both inputs must have the same dimension. Roughly equivalent to: sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q))) erf(x, /) Error function at x. erfc(x, /) Complementary error function at x. exp(x, /) Return e raised to the power of x. expm1(x, /) Return exp(x)-1. This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x. fabs(x, /) Return the absolute value of the float x. factorial(x, /) Find x!. Raise a ValueError if x is negative or non-integral. floor(x, /) Return the floor of x as an Integral. This is the largest integer <= x. fmod(x, y, /) Return fmod(x, y), according to platform C. x % y may differ. frexp(x, /) Return the mantissa and exponent of x, as pair (m, e). m is a float and e is an int, such that x = m * 2.**e. If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0. fsum(seq, /) Return an accurate floating point sum of values in the iterable seq. Assumes IEEE-754 floating point arithmetic. gamma(x, /) Gamma function at x. gcd(*integers) Greatest Common Divisor. hypot(...) hypot(*coordinates) -> value Multidimensional Euclidean distance from the origin to a point. Roughly equivalent to: sqrt(sum(x**2 for x in coordinates)) For a two dimensional point (x, y), gives the hypotenuse using the Pythagorean theorem: sqrt(x*x + y*y). For example, the hypotenuse of a 3/4/5 right triangle is: >>> hypot(3.0, 4.0) 5.0 isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) Determine whether two floating point numbers are close in value. rel_tol maximum difference for being considered "close", relative to the magnitude of the input values abs_tol maximum difference for being considered "close", regardless of the magnitude of the input values Return True if a is close in value to b, and False otherwise. For the values to be considered close, the difference between them must be smaller than at least one of the tolerances. -inf, inf and NaN behave similarly to the IEEE 754 Standard. That is, NaN is not close to anything, even itself. inf and -inf are only close to themselves. isfinite(x, /) Return True if x is neither an infinity nor a NaN, and False otherwise. isinf(x, /) Return True if x is a positive or negative infinity, and False otherwise. isnan(x, /) Return True if x is a NaN (not a number), and False otherwise. isqrt(n, /) Return the integer part of the square root of the input. lcm(*integers) Least Common Multiple. ldexp(x, i, /) Return x * (2**i). This is essentially the inverse of frexp(). lgamma(x, /) Natural logarithm of absolute value of Gamma function at x. log(...) log(x, [base=math.e]) Return the logarithm of x to the given base. If the base not specified, returns the natural logarithm (base e) of x. log10(x, /) Return the base 10 logarithm of x. log1p(x, /) Return the natural logarithm of 1+x (base e). The result is computed in a way which is accurate for x near zero. log2(x, /) Return the base 2 logarithm of x. modf(x, /) Return the fractional and integer parts of x. Both results carry the sign of x and are floats. nextafter(x, y, /) Return the next floating-point value after x towards y. perm(n, k=None, /) Number of ways to choose k items from n items without repetition and with order. Evaluates to n! / (n - k)! when k <= n and evaluates to zero when k > n. If k is not specified or is None, then k defaults to n and the function returns n!. Raises TypeError if either of the arguments are not integers. Raises ValueError if either of the arguments are negative. pow(x, y, /) Return x**y (x to the power of y). prod(iterable, /, *, start=1) Calculate the product of all the elements in the input iterable. The default start value for the product is 1. When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject non-numeric types. radians(x, /) Convert angle x from degrees to radians. remainder(x, y, /) Difference between x and the closest integer multiple of y. Return x - n*y where n*y is the closest integer multiple of y. In the case where x is exactly halfway between two multiples of y, the nearest even value of n is used. The result is always exact. sin(x, /) Return the sine of x (measured in radians). sinh(x, /) Return the hyperbolic sine of x. sqrt(x, /) Return the square root of x. tan(x, /) Return the tangent of x (measured in radians). tanh(x, /) Return the hyperbolic tangent of x. trunc(x, /) Truncates the Real x to the nearest Integral toward 0. Uses the __trunc__ magic method. ulp(x, /) Return the value of the least significant bit of the float x. DATA e = 2.718281828459045 inf = inf nan = nan pi = 3.141592653589793 tau = 6.283185307179586 FILE (built-in)
2**5 > 5**2
True
2**5 >= 5**2
True
math.sqrt(2) == 2**0.5 # 两个等号判断是否相等
True
3**3 != 10 # 不等于 !=
True
2<5<10
True
2<5<3
False
命题1 | 命题2 | and | or |
---|---|---|---|
True | True | True | True |
True | False | False | True |
False | True | False | True |
False | False | False | False |
(2>3) & (5<6)
False
(2>3) and (5<6)
False
(2>3) | (5<6) # | 表示 or
True
(2>3) or (5<6)
True
not(2>3)
True
s = 'hello world'
type(s)
str
len(s)
11
Python的索引是从0开始的,0表示第一个位置,1表示第二个位置,以此类推
s[4] # 提取索引为4(第五个位置)的元素
'o'
s[10]
'd'
s[len(s)-1]
'd'
s[-1]
'd'
s[6] == s[-5] # 提取'w'
True
切片(slice)
s[start:end]
表示提取字符串s
索引从start
到end
-1之间的数s[4:8] # 提取索引从4至7的元素
'o wo'
s
'hello world'
s[2:10]
'llo worl'
s.upper()
'HELLO WORLD'
s
'hello world'
s1 = s.upper()
s1
'HELLO WORLD'
s1.lower()
'hello world'
s1.capitalize() # 首字母大写
'Hello world'
s
'hello world'
s1
'HELLO WORLD'
s + s1 # s与s1 首尾拼接
'hello worldHELLO WORLD'
s + ' ' + s1
'hello world HELLO WORLD'
s*5 # 将s重复5次
'hello worldhello worldhello worldhello worldhello world'
'**'*20
'****************************************'
列表的数据类型是可以通过[]
进行生成,里面的元素可以是各种各样类型,它的索引方式与字符串相同
a = [1,2,3.5,True,'hello',[20,31]] # 生成列表a
a[4]
'hello'
a[-1][1] # 提取31
31
a[3:5]
[True, 'hello']
列表中的元素可以进行更改,字符串中的元素不支持更改
a[3] = False
a
[1, 2, 3.5, False, 'hello', [20, 31]]
s[0] = 'H'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [101], in <cell line: 1>() ----> 1 s[0] = 'H' TypeError: 'str' object does not support item assignment
# 在末尾增加一个元素
a.append(22)
a
[1, 2, 3.5, False, 'hello', [20, 31], 22]
# 在末尾增加多个元素
a.extend([1000,2000,3000])
a
[1, 2, 3.5, False, 'hello', [20, 31], 22, 1000, 2000, 3000]
# 在中间插入元素
a.insert(3,'A')
a
[1, 2, 3.5, 'A', False, 'hello', [20, 31], 22, 1000, 2000, 3000]
# 删除指定索引的元素
a.pop(3)
'A'
a
[1, 2, 3.5, False, 'hello', [20, 31], 22, 1000, 2000, 3000]
# 删除指定值
a.remove(3.5)
a
[1, 2, False, 'hello', [20, 31], 22, 1000, 2000, 3000]
a1 = []
len(a1)
0
a1.append(1)
a1
[1]
字典通过大括号生成,它的结构为{key1:value1,key2:value2...}
age = {'John':15,'Tom':14,'Jerry':16}
age['Tom']
14
# 增加元素
age['Kate']=18
age
{'John': 15, 'Tom': 14, 'Jerry': 16, 'Kate': 18}
age.keys()
dict_keys(['John', 'Tom', 'Jerry', 'Kate'])
age.values()
dict_values([15, 14, 16, 18])
t = (1,2,3)
s2 = {1,2,3,4}
n = 100
if n > 18: # 如果 if后面的语句是True 那么后续语句就运行,否则就不运行
print('成年人')
成年人
n = 100
if n>18:
print('成年人')
else:
print('未成年人')
成年人
n = 500
if n<=18:
print('未成年人')
elif n < 40:
print('青年')
elif n < 60:
print('中年')
else:
print('老年')
老年
作业
生成一个列表,名字为subjects, 里面含有元素'math','bio','phy','chem','econ'。提取第四个元素中的第2个元素;将5个元素变成大写;在末尾增加两个元素分为为'eng','hist';删除第4个元素
定义一个函数 $$f(x)=\frac{1+2\sin(3x)}{\ln (4x+5)-20^x}$$ 并求$f(3)$
定义一个字典,名字为week,里面的元素的key为1,2,3,4,5,6,7,valule为'Monday'....'Sunday'
while
语句后的条件成立,语句就会一直运行for i in [1,2,3,4,5]:
print(i)
print('**'*10)
1 ******************** 2 ******************** 3 ******************** 4 ******************** 5 ********************
a = [1,2,3,4,5,6,7,8,9,10]
s = 0
for i in a:
s = s + i**2
s
385
range(m,n)
可以生成从m
到n-1
中的连续的整数。
range(n)
可以生成从0
到n-1
中连续的整数
list(range(1,5))
[1, 2, 3, 4]
range(1,5)
range(1, 5)
list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
s = 0
for i in range(1,101):
s = s+i**2
s
338350
求 $$\sum_{i=1}^{100} a_i$$
a = 0
for i in range(1,101):
a = a + 2*i+1
a
10200
设计一个函数,当输入等差数列的通项公式中的$a,b$,以及项数$n$,就可以求出这个等差数列的前$n$项和
def sum_a(a,b,n):
s = 0
for i in range(1,n+1):
s = s + a*i+b
return s
sum_a(3,5,20)
730
def sum_a2():
a = float(input('请输入等差数列通项公式中的 a'))
b = float(input('请输入等差数列通项公式中的 b'))
n = int(input('要求的项数'))
s = 0
for i in range(1,n+1):
s = s + a*i+b
return s
sum_a2()
请输入等差数列通项公式中的 a3 请输入等差数列通项公式中的 b5 要求的项数20
730.0
b = input('....')
....3
type(b)
str
type(int(b))
int
type(float(b))
float
n = 20
while n >10:
print(n)
n = n -1
20 19 18 17 16 15 14 13 12 11
s = 0
n = 1
while n <= 100:
s = s + n**2
n = n + 1
s
338350
def sum_a(a,b,n):
s = 0
for i in range(1,n+1):
s = s + a*i+b
return s
sum_a(1,2,3)
12
sum_a(1,2)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [28], in <cell line: 1>() ----> 1 sum_a(1,2) TypeError: sum_a() missing 1 required positional argument: 'n'
def sum_a3(a,b,n=100):
s = 0
for i in range(1,n+1):
s = s + a*i+b
return s
sum_a3(2,3)
10400
sum_a3(1,2,4)
18
位置参数一定是在默认参数前头
def factorial(n):
s = 1
for i in range(1,n+1):
s = s*i
return s
factorial(3)
6
def factorial_rec(n):
if n == 1:
return 1
else:
return n*factorial_rec(n-1)
def fabo(n):
if n == 1 or n==2:
return 1
else:
return fabo(n-1)+fabo(n-2)
fabo(8)
21
def func1(x,y):
return x**2+y**2
func1(10,20)
500
func2 = lambda x,y:x**2+y**2
func2(10,20)
500
len
¶len([1,2,3,4])
4
len('abcd')
4
sum
¶sum([1,2,3,4,5])
15
sum(range(1,100))
4950
map
¶map
函数可以将一个函数应用到给定序列中
list(map(fabo,[1,3,5]))
[1, 2, 5]
list(map(lambda x:x**3,[3,7,9]))
[27, 343, 729]
import math
[math.sin(i) for i in range(1,6)]
[0.8414709848078965, 0.9092974268256817, 0.1411200080598672, -0.7568024953079282, -0.9589242746631385]
[math.sin(i) for i in range(1,11) if i%2==0]
[0.9092974268256817, -0.7568024953079282, -0.27941549819892586, 0.9893582466233818, -0.5440211108893698]