-2

I'm trying to learn some Python and had a question about a really small "program" I made as a test.

    a = input()
    print(a)
    b = '10'
    if a == b:
       print("Yes")
    else:
       print("No")

This works, but my question is why does the value for b have to have the quotes around it.

halfer
  • 19,824
  • 17
  • 99
  • 186
dbel
  • 33
  • 6
  • 5
    Because it's the string `"10"` instead of the integer `10`. `input()` returns strings, so if you want to check for equality, you have to compare to another string. – John Gordon Aug 17 '20 at 18:25
  • 2
    `input()` returns a string. A good way to find out about such things is to start the python interpreter and type `help(input)` e.g. – NickD Aug 17 '20 at 18:26
  • 2
    `a` is a string because it comes from `input()`. It can only possibly be equal to another string, like `'10'`, as opposed to an integer, `10`. – khelwood Aug 17 '20 at 18:27

4 Answers4

2

Python input() function will by default take any input that you give and store it as a string.


why does the value for b have to have the quotes around it

Well, it doesn't have to have quotes. But if you need the condition to evaluate to True, then you need quotes. So, since a is a string, you need to have b = '10' with the quotation mark if you need a == b to evaluate to True.

If your input is an integer, you could also do a = int(input()) and in this case, b=10 would work as well. Simple !

So, the following two can be considered to be equivalent in terms of the result they give -

a = input()

b = '10'
if a == b:
    print("Yes")
else:
    print("No") 

AND

a = int(input())

b = 10
if a == b:
    print("Yes")
else:
    print("No")
Abhishek Bhagate
  • 5,583
  • 3
  • 15
  • 32
1

The value of input() is a string, therefore you must compare it to a string. Everyone learning programming starts off with many questions, and it is the only way to learn, so do not feel bad about it.

John Smith
  • 671
  • 1
  • 9
  • 22
1

It is actually quite simple. All inputs from the user are considered as string values by python. In python, you can only compare a string to string, integer to integer and so on...

You could do this as well

    a = int(input())
    print(a)
    b = 10
    if a == b:
       print("Yes")
    else:
       print("No")

Over here int() converts the value you enter to an integer. So you don't need quotes for the variable b

Pro Chess
  • 831
  • 1
  • 8
  • 23
1

In python default input type is string. if you want it as int you must cast it:

a = int(input()) #change type of input from string to int
print(type(a))
b = 10
if a == b:
    print("Yes")
else:
    print("No")