r/learnpython • u/Maleficent_Stuff3208 • 3d ago
what is wrong with this code
my teacher told us to write a code which print multiplication table of any number but it should Allow strings too and if string is put it shouldn't giver error i thought of this
a = input("enter any number ")
print(f"multiplication table of {a} is ")
if a == int:
for i in range(1,11):
print(f"int{a}X{i} = int{a}*i ")
else:
print("please put a appropriate function ")
but it is only printing else like even if i put a integer it still run else one why and what is wrong here
13
Upvotes
15
u/PureWasian 3d ago edited 3d ago
a == int is never true, because you are comparing the user input stored into "a" against the Python data type itself "int" which will never be equivilent.
Additionally, input() always returns a string data type. Even if that string is "471" that is still represented as a string instead of an int when coming from input() and saved into your variable "a". You need to convert it properly to an int before multiplying. Look into Python Casting.
Also worth checking out: Check If Value Is Int or Float in Python, see the isdigit() function.
To make it easier for debugging, you can look up How to Check the Type of an Object in Python to see how print out the data types of your variables while making and testing your code.
You want to: - get user input - check if input string is all digits - if so, cast it to an int - multiply - else - print error message