当前位置: 动力学知识库 > 问答 > 编程问答 >

python - How to find the numbers in between the numbers that the user has input?

问题描述:

I'm using Grok learning and I need help with finding the numbers in between if a user inputs them.

For example:

3

6

The numbers in between: 4, 5

But this is what I need exactly:

Up the lift The lift is broken! It can still go up and down, but

doesn't display what floor it's at anymore, which is causing confusion

for people trying to use it.

Write a program that will display the floor numbers on an elevator

that is going up. Your program should read in the current floor and

read in the destination floor, which will always be higher than the

current floor. Your program should print out each of the floor numbers

in-between.

Current floor: 3

Destination floor: 6

Level 3

Level 4

Level 5

Level 6 ​

Current floor: 1

Destination floor: 2

Level 1

Level 2

So my current code is:

current = int(input("Current floor: "))

desti = int(input("Destination floor: "))

print("level",current)

print("level",desti)

Now I'm confused how to get it to output the numbers in between.

网友答案:

You could use the range() function using the upper and lower bounds entered by the user:

>>> current = int(input("Current floor: "))
>>> desti = int(input("Destination floor: "))
>>> print(*range(current+1, desti))
4 5
>>> between = list(range(current+1, desti))
>>> between
[4, 5]

If you want the floors going backwards you can do this:

list(range(desti, current, -1))

or you can simply reverse the range:

list(reversed(range(current+1, desti)))

Printing downwards:

print(*range(current+1, desti), sep='\n')

Formatting the output in a loop:

for level in range(current+1, desti):
    print('Level {}'.format(level))
网友答案:

You could create a loop starting at the current floor (exclusive) and increment until you reach the destination floor (exclusive).

网友答案:

Have a look at range function. I think this will do exactly what you want to do.

http://pythoncentral.io/pythons-range-function-explained/

Lets say the range you need is in between 1 and 5.

In Python 2.x it returns a list,

>>> range(1, 5)
[1, 2, 3, 4]

In Python 3.x it's a iterator. so you should convert it to a list.

>>> list(range(1, 5))
[1, 2, 3, 4]

Second input is exclusive, so add one to the last value of the list

4+1=5

分享给朋友:
您可能感兴趣的文章:
随机阅读: