python - 为什么这个 python while 循环缺少逻辑运算符?

标签 python while-loop

我正在通过艰难的方式学习 python,在练习 33 额外学分 2 中,我正在尝试利用 raw_inputargv 设置将在 while 循环中使用的变量:

# from sys import argv
# script, my_num = argv

def all_the_numbers(n):
   """increment by 1 up to limit n"""
   i = 0
   numbers = []
   while i < n:
      print "At the top i is %d" % i
      numbers.append(i)

      i = i + 1
      print "Numbers now: ", numbers
      print "At the bottom i is %d" % i

# print "Please enter an integer: "
# n = raw_input("#")
# n = my_num
n = 10
all_the_numbers(n)

硬编码的 n = 10 按预期工作;打印最多 10 行。但是从 argv 中传入一个值作为 my_num 和/或从 raw_input 中设置变量会导致无限向上的整数递增。后两种设置变量的方式有何不同,它们的行为与同一变量的硬编码设置不同?

最佳答案

raw_input()函数返回一个字符串,而不是一个整数。尝试:

n = int(raw_input("#"))

n = int(my_num)

这会转换 raw_input() 返回的字符串变成一个整数,你的 all_the_numbers()函数期望。

这是 relevant passage from the Python docs (强调我的):

The operators <, >, ==, >=, <=, and != compare the values of two objects. The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily.

在您的例子中,数字和字符串是任意排序的,在您的例子中是 <比较总是评估为 True .确保此类比较的类型兼容是程序员的责任。

关于python - 为什么这个 python while 循环缺少逻辑运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5466346/

相关文章:

python - 在数据帧的新列中返回 TextBlob 正、负或中性分类

python - 将 numpy 数组转换为十六进制字节数组

java - 当收到 NumberFormatException 时,如何阻止或重做 SWING 输入?

c - While 循环内的优先级

java - Java 中的 while 循环不会对文档的最后一行执行操作

python - 运行 python 单元测试作为程序的一个选项

python - 如何使用正则表达式来帮助抓取网络数据?

python - 将 2+ 个 mock.patch 合二为一

php - 使用 while 时 PHP 中的 MySql_fetch_array() 错误

c - C 猜谜游戏,使用 while 循环和 if 语句调试