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

题目来源: 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 这个语言的语法的确比较简洁,很直观。

转载于:https://www.cnblogs.com/OA-maque/p/4802711.html

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值