This question already has answers here:
Comparing numbers give the wrong result in Python
(4 answers)
Closed 4 years ago.
Very new to programming and decided to get into Python. Sorry in advance if this question is very simple. Experimenting with functions. Got this to run with no errors, but doesn't always work.
I'm pretty sure I'm doing the string replacement wrong? Any explanation or advice would be great.
Noticed it wasn't working when I was comparing a single digit number to a multi digit.
def bigger(a, b):
if a > b:
print ("%s is bigger" % a)
elif a == b:
print ("They are both equal!")
else:
print ("%s is bigger" % b)
a = input("Pick a number: ")
b = input("Pick another number: ")
bigger(a, b)
input by default return String. You need to convert it to numbers. Change the int into float or double, if dealing with decimal numbers
def bigger(a, b):
if int(a) > int(b):
print ("%s is bigger" % a)
elif a == b:
print ("They are both equal!")
else:
print ("%s is bigger" % b)
a = input("Pick a number: ")
b = input("Pick another number: ")
bigger(a, b)
a = input("Pick a number: ")
b = input("Pick another number: ")
input() is always represented as a string and not an integer so in order to run comparisons like if a > b you must first convert it to an integer, like this:
a = int(input("Pick a number: "))
b = int(input("Pick another number: "))
The reason your program works is because Python is comparing the individual sizes of your strings. So "32" starts with a 3 while "122" starts with a 1 so 32 is larger.
>>> '122'<'32'
True
>>> '44'>'1333333'
True
Related
This question already has answers here:
Python excepting input only if in range
(3 answers)
Closed 2 years ago.
what's the easiest way to limit this code integer input to a single digit?
num = ["First","Second","Third"]
num_list = []
for a in num:
x = int(input(f"Enter Your {a} number: "))
num_list.append(x)
for i in range(0,3):
for j in range(0,3):
for k in range(0,3):
if(i!=j&j!=k&k!=i):
print(num_list[i],num_list[j],num_list[k])
just a quick fix
def get_single_digit_input():
while True:
a = input('please enter number')
if not a.isnumeric():
print('please enter single digit Numeric only')
continue
a = int(a)
# your logic is here
if a<=9 and a>=0:
return a
else:
print('please enter single digit Numeric only')
a = get_single_digit_input()
You can check using a while statement. If the input is not a single digit, force it back to the input statement. Also you want to check if the input is a digit and not an alphabet or special character.
Here's a way to do it: I am using the walrus operator in python 3.9
while len(x:=input('Enter a single digit :')) > 1 or (not x.isnumeric()):
print ('Enter only a single digit')
print (x)
If you are using python < 3.9, then use this.
x = ''
while True:
x = input ('Enter a single digit :')
if (len(x) == 1) and (x.isnumeric()): break
print ('Enter only a single digit')
print (x)
This question already has answers here:
How do I determine if the user input is odd or even?
(4 answers)
Closed 4 years ago.
I tried to make a odd/even 'calculator' in python and it keeps popping up errors. Here's the code:
def odd_even():
print("Welcome to Odd/Even")
num = input("Pick a number: ")
num2 = num/2
if num2 == int:
print("This number is even")
else:
print("This number is odd")
Id like to know whats causing the errors and solutions to them
There is an error in the line: num = input("Pick a number: ")
Because input method always returns a String,so you should convert it into int to performs the integer operation
The currect code is:
num =int( input("Pick a number: "))
you can't do math with strings convert it to int
try:
num = int(input("Pick a number: "))
except ValueError:
print('This is not a number!')
return
import random
def mathquiz():
name = str(input("Whats your name?:"))
a = random.randint(1,10)
b = random.randint(1,10)
c = (a * b)
timesby = ("*")
print('what is', + a, timesby, + b)
ans = input("Enter your answer here")
if ans == c:
print("Thats correct")
else:
print ("Incorrect the answer is", + c)
I am trying to create a maths quiz using random numbers and just say the question is 10 * 10 if i enter 100 if will say i have the wrong answer. Everything else works fine just this bit is wrong.
ans and c are of different types. Since you read ans from the console, it is a string, and not a number, while c is calculated through multiplying 2 numbers, so it is a number. there are 2 ways to fix this, convert ans to an int with int(ans) instead of ans, or convert c to a string with str(c) instead of c.
I was writing a complex program and I was getting an if statement...
(this isn't the complex code, this is just an example)
print("The 24 game will give you four digits between one and nine")
print("It will then prompt you to enter an ewuation one digit at a time.")
import random
a = random.randint(1,9)
b = random.randint(1,9)
c = random.randint(1,9)
d = random.randint(1,9)
print(a,b,c,d)
f=input("Enter one of the above numbers")
if f==a:
print("ok")
elif f != a:
print("No")
No matter what I type it always outputs "NO".
It would work after converting the user input string to a number:
if int(f) == a:
print("ok")
I've just started studying Python, and I'm an absolute newbie.
I'm starting to learn about functions, and I wrote this simple script:
def add(a,b):
return a + b
print "The first number you want to add?"
a = raw_input("First no: ")
print "What's the second number you want to add?"
b = raw_input("Second no: ")
result = add(a, b)
print "The result is: %r." % result
The script runs OK, but the result won't be a sum. I.e: if I enter 5 for 'a', and 6 for 'b', the result will not be '11', but 56. As in:
The first number you want to add?
First no: 5
What's the second number you want to add?
Second no: 6
The result is: '56'.
Any help would be appreciated.
raw_input returns string, you need to convert it to int
def add(a,b):
return a + b
print "The first number you want to add?"
a = int(raw_input("First no: "))
print "What's the second number you want to add?"
b = int(raw_input("Second no: "))
result = add(a, b)
print "The result is: %r." % result
Output:
The first number you want to add?
First no: 5
What's the second number you want to add?
Second no: 6
The result is: 11.
You need to convert the strings to ints to add them, otherwise + will just perform string concatenation since raw_input returns raw input (a string):
result = add(int(a), int(b))
You need to cast a and b to integer.
def add(a, b):
return int(a) + int(b)
This is because raw_input() returns a string and + operator has been overloaded for strings to perform string concatenation. Try.
def add(a,b):
return int(a) + int(b)
print "The first number you want to add?"
a = raw_input("First no: ")
print "What's the second number you want to add?"
b = raw_input("Second no: ")
result = add(a, b)
print "The result is: %r." % result
The resultant output is as follows.
>>>
The first number you want to add?
First no: 5
What's the second number you want to add?
Second no: 6
The result is: 11
Converting the string inputs to int, uses the + operator to add the results instead of concatenating them.
.
**
**>raw_input always returns string. You need to convert the strings to int/float datatype to add them, otherwise addition will perform string concatenation.
You can check the type of the variables yourself : print(type(a), type(b))
Simply tweak your function**
**
def add(a, b):
return int(a) + int(b)
OR
def add(a, b):
return float(a) + float(b)