Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Question on input()

Whaddup, peoples. I put together this small name reversing script, but a user can move through the script without inputting any info (by just hitting return on their keyboard). How would I prevent this??

name = input("What's your name? ").upper()
scramble = input("Did you say {}? (y/n)".format(name[::-1])).lower()
if scramble == "y":
  print("Good, I'm never wrong!")
else: 
  print("That's not true!! I know it is you {}!!".format(name[::-1]))

1 Answer

Enclose the statement in a while block to check for the empty string:

name = input("What's your name? ").upper()
while(name == ""):
  print("you're dumb, try again")
  name = input("What's your name? ").upper()
scramble = input("Did you say {}? (y/n)".format(name[::-1])).lower()
if (scramble == "y"):    #added missing parenthesis here
  print("Good, I'm never wrong!")
else: 
  print("That's not true!! I know it is you {}!!".format(name[::-1]))

Python automatically parses command-line input to a string so just hitting enter only gives you an empty string.

Absolutely --thanks!