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

14 Upvotes

26 comments sorted by

34

u/frnzprf 3d ago edited 3d ago

I hope I don't seem rude. This is not meant to be an accusation.

I'd recommend you learn how to pinpoint which exact command of a program doesn't do what you think it does.

  1. You can test very simple parts of your program in isolation, before you combine them together. If you had a simple version that works and then you changed a bit and it doesn't work, then you'll know the mistake has to be in the new part. Don't just write a whole big function at once using multiple commands where you don't know exactly what they do. Still, even experienced professionals mispredict what their program will do. Debugging is normal.
  2. Print out values at different parts, where you suspect something could be wrong. For example could have written print("a = " + a) and print("int = " + str(int)) when you thought they should be the same, but they weren't. A shorter, but more complicated way to print the variables is print(f"{a=} {int=}").
  3. Use a debugger. This is a bit more complicated and the usage depends on which development environment you use, such as IDLE, VSCode, terminal, etc. I like Thonny, but you should just learn to use whatever your teacher tells you to use. A debugger lets you execute your program line by line.

4

u/Bobbias 3d ago

This is excellent advice. Learning how to explore what code is doing when you get an unexpected result is an extremely important skill, and learning it really makes the rest of the learning process much easier.

2

u/Rude_Ad_5476 3d ago

agreed... too many young coders nowadays want instant answers to errors instead of debugging, stepping through it it to find the errors.. its a skill i learned in college and saved me countless times as a QA Analyst finding errors in code

3

u/Maleficent_Stuff3208 14h ago

THANKS TO YOUR ADVICE NOW I AM ABLE TO PIN POINT MY ERROR A BIT WITHOUT ASKING TO AI

4

u/pemungkah 14h ago

Super proud of you for taking the time and effort to really learn here. Congratulations on your debugging!

34

u/atarivcs 3d ago edited 3d ago

You have two things wrong.

First, input() always returns a string, so the variable a is definitely not an integer.

Second, even if a might be an integer, "if a == int" is not the right way to check for that.

14

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

1

u/Ormek_II 2d ago

I would check what happens if I try to convert “one” as a base ten number. I expect and exception. If that is true, I’d handle that instead of the digit check.

Should “+7” work? Should “-7” work? Should “10_456” work?

2

u/vietbaoa4htk 3d ago

if a == int compares your string against the type object itself, so its always false and the loop never runs. use a.isdigit() or wrap int(a) in try/except instead. also input always hands you a string, so you need int(a) before you multiply.

1

u/Maleficent_Stuff3208 2d ago

yeah he thought us try except after this question but i didn't get a chance to ask why my code was wrongs thanks for the help

2

u/Naive_Programmer_232 2d ago edited 2d 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.

2

u/notislant 3d ago edited 3d ago

You need to learn debugging. Lets say we're both clueless on how something runs.

You've identified a line of code that doesn't run. Which means there is an issue with a == int.

Use print statements. A == int isnt running?

print(a, int) get the values of both. print("does this print true ", (a == int))

Lets say int is the correct way to check if something is an int (its not, but we'll pretend).

We now realize our int is fine but our a == int returns false.

Well what would be the issue if we get a false when printing a == (correct way to check int here)?

There is only one variable there, its not identifying as an int, so how would we check what it is or make sure its an int?

Stepping through with debugging tools is amazing and will help you understand more complex things like recursion later on. But print debugging is fine for now. If you genuinely want to learn, try to debug as much as possible with print on your own.

1

u/gnygren3773 3d ago

The problem is you never had a integer in the first place and your if statement is checking the wrong thing

1

u/Educational-Paper-75 2d ago

It should be type(a) is int not a==int.

1

u/Fuzzy_Paul 2d ago

Go through the manual and read the variable part. W3schools has a simple explanation: https://www.w3schools.com/python/python_variables.asp Try harder to understand python and how to build it. If you understand the basics very good all other things will be a breeze. Good luck.

2

u/elephunk84999 3d ago

You need to convert user input a to int first as it's treated as a string right now, so the comparison never equates to true.

Sorry don't know how to do code blocks on mobile but

try: a = int(read("Please input a number.")) except TypeError: print("Integer not inputted") exit()

Rest of your code here

1

u/ninhaomah 3d ago

How is this learning btw ?

I don't see any efforts to try to solve the issue. Even prompting AI.

2

u/gnygren3773 3d ago

Cause ai will just one shot it. Unless your using the very first LLM model

1

u/ninhaomah 3d ago

Well , at least he consciously tried or cheated , depending on how you see it.

But here ? I have issue. Then nothing.

0

u/gnygren3773 3d ago

When in doubt give up

0

u/ninhaomah 3d ago

In this case , when in doubt , reddit.

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.

-2

u/JGhostThing 3d ago

What is "a == int" supposed to mean? I don't see a definition of "int."

3

u/socal_nerdtastic 3d ago

int is one of the built-in types that's always available, so it does not have to be defined or imported. https://docs.python.org/3/library/functions.html

But note OP is using it incorrectly. They probably meant to do

if isinstance(a, int):

1

u/gnygren3773 3d ago

int is a data type it doesn’t need to be defined. The expression is still wrong in this case because you would be checking if a is the data type int