【问题标题】:(Python) Trying to make a simple Counter (Book project)(Python)尝试做一个简单的计数器(书籍项目)
【发布时间】:2015-08-10 19:19:45
【问题描述】:

尝试用python做一个简单的计数器 对于“Learn Python Book”中的项目

简介:编写一个对用户有用的程序。 让用户输入起始号码, 结束号码和金额 数数。

到目前为止我所拥有的:

print ("Welcome to the program for those who are to lazy to count")
print ("You must be really really lazy too use this")

input ("\n Press any key to continue")

Num1 = input ("Please Enter Starting Number: \n")
Num2 = input ("Please Enter Ending Number: \n")
count = input ("Count up in: \n")

while (Num1 < Num2):
      Num1 += count
      print (Num1)      

不确定这段代码有什么问题,它卡在无限循环中,有人能解释一下原因吗?并且可能是一个修复:) 卡住了

【问题讨论】:

  • 提示:"100" &lt; "9" 是真的。 100 &lt; 9 是假的。
  • 嗯,你能详细说明一下 Num1 和 Num2 是变量,所以如果我将它们放在 "" 引号内,它只会将它们视为字符串?

标签: python python-3.x counter


【解决方案1】:

正如凯文所说,您正在比较字符串。您需要将输入转换为 int 以便它们可以与

【讨论】:

  • 啊,好吧,我知道有那个操作员吗?
  • 你的书没有提到int()内置函数?
  • 目前还没有,我什么时候会使用 int()
  • 你的书是为 Python 2 设计的吗?
  • 如果它是为 Python 3 设计的,并且在告诉你比较整数时甚至没有提到 int(),我认为这不是一本很好的书。你应该试试[官方 Python 教程](https://docs.python.org/3.4/tutorial)。
【解决方案2】:

正如其他人所说,input() 函数返回一个类型string,因此您无法正确地将这些值与&lt; 运算符进行比较。

您应该首先使用内置函数int()num1num2count 的类型转换为整数(参见The Python Standard Library)。

试试这个简化版(无错误处理):

Num1 = int(input ("Please Enter Starting Number: \n"))
Num2 = int(input ("Please Enter Ending Number: \n"))
count = int(input ("Count up in: \n"))

希望对您有所帮助!

【讨论】:

  • 非常感谢,希望我知道 int() 这么小的错误 >
猜你喜欢
  • 1970-01-01
  • 2010-09-22
  • 2016-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-23
  • 2020-12-18
  • 1970-01-01
相关资源
最近更新 更多