-4

another simple problem that I'am having trouble with. If I run the below code and type 8, or 9 as the input, the code returns the correct response. Once I type larger numbers such as 10, 20 it just returns "I have more socks than you" Is this something to do with int and str values or have I just messed up the code. Please explain in laymans terms.

 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!")

Many thanks

SimonJN
  • 23
  • 5
  • 2
    *"Is this something to do with int and str values"* - sounds like you already know the answer. – alani Sep 12 '20 at 08:25
  • Does this answer your question? [String comparison technique used by Python](https://stackoverflow.com/questions/4806911/string-comparison-technique-used-by-python) – tornikeo Sep 12 '20 at 08:30
  • Does this answer your question? [How can I read inputs as numbers?](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers) – Gino Mempin Sep 12 '20 at 10:30

2 Answers2

1

You are actually comparing strings,so it uses the lexicographic order (alphabet order) which means '10' < '7' because you look character by character and '1' < '7'

You need ints

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!")
else:
   print("We have the same amount !")
alani
  • 12,573
  • 2
  • 13
  • 23
azro
  • 53,056
  • 7
  • 34
  • 70
0

When python is reading user input the default type is str, check here.

I suggest you deal with numbers (int) to make your program work in your scenario. This is because when you are using string values to evaluate conditions you are actually using the ASCII (ASCII stands for American Standard Code for Information Interchange). So '7' translates to 55 and '10' since it is has 2 characters will only translate to 49 the value of '1'

If you do the following your program should work as expected.

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!"