Understanding bools in Python [duplicate] - python

This question already has answers here:
Python input never equals an integer [duplicate]
(5 answers)
Closed 2 years ago.
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.

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

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

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.

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

Related

while loop not terminating on changing test condition [duplicate]

Switching from Unity JS to Python for a bit, and some of the finer points elude me as to why this does not work.
My best guess is that the variable guess is actually a string, so string 5 is not the same as integer 5?
Is this what is happening and either way how does one go about fixing this.
import random
import operator
ops = {
'+':operator.add,
'-':operator.sub
}
def generateQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
op = random.choice(list(ops.keys()))
a = ops.get(op)(x,y)
print("What is {} {} {}?\n".format(x, op, y))
return a
def askQuestion(a):
guess = input("")
if guess == a:
print("Correct!")
else:
print("Wrong, the answer is",a)
askQuestion(generateQuestion())
Yes, you are absolutely right that "5" is distinct from 5. You can convert 5 into a string by using str(5). An alternative would be to convert "5" into an integer by int("5") but that option can fail, so better handle the exception.
So, the change to your program could be e.g. the following:
if guess == str(a):
instead of:
if guess == a:
Another option would be to convert guess into an integer, as explained in the other answer.
EDIT: This only applies to Python versions 2.x:
However, you're using input(), not raw_input(). input() returns an integer if you type an integer (and fails if you type text that isn't a valid Python expression). I tested your program and it asked What is 4 - 2?; I typed 2 and it sait Correct! so I don't see what is your problem.
Have you noticed that if your program asks What is 9 - 4? you can type 9 - 4 and it says Correct!? That's due to you using input(), not raw_input(). Similarly, if you type e.g. c, your program fails with NameError
I would however use raw_input() and then compare the answer to str(correct_answer)
I am assuming you are using python3.
The only problem with your code is that the value you get from input() is a string and not a integer. So you need to convert that.
string_input = input('Question?')
try:
integer_input = int(string_input)
except ValueError:
print('Please enter a valid number')
Now you have the input as a integer and you can compare it to a
Edited Code:
import random
import operator
ops = {
'+':operator.add,
'-':operator.sub
}
def generateQuestion():
x = random.randint(1, 10)
y = random.randint(1, 10)
op = random.choice(list(ops.keys()))
a = ops.get(op)(x,y)
print("What is {} {} {}?\n".format(x, op, y))
return a
def askQuestion(a):
# you get the user input, it will be a string. eg: "5"
guess = input("")
# now you need to get the integer
# the user can input everything but we cant convert everything to an integer so we use a try/except
try:
integer_input = int(guess)
except ValueError:
# if the user input was "this is a text" it would not be a valid number so the exception part is executed
print('Please enter a valid number')
# if the code in a function comes to a return it will end the function
return
if integer_input == a:
print("Correct!")
else:
print("Wrong, the answer is",a)
askQuestion(generateQuestion())

How do I create an if statement to check if my variable is an int? [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 years ago.
I want to make a program where I need to check the input of the user
so, the question is How do I check the input value, if it`s a string or an integer?
Here's some experimental code that didn't work:
a = 10
print(type(a))
if (a==10):
print("aaaaa")
else:
if(type(a)== "<class 'int'>"):
print("12345")
You can do it in the following way:
a = 10
if type(a) is int:
print("Yes")
else:
print("No")
input() will always return string, i.e type(input()) will be str
from my understanding, you want to validate input before proceeding further
, this is what you can do
foo = input()
if not foo.isdigit():
raise ValueError("Enter a valid integer")
foo = int(foo)
this will not work for a negative number, for that you can check if foo startswith "-"
if foo.lstrip("-").isdigit():
multiply_by = -1 if foo.startswith("-") else 1
foo = multiply_by * int(foo.lstrip("-"))
and if you want to check type of variable
a = 10
if isinstace(a, int):
pass

Find biggest number out of 3 numbers

I am trying to find of biggest of 3 numbers using python3.6. But its returning wrong value.
#!/usr/bin/python3
a=input("Enter first number: ")
b=input("Enter second number: ")
c=input("Enter Third number: ")
if (a >= b) and (a >= c):
largest=a
elif (b >= a) and (b >= c):
largest=b
else:
largest=c
print(largest, "is the greatest of all")
If I provide, a=15; b=10 and c=9
Expected output should be 15.
But I am getting actual output as 9.
input() returns strings. You need to convert the strings to class int to compare their numeric value:
a = int(input("Enter the first number: "))
In string comparisons, 9 is greater than 1. You can try in the REPL:
>>> '9' > '111111111111111111'
True
You can use the max() builtin function of python:
https://www.freecodecamp.org/forum/t/python-max-function/19205
Like the comment of khelwood mentioned it You are comparing strings, not numbers. – khelwood. You should first cast the input values to integers (or float) and then compare them.
More about casting in python can be found here
As khelwood pointed out in comment those inputs are used as strings.
try inserting this after input and its fixed:
a = int(a)
b = int(b)
c = int(c)

Condition checking in python with user input [duplicate]

This question already has answers here:
If...else statement issue with raw_input on Python
(2 answers)
Closed 7 years ago.
I tried taking an input from keyboard. the checking that input with an if else statement. But everytime the else part is working. The if statement does not happen to be true. I can't understand where I am going wrong.
Here is what I have done.
abc= raw_input("Enter a 2 digit number");
if abc==6:
print "Its party time!!!"
else:
print "Its work time"
Please suggest
Your input variable is a string. You need to cast it to an integer to correctly compare it to 6.
if int(abc) == 6:
raw_input returns a string. abc is a string, and a string will never be equal with an integer. Try casting abc or the return value of raw_input(). Or, you can make 6 a string.
Casting the return value of raw_input() :
abc = int( raw_input('Enter a 2 digit number') )
Casting abc :
abc = int(abc)
or
if int(abc) == 6:
Changing 6 to string :
if abc == '6':
>>> abc= raw_input("Enter a 2 digit number")
Enter a 2 digit number6
>>> if int(abc) == 6:
print "Its party time!!!"
Its party time!!!
>>>

While loop adding two numbers

I want to write a very basic code.
Add two numbers,next add another number given by user,print result,ask for another,add to previous result,print new result.
I've started with that:
a=int(raw_input('give a number'))
b=int(raw_input('give second number'))
y=True
n=False
while input('Continue? (y/n)') != 'n':
c = a + b
print c
b = int(raw_input('give another number'))
Ok I've correct code by your tips.I am appreciate but it stil doesn't work.It add two numbers,print result then ask for another add to result(right now its ok) But when you enter another it add to a and then print.
Maybe you see what is wrong?
And when I enter "n" it didn't end the program
I'd avoid using input() in lieu of raw_input() (safer, and input() was removed in Python 3). With it, you can then turn the input into a number yourself by wrapping it with int() or float(). Then you have a couple possibilities:
Loop forever, and end the loop if you get an error in conversion:
...
while True:
try:
b = int(raw_input('give another number ("x" to exit)'))
except ValueError:
break
...
Or, break if you see some sentinel value, for instance 0 (which conveniently evaluates as false).
a = 1
b = 2
while b:
a = a + b
print a
b = int(raw_input('give another number'))
In most programming languages, including Python, conditions must evaluate to true or false. In this case, the string "condition" will always evaluate to true, because only empty strings evaluate to false. In order to leave the while loop, you must first determine what condition is necessary to discontinue looping. With
while condition: pass
condition can be an if statement, or an object reducible to True or False. Most objects, such as lists, tuples, and strings, evaluate to True when not empty, and False when empty. The other common condition is a comparison between two values; such as
1 < 2
or
a is b
The simplest condition you could check for is EOF (end of file). That would be when the user does not type a number but instead just types a carriage return.
It is up to you to tell the user how to end the program. So you also have to write an instruction to them e.g.
b=input('give another number or type <enter> to end')
I'm a beginner too. I know this solution is simplistic, but it works.
a=int(raw_input('Give a number'))
while True:
print a
userIn = (raw_input('Give another number or <cr> to end)'))
if not userIn:
break
b = int(userIn)
a = a + b

Categories