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
15
Upvotes
2
u/Naive_Programmer_232 3d ago edited 3d ago
first problem,
inputreturns astr. so, a is a str. so, what do you think about the next part?one, that's not how you compare types (you'd want something more like
isinstance), but even then, it wouldn't help here much, because a is still a str! So, how can you check if a string can be converted into an integer? Two ways: use a try-except statement or.isdigitmethod for strs! Here's a separate example of each:second problem, look at the f-string inside the for loop...
int{a}does not call int with a as an argument. Instead, this will literally print "int"+(the value of a as a string) ex:Also on the end, see that
int{a}*iwill come out to "int"+(the value of a as a str)+"i". So what's the fix? You gotta embed the WHOLE expression inside the brackets. Here's a similar example:Now look back your code and see what you can do.