Understanding bools in Python

Question:

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.

Asked By: dbel

||

Answers:

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")
Answered By: Abhishek Bhagate

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.

Answered By: John Smith

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

Answered By: Pro Chess

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")
Answered By: user13959036
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.