fiona
fiona

Reputation: 89

While Loop stop with blank input

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)

Upvotes: 0

Views: 1118

Answers (2)

talismanbrandi
talismanbrandi

Reputation: 161

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)

Upvotes: 1

jastor_007
jastor_007

Reputation: 451

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.

Upvotes: 1

Related Questions