Python两个整数循环,+1到A直到A = B.

时间:2013-06-15 14:31:42

标签: python loops integer

我需要帮助创建一个循环,它会向用户询问python中的两个数字(一个大于另一个),然后继续向小数字添加1,直到小数字等于大数字。< / p>

在此期间,我需要它同时打印出数字。

背景:我是python的新手,这是编程类的最后一步,我已经完成了4个任务,这很简单,但这是剩下的一个。

示例:请输入一个小数字:5
          请输入一个大数字:10
          5,6,7,8,9,10

我希望如何运作?

var_small = int(raw_input("Please enter a small number : "))
var_large = int(raw_input("Please enter a large number : "))

if var_small > var_large:
print "Try two other numbers, remember that the small number comes first!"
 #Here I would re-run the loop
elif var_small < var_large:
var_small +1 until = var_large

我很抱歉这样一个noob问题,我希望得到回复。

3 个答案:

答案 0 :(得分:2)

您必须将对var_small和var_large的赋值与while循环

组合
var_small = int(raw_input("Please enter a small number : "))
var_large = int(raw_input("Please enter a large number : "))

while var_small > var_large:
    print "Try two other numbers, remember that the small number comes first!"
    var_small = int(raw_input("Please enter a small number : "))
    var_large = int(raw_input("Please enter a large number : "))

while var_small != var_large:
    var_small += 1
    print var_small, var_large

答案 1 :(得分:1)

>>> var_small = 5
>>> var_large = 10
>>> range(var_small, var_large + 1)
[5, 6, 7, 8, 9, 10]

我猜你正在寻找一种“原始”方式。那么while - 循环似乎适合你:

>>> while var_small <= var_large:
...     print var_small
...     var_small += 1
5
6
7
8
9
10

答案 2 :(得分:0)

以下代码不需要重复输入语句,并根据您的请求显示输出(在一行上):

# Initialize variables.
var_small = 0
var_large = 0

while var_small >= var_large:
    var_small = int(raw_input("Please enter a small number : "))
    var_large = int(raw_input("Please enter a large number : "))

    # Need to try this again ?
    if var_small >= var_large:
        print "Try two other numbers, remember that the small number comes first!"

# Output loop
while var_small != var_large:
    # Mind the , at the end to avoid a newline
    print "%d, " % var_small,
    var_small = var_small + 1

# Also print the last value and a newline
print var_large