0

I'm very new to programming and python. I'm writing a script and I want to exit the script if the customer type a white space. questions is how do I do it right? This is my attempt but I think is wrong

For example

userType = raw_input('Please enter the phrase to look: ')
userType = userType.strip()

line = inf.readline()
while (userType == raw_input)
    print "userType\n"

    if (userType == "")
        print "invalid entry, the program will terminate"
        # some code to close the app
Andreas Florath
  • 4,418
  • 22
  • 32
NewLearner
  • 213
  • 2
  • 6
  • 16

4 Answers4

3

I know this is old, but this may help someone in the future. I figured out how to do this with regex. Here is my code:

import re

command = raw_input("Enter command :")

if re.search(r'[\s]', command):
    print "No spaces please."
else:
    print "Do your thing!"
2

The program you provided is not a valid python program. Because you are a beginner some small changes to you program. This should run and does what I understood what it should be.

This is only a starting point: the structure is not clear and you have to change things as you need them.

userType = raw_input('Please enter the phrase to look: ')
userType = userType.strip()

#line = inf.readline() <-- never used??
while True:
    userType = raw_input()
    print("userType [%s]" % userType)

    if userType.isspace():
        print "invalid entry, the program will terminate"
        # some code to close the app
        break
Andreas Florath
  • 4,418
  • 22
  • 32
0

After applying strip to remove whitespace, use this instead:

if not len(userType):
     # do something with userType
else:
     # nothing was entered
octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
0

You could strip all whitespaces in your input and check if anything is left.

import string

userType = raw_input('Please enter the phrase to look: ')
if not userType.translate(string.maketrans('',''),string.whitespace).strip():
      # proceed with your program
      # Your userType is unchanged.
else:
      # just whitespace, you could exit.
Community
  • 1
  • 1
Senthil Kumaran
  • 54,681
  • 14
  • 94
  • 131