基础知识

我一直是喜欢用for循环的,格式更工整,

for 循环变量 in 有序序列 :(:和下一行的锁进共同开启循环模块)

循环次数更是尽在掌握中的感觉。

range函数可以自动产生序列,它来控制for循环的循环次数可以很帅

接收的参数个数也是可变的:

给它一个参数,比如range(5),即for i in range(5),则循环变量i从0递增到4,然后...偏偏就是不包括5,too bad!

给它两个参数,比如range(12, 16),即for i in range(12, 16),则循环变量i从12递增到16

如果给三个参数,就是规定步数了for i in range(1, 10, 2),则循环变量按1、3、5、7、9的序列变化

在视频里我们用for循环解决了1到100的求和问题,

据说数学家高斯的老师就是从这道题的计算发现了高斯的数学天才。10岁的高斯用的是对称法,1和99、2和98...凑出了50个100,再加上中间的50得到了正确答案5050,用时几秒钟。

# 1 + 2 + 3 + 4 + ... + 99 + 100

# Empty sum variable
total = 0

# Use loop to accumulate 1 to 100
for num in range(101):
	total += num

# Print out the result
print('1 + 2 + 3 + ... + 100 = ', total)

我们继续用for循环做算数,一个非常简单的储蓄增长程序:用户输入本金和利率,程序计算出若干年后能拿回多少钱。

如果计算没错的话,投资20万,利率为5的情况下,能拿回32万多。程序结果刚出来时我觉得好多啊!!!

可后想想还有通货膨胀呐,如果算上通货膨胀,是不是32万就不多了呢?

这个问题我想破头也没想明白。

# ---------- PROBLEM : COMPOUNDING INTEREST ----------

# Have the user enter their investment amount and interest rate
# Each year : investment + investment * interest rate
# Print out the earning after a 10 year period

# Ask for the money invested and the interest rate
money = input('How much to invest: ')
interest_rate = input('Interest Rate: ')

# Convert the value to a float
money = float(money)

# Convert value to a float and round the percentage rate by 2 digits
interest_rate = float(interest_rate) * .01

# Cycle through 10 year using a for loop and range from 0 to 9
for i in range(10):

	# Add the current money in the account + interest earned that year
	money = money + money * interest_rate

# Output the results
print("Investment after 10 years: {:.2f}".format(money))

Python 循环控制之for循环:
 

1 1 1 1 1 1 1 1 1 1 Rating 2.50 (5 Votes)