user2812028
user2812028

Reputation: 263

Python Validation with While Loops

So, I'm basically trying to make it so it won't proceed with a function unless you type yes/no after the inputs. This function will just add your inputs into a list. Basically I want the program to make you input a bunch of different numbers, it'll then at the end of inputting them ask you if you'd like to proceed. If you press yes I'd like it to proceed with the function but in my code I made it so each input is on a new input line, not in the same one so when I append it to the list I'm using a while statement.

If you need me to clarify more, please let me know.

Code:

next2=input("How many would you like to add? ")
print("")
count = 0
while count < int(next2):
    count = count + 1
    next3=input(str(count) + ". Input: ")
    add(next3)
print("")
check=input("Are you sure? (Y/N) ")
while check not in ("YyYesNnNo"):
    check=input("Are you sure? (Y/N) ")
if check in ("YyYes"):
    home()

Function:

def add(next2):
    numbers.append(next2)
    sort(numbers)

When you run this program it should look like this:

How many numbers would you like to add? "4"
1. Input: 4
2. Input: 3
3. Input: 2
4. Input: 1

Are you sure? (Y/N): Y

> append the inputs here

If they click no, it brings them to the home screen of the program which I already have setup.

This is what it does right now:

How many numbers would you like to add? "4" 1. Input: "4"

Append to list 2. Input: "3" Append to list 3. Input: "2" Append to list 4. Input: "1" Append to list Are you sure? (Y/N): "Y" Sort list and display

Upvotes: 1

Views: 2320

Answers (1)

hankd
hankd

Reputation: 649

It is appending them to the list as you enter them (before you ask if they are sure) because you are calling your add function inside the loop. You want to store them in some temporary structure, and only add them after you have checked that they are sure.

next2=input("How many would you like to add? ")
print("")
count = 0
inputs = []
while count < int(next2):
    count = count + 1
    next3=input(str(count) + ". Input: ")
    inputs += [next3]
print("")
check=input("Are you sure? (Y/N) ")
while check not in ("YyYesNnNo"):
    check=input("Are you sure? (Y/N) ")
if check in ("YyYes"):
    for userInput in inputs:
        add(userInput)
else:
    home()

Upvotes: 2

Related Questions