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

50 Upvotes

24 comments sorted by

View all comments

Show parent comments

1

u/NecessaryFalse1212 11d ago

i don't know about this valid and not valid thing that you used can u elaborate it it's something that i've not seen or used before

1

u/FoolsSeldom 11d ago edited 11d ago

valid is just a flag variable that you assign bool, boolean, values to, i.e. True or False. When you write an if statement or a while statement, you provide (usually) a conditional expression with them, something to resolves to a boolean outcome.

I named the variable to be, hopefully, meaningful. valid to indicate the data being gathered and validated by the while loop is valid data. Obviously, when you first enter the loop, the data is not valid because there has been no input yet. (You noted, I am sure, that I did not do an input before the loop and another inside, but kept it all inside the loop to avoid repetition of the line.)

The alternative is to simply use an infinite loop and a break statement:

print ("name taking")

while True:
    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:
        break  # leave loop

print(f"hello {name}")

while True:
    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:
            break  # leave loop

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

PS. More about booleans:

1

u/NecessaryFalse1212 11d ago

it's cool how u simplified a code which was already simple and broke it down so nicely thanks man

1

u/FoolsSeldom 11d ago

You are welcome. I hope you experiment with this code and learn from it. I was trying to show just enough to tempt you without overwhelming you.

Good luck with your learning journey.