Python example 2

Article directory


foreword

Today we will continue to talk about Python examples.


1. Fibonacci sequence

The Fibonacci sequence , also known as the golden section sequence , refers to such a sequence of 0, 1, 1, 2, 3, 5, 8, 13. In particular, the 0th item is 0, and the 1st item is the first 1. Starting with the third term, each term is equal to the sum of the previous two.

code:

# 获取用户输入数据
nterms = int(input("你需要几项?"))
 
# 第一和第二项
n1 = 0
n2 = 1
count = 2
 
# 判断输入的值是否合法
if nterms <= 0:
   print("请输入一个正整数。")
elif nterms == 1:
   print("斐波那契数列:")
   print(n1)
else:
   print("斐波那契数列:")
   print(n1,",",n2,end=" , ")
   while count < nterms:
       nth = n1 + n2
       print(nth,end=" , ")
       # 更新值
       n1 = n2
       n2 = nth
       count += 1

Effect:

你需要几项? 10
斐波那契数列:
0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 ,

 

2. Armstrong number

If an  n  -digit positive integer is equal to the sum of the nth powers of its digits  ,  the number is called an Armstrong number. For example 1^3 + 5^3 + 3^3 = 153.

Armstrong numbers up to 1000: 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407.

# 获取用户输入的数字
num = int(input("请输入一个数字: "))
 
# 初始化变量 sum
sum = 0
# 指数
n = len(str(num))
 
# 检测
temp = num
while temp > 0:
   digit = temp % 10
   sum += digit ** n
   temp //= 10
 
# 输出结果
if num == sum:
   print(num,"是阿姆斯特朗数")
else:
   print(num,"不是阿姆斯特朗数")

 Get the Armstrong number for a specified period:

# Filename :test.py
# author by : www.runoob.com
 
# 获取用户输入数字
lower = int(input("最小值: "))
upper = int(input("最大值: "))
 
for num in range(lower,upper + 1):
   # 初始化 sum
   sum = 0
   # 指数
   n = len(str(num))
 
   # 检测
   temp = num
   while temp > 0:
       digit = temp % 10
       sum += digit ** n
       temp //= 10
 
   if num == sum:
       print(num)

Summarize

That's it for today.

 

Guess you like

Origin blog.csdn.net/we123aaa4567/article/details/129130049