1

I have a problem in which users can input spaces or nothing and still pass through the program, how do I go about preventing this? I am still a beginner at python.

def orderFunction(): # The function which allows the customer to choose delivery or pickup
    global deliveryPickup
    deliveryPickup = input("Please input delivery or pickup: d for delivery p for pickup")
    if deliveryPickup == "d": 
        global customerName
        while True:
            try:
                customerName = (input("Please input your name"))
                if customerName == (""):
                    print("Please input a valid name")
                else:
                    break
        global customerAddress
        while True:
            try:
                customerAddress = (input("Please input your name"))
                if customerAddress == (""):
                    print("Please input a valid Address")
                else:
                    break
        global customerPhnum
        while True: 
            try: 
                customerPhnum = int(input("Please input your phone number"))
            except ValueError:
                print("Please input a valid phone number")
            else:
                break
            print("There will also be a $3 delivery surcharge")
    elif deliveryPickup == "p": 
        customerName = (input("Please input your name"))
        if customerName == (""):
            print("Please input a valid name")
            orderFunction()

    else:
        print("Please ensure that you have chosen d for Delivery or p for Pickup")
        orderFunction()

orderFunction()   

Here is my attempt at doing this but I get all kinds of unindent and indent errors at the moment and I think my while loops are probably wrong.

Essentially if I input a space or hit enter into one of the customer inputs (customerName for instance) it gets stored. This needs to prevented and I have tried to fix it by using while loops which obviously haven't worked.

Hopefully someone has a solution to this problem

Many Thanks.

Ilyas Rosslan
  • 25
  • 1
  • 4
  • Try checking out [string templates](https://docs.python.org/3/library/string.html#template-strings). They're incredibly useful for getting input such as customer information. – Noah M. Aug 09 '18 at 10:21

8 Answers8

0

Try using a regular expression that checks if any character between "A-Z" has been inserted, if not, give an error

King
  • 827
  • 2
  • 10
  • 20
0

Instead of using input right away you can make a function similar to this one that will only allow valid inputs.

You can use this valid_input function instead of input.

def valid_input(text):
    not_valid = True
    res = ''
    while not_valid:
        res = input(text)
        if res.split():  # if text is empty or only spaces, this creates an empty list evaluated at False
            not_valid = False
    return res

here the check is pretty simple: every text made out of nothing or spaces won't be allowed and we will keep asking for the same input until a valid information is given.

I made this code simple just so you get a general idea. But you can change the validation test to your liking and maybe also output a warning saying why the input wasn't allowed so the person knows what to do. You can do more advanced validation with regex, and maybe you need a minimum text length etc...

smagnan
  • 1,197
  • 15
  • 29
0

You have indent error because you have a try statement without the corresponding except. You need both to make it work (as you did in the Phone number section).

Here is a link to the try/except: docs

Also, you can check if a string is empty as detailed in this answer.

So for example you want to write:

        try:
            customerName = input("Please input your name")
            if not customerName:
                print("Please input a valid name")
            else:
                break
        except ValueError:
                print("Please input a valid name")

Although the above seems a bit redundant, so you might want to raise an exception if the customer name is empty, catch the exception in the except block, print the warning and return error (or something else).

        try:
            customerName = input("Please input your name")
            if not customerName:
                raise ValueError
        except ValueError:
            print("Please input a valid name")
        else:
            break
FLab
  • 7,136
  • 5
  • 36
  • 69
0

What you are looking for is the str.strip method that remove trailing whitespace in strings. Also I think try is not particularly suited for your needs here.

customerName = input("Please input your name")
while not customerName.strip():
    customerName = input("Please input a valid name")

for the phone number I would not convert to integer because if the phone number starts with zeros, they will not be stored.

Alexis
  • 337
  • 1
  • 12
0

The while loops are a decent solution, you just need to add more checks to your if statements.

First, you don't need a try statement on the top two loops. Don't use a try statement unless you're expecting an error, which you need to handle with an except statement, like you do in the bottom while loop.

Then you just need to add more conditions to your top two loops, I don't know exactly what you want to prevent, but you could try checking the length of the input, also see this answer for an interesting method: https://stackoverflow.com/a/2405300/8201979

strava
  • 765
  • 6
  • 14
0

Try adding another while true for pick and delivery option so that it can prevent taking other inputs

Aadhya Sharma
  • 25
  • 1
  • 1
  • 6
0

you don't need any of those try/excepts (which are broken anyway).

Its difficult to figure out what you're trying to do, are you trying to raise an exception if an empty string is passed, or request another input from the user? You seem to be half implementing both at the moment.

If its the latter, something like this would work.

def func(fieldname):
    while True:
        val = input("Please input your {}".format(fieldname))
        if val.strip() != "":
            break
        else:
            print("Please input a valid {}".format(fieldname))
    return val

delivery_pickup = input("Please input delivery or pickup: d for delivery p for pickup")

if delivery_pickup == "d":
    customer_name = func("name")
    address = func("address")
    phone_number = func("phone number")
Louis Byrne
  • 51
  • 1
  • 4
  • It would be cleaner to put your condition directly in the while rather than manually break. Note: `if val.strip() != ""` is equivalent to `if val.strip()` because empty strings behave as `False` in conditions. – Alexis Aug 09 '18 at 11:09
0

.strip() removes all tabs or spaces before and after a string. Meaning all spaces == empty string. All tabs == empty string. So all you have to check if the length of that string != 0 or the string is not empty. Just use an infinite loop to keep on forcing the right input.

Also as a tip, you don't have to limit yourself into one function. Here's a working code below.

def getNonBlankInput(message, error_message):

    x = input(message)
    while len(x.strip()) == 0:
        x = input(error_message)

    return x

def getValidIntegerInput(message, error_message):

    msg = message
    while(True):
        try: 
            x = int(input(msg))
            break
        except ValueError:
            msg = error_message

    return x


def orderFunction(): # The function which allows the customer to choose delivery or pickup
    global deliveryPickup
    global customerName
    global customerAddress
    global customerPhnum

    deliveryPickup = input("Please input delivery or pickup: d for delivery p for pickup")

    if deliveryPickup == "d": 
        customerName = getNonBlankInput("Please input your name: ", "Please input a valid name: ")
        customerAddress = getNonBlankInput("Please input your address: ", "Please input a valid address: ")
        customerPhnum = getValidIntegerInput("Please input your phone number: ", "Please input a valid phone number: ")
        print("There will also be a $3 delivery surcharge")
    elif deliveryPickup == "p": 
        customerName = getNonBlankInput("Please input your name: ", "Please input a valid name: ")
    else:
        print("Please ensure that you have chosen d for Delivery or p for Pickup")
        orderFunction()

orderFunction() 
Franrey Saycon
  • 647
  • 1
  • 5
  • 18
  • Do you have a way to make sure the phone number isn't a negative integer? – Ilyas Rosslan Aug 09 '18 at 11:00
  • `customerPhnum > 0` will do, altough i do not think that intergers are a particularly good representation for phone numbers. – Alexis Aug 09 '18 at 11:03
  • Also in Python an empty string behaves as `False` in conditions. Therefore `while len(x.strip()) == 0` can be replaced with `while not x.strip()` – Alexis Aug 09 '18 at 11:04
  • okay, I sorta understand but where do I place the customerPhnum > 0? – Ilyas Rosslan Aug 09 '18 at 11:10
  • you should place it where you want to make sure the phone number is not negative. – Alexis Aug 09 '18 at 11:12
  • 1
    0 is false and > 0 is true in python as well. Alexis is right. In the real world phone numbers are strings since people sometimes add + or any other symbols along with their phone number. – Franrey Saycon Aug 09 '18 at 11:12
  • @IlyasRosslan you may use `abs()` instead to force all numbers to be converted positive. `abs(int(input(msg)))` in getValidIntegerInput. – Franrey Saycon Aug 09 '18 at 11:14
  • yes, also they might type something like 000-33-456-... some country use paranthesis. In France we put space between every two digits ... – Alexis Aug 09 '18 at 11:17