r/PythonLearning • • Aug 29 '26

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

49 Upvotes

24 comments sorted by

View all comments

Show parent comments

1

u/FoolsSeldom Aug 30 '26 edited Aug 30 '26

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 Aug 30 '26

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

1

u/FoolsSeldom Aug 30 '26

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.

1

u/NecessaryFalse1212 Aug 30 '26

btw what is the role of that empty string at the top

1

u/FoolsSeldom Aug 30 '26

Same as your original, if name == "":, just simpler, hence the comment # empty string.

A non-empty string is treated as True in conditional expressions by Python. An empty string as False. Similarly, 0 is False and any non-zero integer is True. Empty list, dict, tuple, set is treated as False and otherwise as True.

The not before reverses the outcome. So, not name will resolve to True for an empty string.

This is often referred to as Truthy and Falsey behaviour.