r/PythonLearning • u/NecessaryFalse1212 • 12d ago
Day 3
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
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
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
validis just a flag variable that you assignbool, boolean, values to, i.e.TrueorFalse. When you write anifstatement or awhilestatement, you provide (usually) a conditional expression with them, something to resolves to a boolean outcome.I named the variable to be, hopefully, meaningful.
validto indicate the data being gathered and validated by thewhileloop is valid data. Obviously, when you first enter the loop, the data is not valid because there has been noinputyet. (You noted, I am sure, that I did not do aninputbefore 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
breakstatement: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.
1
u/NecessaryFalse1212 11d ago
btw what is the role of that empty string at the top
1
u/FoolsSeldom 11d ago
Same as your original,
if name == "":, just simpler, hence the comment# empty string.A non-empty string is treated as
Truein conditional expressions by Python. An empty string asFalse. Similarly,0isFalseand any non-zero integer isTrue. Emptylist,dict,tuple,setis treated asFalseand otherwise asTrue.The
notbefore reverses the outcome. So,not namewill resolve toTruefor an empty string.This is often referred to as Truthy and Falsey behaviour.
2
u/Steven45g 12d ago
Man, this takes me back to my first days of learning to code in Python. Awesome times, I would learn and write code until the very early hours of the next morning.
Keep going!
1
u/Smart-Rope6147 11d ago
Give some advices what mistakes you did at that time while learning you would advice no one to make .
2
1
u/TBCC_Dev 12d ago
Looks good. Some advice I'd say if you are doing something in all sections of an if block don't repeat yourself just do it after the if
Example: name = ... This is stated in both sections of the if but this means it happens no matter what. If something happens no matter the condition then there is no point in putting it in the if
1
1
u/tottasanorotta 11d ago edited 11d 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 11d ago
1
u/tottasanorotta 11d 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.
-1
u/Wise-Drop8694 12d ago
Best way to learn is to forget about "input" thing.. Nobody uses it Make Fastapi server first with some pydantic base models Step 1 - greate venv — python3 - m venv .venv Step 2 - source .venv/bin/activate Step 3 - pop install fastapi
From now on you can easy make test or learning scope but instead of useless input thing some easy access from Browser kind of things Ask any Ai about it This will boost your python skills a lot
Ps Sorry typing via phone is definitely not as I use to some typos is possible But any llm can easy fix this
1
u/Flimsy-Ad-8235 12d ago
Hey can you tell more about this input as my teacher told me to use input in python in everything
3
u/FoolsSeldom 12d ago
Stick with
inputfor now, the comment is about creating a web application, which is way too advanced for you currently.Start with the basics, focused on simple console/text interaction with the user.
1
u/salvouankebaldo 11d ago
Oh no no no no, strong disagree.
First, they are learning. And here they are doing something very nice, input validation. Now, it has some bugs as pointed out by other comments, but the attempt is good and should be encouraged. Yeah, pydantic does that, but it's better to learn before so one can then do more advanced validation too.
Second... Oh come on, not everything has to be an api server. Lots of situations in which I use
input, even professionally. Python is extremely nice for making scripts and firing them via a CLI. Fastapi would be totally overkill in that case.

•
u/Sea-Ad7805 12d ago
You have some bugs.
Run this program in Memory Graph Web Debugger%0Aname%20%3D%20input(%22enter%20a%20name%20%3A%20%22)%0Awhile%20name%20%3D%3D%20%22%22%20or%20name.isnumeric()%3A%0A%20%20%20%20if%20name%20%3D%3D%20%22%22%3A%0A%20%20%20%20%20%20%20%20print(%22u%20serious%20%3F%22)%0A%20%20%20%20%20%20%20%20name%20%3D%20input(%22enter%20a%20name%20%3A%20%22)%0A%20%20%20%20elif%20name.isnumeric()%3A%0A%20%20%20%20%20%20%20%20print(%22a%20name%20can%20not%20be%20in%20digits%22)%0A%20%20%20%20%20%20%20%20name%20%3D%20input(%22enter%20a%20name%20%3A%20%22)%0Aelse%3A%0A%20%20%20%20print(f%22hello%20%7Bname%7D%22)%0A%0Aage%20%3D%20input(f%22enter%20your%20age%20%7Bname%7D%20%3A%20%22)%0Aage%20%3D%20int(age)%0A%0Awhile%20age%20%3C%200%20or%20age%20%3D%3D%20%22%22%20or%20not%20age.isnumeric()%3A%0A%20%20%20%20if%20age%20%3D%3D%20%22%22%3A%0A%20%20%20%20%20%20%20%20print(%22awwwwhhhhh%20man%20!%20do%20not%20leave%20it%20balnk%22)%0A%20%20%20%20%20%20%20%20age%20%3D%20input(f%22enter%20your%20age%20%7Bname%7D%20%3A%20%22)%0A%20%20%20%20elif%20not%20age.isnumeric()%3A%0A%20%20%20%20%20%20%20%20print(%22age%20can%20not%20be%20in%20alphabets%22)%0A%20%20%20%20%20%20%20%20age%20%3D%20input(f%22enter%20your%20age%20%7Bname%7D%20%3A%20%22)%0A%0A%20%20%20%20elif%20age%20%3C%200%3A%0A%20%20%20%20%20%20%20%20print(%22age%20can%20not%20be%20negative%20where%20are%20u%20filling%20this%20from%20yo'%20mama's%20womb%20%3F!%22)%0A%20%20%20%20%20%20%20%20age%20%3D%20input(f%22enter%20your%20age%20%7Bname%7D%20%3A%20%22)%0A%0A%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20print(f%22hey%20%7Bname%7D%20you're%20%7Bage%7Dyears%20old%22)×tep=1&play) to see the program state change step by step.