Python:raw_input 读取数字时出现问题[重复]
- 2025-02-14 09:50:00
- admin 原创
- 42
问题描述:
不幸的是 raw_input 没有做我需要它做的事情。我想做的是让 totPrimes = 我在提示符下输入的任何内容。如果我while count < totPrimes
用while count < 50
这个脚本替换,它会起作用。如果我在提示符中输入 50,这个脚本不起作用,我担心 raw_input 不是我想要使用的函数?这是我的代码片段:
testNum = 3
div = 2
count = 1
totPrimes = raw_input("Please enter the primes: ")
while count < totPrimes :
while div <= testNum :
解决方案 1:
做
totPrimes = int(totPrimes)
while count < totPrimes:
# code
raw_input
给出一个字符串,在进行任何数字比较之前,您必须将其转换为整数或浮点数。
解决方案 2:
您需要将 totPrimes 转换为 int,如下所示:
integer = int(totPrimes)
解决方案 3:
您只需要将原始输入转换为整数即可。对于您的代码,只需将代码更改为:
testNum = 3
div = 2
count = 1
totPrimes = raw_input("Please enter the primes: ")
totPrimes=int(totPrimes)
while count < totPrimes :
while div <= testNum :
解决方案 4:
raw_input 函数总是返回 'string' 类型raw_input docs,所以在这种情况下我们必须将totPrimes
'string' 类型转换为 'int' 或 'float' 类型,如下所示:
totPrimes = raw_input("Please enter the primes: ")
totPrimes = float(totPrimes)
您可以像这样组合它们:
totPrimes = float(raw_input("Please enter the primes: "))
为了在 python 中比较事物count < totPrimes
,比较需要有意义(数字与数字,字符串与字符串),否则程序将崩溃并且while count < totPrimes :
while 循环将无法运行。
您可以使用 try/except 来保护您的程序。管理异常
对于参加“人人编程”课程的人来说,您可以花费数小时并以此方式进行评分。您应该尝试弄清楚 if/else 语句。
解决方案 5:
您必须将每个数字更改为“小时”或“费率”。
例如:40*10.50+(h-40)*10.50*1.5
是错的,40*r+(h-40)*r*1.5
是正确的。
解决方案 6:
然后使用输入。
原始输入返回字符串。
输入返回 int。
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD