统计任意两个正整数之间所有奇数的和

题目来源: Conditions and Loops

 1 #!/usr/bin/python3
 2 # sum all odds between two positive integer
 3 
 4 a = int(input("Please input one positive integer > ")) # in python3, input() replace of raw_input(), so use int() 
 5 b = int(input("Please input another positive integer > "))
 6 
 7 if a == b:                                      # use condition check
 8     print("please input two different integer")
 9     exit()             # should add it, elsewise it will continue execute the print() statement in the end
10 elif a > b:
11     small_num = b
12     large_num = a
13 else:
14     small_num = a
15     large_num = b
16 
17 sum_odd = 0
18 for i in range(small_num, large_num + 1):   # use for loop, and use range() function 
19     if i % 2 == 1:
20         sum_odd = sum_odd + i
21 
22 print("the sum of all odds number between " + str(small_num) + " and " + str(large_num) + " is " + str(sum_odd))

运行结果:

ubuntu:~/python3$ python3 sum_odd.py 
Please input one positive integer > 100
Please input another positive integer > 200
the sum of all odds number between 100 and 200 is 7500

虽然真的很简单,但是挺有意思的,而且也能体现 python 这个语言的语法的确比较简洁,很直观。

posted on 2015-09-12 11:10  OA_maque  阅读(642)  评论(0编辑  收藏  举报

导航