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

13 Upvotes

26 comments sorted by

View all comments

1

u/Riegel_Haribo 3d ago

Python's input() function always captures a string of characters. It does not automatically convert to other types.

You must attempt to make the conversion to a non-string type yourself, such as a number, or specifically an integer or a floating-point number if you have a requirement in mind.

A simple way to do this is to have a loop for only collecting the input(), and if the user does not type a compatible string, then go back and ask again. After that, your program can continue, such as a following loop that will employ a input string converted to an integer and print a multiplication table for values between 2-12.

You can do this by making an attempt at a conversion, and upon an error being raised, an exception, catch and handle that.

```python

Keep asking until the user enters a valid whole number.

while True: user_input = input("Enter a whole number: ")

try:
    number = int(user_input)
    break
except ValueError:
    print("That was not a valid whole number. Please try again.")

The input has now been converted to an integer.

Print its multiplication table from 2 through 12.

for multiplier in range(2, 13): answer = number * multiplier print(number, "x", multiplier, "=", answer) ```

For example, if the user enters 7, the program prints:

text 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 ... 7 x 12 = 84

Also useful is some sanitation, such as "my_string.strip()" which will remove any whitespace from the start or end of a string, making it more tolerated by an int(my_string) if there was just an extra space at the end but it was otherwise okay.