增加用户的输入

时间:2014-11-20 10:59:31

标签: python loops input while-loop increment

该程序向用户询问三个问题:

  1. 输入您希望我开始计算的数字;
  2. 输入您希望我结束的号码;和
  3. 你想增加多少?
  4. 从问题中,你可以看到我希望程序做什么。

    我的问题是我可以通过将start循环放入while循环来手动递增#Demonstrates user's input and increment. start = int(input("Enter the number you want me to start counting in: ")) end = int(input("Enter the number you want me to end in: ")) increment = int(input("How much do you want to increment by? ")) while start < end: start += 1 print(start) input("Press the enter key to exit..") 数字,但我不能将其作为用户的输入合并。

    {{1}}

    我知道程序中的第三个问题是无用的,因为它与实际循环没有关系,但我把它放在那里因为那将是我最终程序的一部分。

3 个答案:

答案 0 :(得分:1)

如果您要打印从startend的数字,包括极端情况,while上的条件不正确,因为当您start的数字为stop时要打印的内容完全等于start<stop,条件Falsewhile,因此while not start > end: ... 的正文不会执行。

正确的条件是

while start !> end:
    ...

while start <= end:
    ...

或最终

True

start等于end时,所有这三种编写测试的方式都会评估为start

作为旁注,在我看来,你最好不要将while用于incr = 1 current = start while current <= end: print(current) current = current + incr 循环,而是引入一个辅助变量,如

{{1}}

Post Scriptum

有更多惯用的方式(更多 pythonic 方式,有人会告诉你)来完成你的工作,但是现在让我们保持简单的事情尽可能简单...此外,我希望你没有错过使用增量的隐含提示......

答案 1 :(得分:0)

试试这个:

while start < end:
    start += increment
    print(start)

答案 2 :(得分:-2)

使用Python range()函数。它需要三个参数:

  1. 起点
  2. 结束点
  3. 每次递增
  4. 例如:

    def increment(start, end, increment):
         for i in range(a, b, increment):
             print(i)