任何计算机都能做的两件事是:进行计算、存储结果
不能把推算平方根的方法写成真正的计算机程序是因为计算机不能猜出y的初始值
程序计数器指向程序将执行的下一条命令
判断子串是否有意义静态语义Static sematics
赋予合法的语句意义 Sematics
round是把数字往绝对值大方向取整 int是把数字往绝对值小方向取整
temp = 120
if temp > 85:
print "Hot"
elif temp > 100:
print "REALLY HOT!"
elif temp > 60:
print "Comfortable"
else:
print "Cold"
#这个比较,从最先开始判定的开始比较,所以结果应该是Hot
temp = '32'
if temp > 85:
print "Hot"
elif temp > 62:
print "Comfortable"
else:
print "Cold"
# 虽然说的是不同类型在python里面能够比较,而且某些类型总是比另一些类型大,在新版里面就没有这样的结果了
# 老版里面string类型一定比int大
var = 'Panda'
if var == "panda":
print "Cute!"
elif var == "Panda":
print "Regal!"
else:
print "Ugly..."
#python在比较时大小写必须严格对齐
a += b is equivalent toa = a + b
a -= b is equivalent to a = a - b
a *= b is equivalent to a = a * b
a /= b is equivalent to a = a / b
school = 'Massachusetts Institute of Technology'
numVowels = 0
numCons = 0
for char in school:
if char == 'a' or char == 'e' or char == 'i' \
or char == 'o' or char == 'u':
numVowels += 1 #这里的大写 I不算数
elif char == 'o' or char == 'M':
print (char)
else:
numCons -= 1
print ('numVowels is: ' + str(numVowels))
print ('numCons is: ' + str(numCons))
#最后结果当然是numVowels is:11
#numCons is:-25
for variable in range(20):
if variable % 4 == 0:
print variable
if variable % 16 == 0:
print 'Foo!'
#这里千万注意,range是从0开始的,所以肯定可以在0的地方输出一个Foo!
#表达逆序range的两种方式,可以在输出时做好,也可以在设定的时候用range(10,0,-2)设定好
# There are always many ways to solve a programming problem. Here is one:
print "Hello!"
for num in range(0, 10, 2):
print 10 - num
# Here is another:
print "Hello!"
for num in range(10, 0, -2):
print num
"Hello, world!"
#有多少个字符?,不能漏数空格,12个,极其容易数错
count = 0
phrase = "hello, world"
for iteration in range(5):
while True:
count += len(phrase)
break
print "Iteration " + str(iteration) + "; count is: " + str(count)
#这就是为了用while而用while
x = 25
epsilon = 0.01
step = 0.1
guess = 0.0
while guess <= x:
if abs(guess**2 -x) < epsilon:
break
else:
guess += step
#到这里用穷举法从0开始用步长step进行搜索,检测能否求到epsilon内精确
if abs(guess**2 - x) >= epsilon:
print 'failed' #因为步长太大,上面那步无法穷举出来,所以失败
else:
print 'succeeded: ' + str(guess)
使用round()
命令可以四舍五入,0.5入0
round(0.5000000000000001)小数点后16位入1
round(0.50000000000000001)入0 可能后面的1省略了
可能是因为双精度浮点数小数点后刚好16位就看作有效
在同一行输出的小技巧
Python Trick: Printing on the same line
Try the following in your console:
# Notice how if we have two print statements
print "Hi"
print "there"
# The output will have each string on a separate line:
Hi
there
# Now try ading a comma after the print statement:
print "Hi",
print "there"
# The output will place the subsequent string on the same line:
Hi there