运行if和elif语句的Python代码有问题

运行if和elif语句的Python代码有问题,python,if-statement,Python,If Statement,另一个我遇到麻烦的简单问题。 如果我运行下面的代码并键入8或9作为输入,代码将返回正确的响应。一旦我输入较大的数字,如10、20,它就会返回我的袜子比你的多 这与int和str值有关,还是我把代码搞乱了。请用外行的语言解释 my_socks = "7" user_input = input("How many socks do you have?") if user_input < my_socks: print("I h

另一个我遇到麻烦的简单问题。 如果我运行下面的代码并键入8或9作为输入,代码将返回正确的响应。一旦我输入较大的数字,如10、20,它就会返回我的袜子比你的多 这与int和str值有关,还是我把代码搞乱了。请用外行的语言解释

 my_socks = "7"

 user_input = input("How many socks do you have?")

 if user_input < my_socks:
    print("I have more socks than you!")
 elif user_input > my_socks:
    print("You have more socks than me!")

非常感谢

您实际上是在比较字符串,因此它使用了字母顺序,意思是“10” 你需要ints


当python读取用户输入时,默认类型为str,请选中

我建议您处理数字int,使您的程序在您的场景中工作。这是因为当您使用字符串值来评估条件时,实际上使用的是ASCII代表信息交换的美国标准代码。因此,“7”转换为55,“10”因为它有2个字符,所以只能将“1”的值转换为49

如果您执行以下操作,您的程序应按预期工作

my_socks = 7
user_input =  int(input("How many socks do you have?"))
if user_input < my_socks:
    print("I have more socks than you!")
elif user_input > my_socks:
    print("You have more socks than me!"

这与int和str值有关吗?听起来你已经知道答案了。这能回答你的问题吗?这回答了你的问题吗?
my_socks = 7
user_input =  int(input("How many socks do you have?"))
if user_input < my_socks:
    print("I have more socks than you!")
elif user_input > my_socks:
    print("You have more socks than me!"