1.An Informal Introduction to Python

1.1 Using Python as a Calculator

1.1.1. Numbers

[1]直接数值运算

In [8]:
print('2+2=',2+2)
print('50-5*6=',50-5*6)
print('(50-5*6)/4=',(50-5*6)/4)
print('17/3=',17/3)   #代数除
print('17//3=',17//3)  #整除
print('17%3=',17%3) #取余数
print('5*3+2=', 5*3+2)
print('5**2=',5**2)
print('4**(0.5)=',4**(0.5))


2+2= 4
50-5*6= 20
(50-5*6)/4= 5.0
17/3= 5.666666666666667
17//3= 5
17%3= 2
5*3+2= 17
5**2= 25
4**(0.5)= 2.0
[2]变量

In [11]:
width=20
height=5*9
print('width=',width)
print('height=',height)
print('width*height=',width*height)
# print('n is not initialize, n=', n)
n=100
print('n=',n)


width= 20
height= 45
width*height= 900
n= 100

1.1.2 String

【1】string literals

In [15]:
print('spam eggs') #single quates
print('doesn\'t')  #escape char \'=='
print("doesn't")   #mix using " and '
print('"yes," he said.')
#escape char \n==change line
print('first line.\nsecond line') 
print("c:\some\name") #note \n 
print(r"c:\some\name")#r表示字符串没有escape
#'''或"""都可以显示多行的原始string
print('''\
Usage: thingy [OPTION]
    -h            Display this usage message
    -H hostname   Hostname to connect to
''')


spam eggs
doesn't
doesn't
"yes," he said.
first line.
second line
c:\some
ame
c:\some\name
Usage: thingy [OPTION]
    -h            Display this usage message
    -H hostname   Hostname to connect to

[2] string operator

In [17]:
print('hello ''world!')
print("hello "+"world!") #+将两个字符串连接
print(3*'ha')          #*生成重复的字符串


hello world!
hahaha

In [ ]: