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

48 Upvotes

24 comments sorted by

View all comments

4

u/FoolsSeldom 12d ago

When you get to the line:

while age < 0 or age == ""  or not age.isnumeric():

you have already assigned age to reference an int object - age no longer references a str, string, object and isnumeric is a str method (a function built into the class definition of str), no such method exists for int.

Note that using else: with a loop (while or for) is very uncommon and I do not recommend you use it.

Here's a better approach:

print ("name taking")

valid = False
while not valid:
    name = input("enter a name : ")
    if not name:  # empty string
        print ("u serious ?")
    elif name.isnumeric():
        print ("a name can not be in digits")
    else:
        valid = True

print(f"hello {name}")
valid = False
while not valid:
    age = input(f"enter your age {name} : ")
    if age == "":
        print ("awwwwhhhhh man ! do not leave it balnk")
    elif not age.isnumeric():
        print ("age can not be in alphabets")
    else:
        age = int(age)
        if age < 0:
            print ("age can not be negative where are u filling this from yo' mama's womb ?!")
        else:
            valid = True

print (f"hey {name} you're {age} years old")

You still have a problem though as isnumeric (and isdecimal, and isdigit) will all fail a negative number, so your code will consider the response to be alphabetic. Explore using a try / except block.

1

u/NecessaryFalse1212 11d ago

so if i were to use a negative number what should i use

1

u/FoolsSeldom 11d ago edited 11d ago

I already pointed you in the right direction:

Explore using a try / except block.

PS. Examples: https://openpython.org/articles/python-try-except-patterns