3

我需要帮助创建一个循环,它将在 python 中向用户询问两个数字(一个比另一个大),然后继续将 1 加到小数上,直到小数等于大数。

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

背景:我对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

我很抱歉提出这样一个菜鸟问题,我希望我能得到答复。

4

3 回答 3

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
于 2013-06-15T14:41:04.290 回答
1
>>> var_small = 5
>>> var_large = 10
>>> range(var_small, var_large + 1)
[5, 6, 7, 8, 9, 10]

我猜你正在寻找一种“更原始”的方式。那么while-loop 看起来很适合您:

>>> while var_small <= var_large:
...     print var_small
...     var_small += 1
5
6
7
8
9
10
于 2013-06-15T14:35:40.350 回答
0

The following code does not require the input statements to be repeated and presents the output as you request (on a single line):

# 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
于 2013-06-15T14:53:21.247 回答