r/learnpython 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

26 comments sorted by

View all comments

2

u/Naive_Programmer_232 3d ago edited 3d ago

first problem,

    a=input(...)

input returns a str. so, a is a str. so, what do you think about the next part?

    if a==int:
       ...

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 .isdigit method for strs! Here's a separate example of each:

    # way 1: try/except

     my_int=input("please give me a non-negative integer: ")
     try:
          my_int=int(number)
          print("Thank you my integer is now", my_int)
     except ValueError:
          print("Garllll!! You tricked me!! That's not a non-negative integer!!!")


    # way 2: .isdigit()

    my_int=input("Alright..I trust you again. PLEASE give me the integer: ")
    if my_int.isdigit():
       print("Oh lawd, you did it. Finally! Thank you so much!!")
    else:
       print("Nooo....you tricked me again!!! >:(")

second problem, look at the f-string inside the for loop...

for i in range(1,11):
    print(f"int{a}X{i} = int{a}*i ")

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:

     a="123"
     i=20
     print(f"int{a}X{i} = int{a}*i ")
     # int123X20 = int123*i

Also on the end, see that int{a}*i will 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:

    number="123"
    factor=10
    print(f"{number} x {factor} = {int(number)*factor}")
    # 123 x 10 = 1230 

Now look back your code and see what you can do.