0

How can I make the while loop stop when the x input is blank instead of it stopping when the word 'stop' appears?

This is what I did but with 'stop'. However if I change the condition to x!=' ', when I try to convert x into an int it breaks.

x=''
y=''
list=[]
while x!='stop':
    x=input('x input: ')
    y=int(input('y input: '))
    if x!='stop':
        list.append((int(x),y))
    
print('Stop')
print(list)

2 Answers 2

1

Try this

x=''
y=''
list=[]
while x!='stop':
    x=input('x input: ')
    y=int(input('y input: '))
    # break loop when x is empty string
    if x == '':
        break;
    if x!='stop':
        list.append((int(x),y))
    
    
print('Stop')
print(list)

break keyword breaks the loop if x is empty string. Validate variable x before casting it to int.

Sign up to request clarification or add additional context in comments.

2 Comments

@bench You should accept the answer by clicking the grey tick under the vote sign. If you feel like, you can give an upvote as well. Helps the rep of the person who answered.
Just did! I forgot to do it cause it made me wait 5 minutes
1

This should do what you want to do.

x='x'  
y='y'  
list=[]  
while x!='':  
    x=input('x input: ')  
    if x!='':  
        y=int(input('y input: '))  
        list.append((int(x),y))  
    
print('Stop')  
print(list)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.