Ask coding questions

← Back to all posts
I need help please
isaac0702675 (4)

Can someone help me solve this. Its supposed to do this but i'm struggling.

Write a program that uses a while loop to request a certain type of information from the user. Example output as follows:

Enter your name: 5

This is not a name. Try again.

Enter your name: 5.0

This is not a name. Try again.

Enter your name: Brennan.

Hello, Brennan.

Commentshotnewtop
PDanielY (983)

Moved your post to ask since challenge is not for this post.

RobertoBean (37)

You are checking the type of the user input, but all input returned by input() is a str. If you want to see if a string contains a number, use str.isdigit().

Next, you wan't to use what's called a validation loop, which loops back to the input until the user enters a valid value. This is usually achieved with a while loop or a recursive function.

BD103 (18)

Please check @RobertoBean ‘S comment as the answer. @isaac0702675

isaac0702675 (4)

I did and it worked most of the way but when I put a decimal in the number it messed up. @BD103

RobertoBean (37)

@isaac0702675 just do name.replace('.', '').isdigit()

RobertoBean (37)

@isaac0702675 in the place of if name.isdigit():

Nemoiscool (45)

I think what you're looking for is testing whether or not the input is a string. This would be an easy solution, except that all inputs come out as strings. Thus, I would recommend using a try/except statement:

def checkname():
name = input("What is your name? ")
try:
float(name)
except:
print("Hi %s" % name)
return
print("That is not a name.")
checkname()

checkname()

in this example, it takes the user input and tries to convert it into a float. if it can't, then it assumes it is a string, in which case it is considered a name. So, it says Hi [name] and returns, exiting the recursive function loop. If it is able to convert it to a float, then it will skip the except statement and move on to the next bit of code, which tells the user that what they inputted is not a name, and recursively calls itself.