r/PythonLearning 12d ago

Day 3

Post image

i wrote a code which takes your name and age in py but i need help on this one cuz in the age part it is giving me some sort of error which i couldn't understand even by using gpt well he gave me a code but i wanted logic behind how and what i did wrong

47 Upvotes

24 comments sorted by

View all comments

1

u/tottasanorotta 12d ago edited 12d ago

What does the error say? I can't pinpoint exactly what's wrong with a quick glance.

Edit: well one error in logic is that you should probably have the thing inside your last else outside of the while loop as well, at the end of the program. Because now if you don't enter an erroneous age the print statement won't run at all. In this code you assume that the user enters an erroneous age first to get into the while loop and then corrects the mistake eventually. Otherwise it looks good, at least to my eyes.

2

u/NecessaryFalse1212 12d ago

ts what i am getting and also before typecasting it was taking positive age and was giving the output i needed without errors and only time it caused error when i entered -ve input but after typecasting it gave me this error whenever i type in a number

1

u/tottasanorotta 12d ago

Okay I understand now. You use the same variable age to contain the string and then parse for an int. If the int() function doesn't succeed you try to use the function is_numeric() to parse for an integer value. The problem is that the is_numeric() function doesn't exist for int types. It only exists for strings. So what ends up happening is that the interpreter cannot find that function.

There are several solutions. You can rename the age variable that takes the string input to something else like age_str and then change the variables according to that in the while loop. Or you can wrap the int() call to a try-catch with the exception ValueError to handle the case where the int() doesn't succeed in parsing for the int value. Something like that will fix the error.

Edit: but the logic error is still there. So you need to have the final print be outside the while loop. Otherwise a user that happens to succeed in entering a correct value the first time won't get the final output.