I have written python while loop that intercats with user input .
There is a table with dates columns.
The idea is that the user being asked if it wantes to remove cols from the table. if yes, then it needs to specified the column from a given list. it drop the column and asks again if the more columns need to be drop, until it gets the answer no and then it saves the table.
The problem: If the user wants to remove more than 1 column, the loop does not accept/ understand anymore the columns names.
the script:
x=input('Would you like to drop columns? ')
print(x)
if x=='yes':
print('The available columns will be print now. please select each time only one column.')
print('available columns are:',new_dates)
d_bye=input('date to drop:')
print(d_bye)
df.drop(d_bye,axis=1,inplace=True)
rep=input('do you have more columns to drop?')
print(rep)
while rep == 'yes':
d_bye=input('column to drop:')
df.drop(d_bye,axis=1,inplace=True)
print(rep)
if rep=='no':
break
else:
print('please type yes or no!')
print(rep)
df.to_csv(result_table)
'Process accomplished!'
The output of this in the specific case is:
Would you like to drop columns? yes
yes
he available columns will be print now. please select each time only one column.
available columns are: ['a','b','c','d']
date to drop: a
a
do you have more columns to drop? yes
yes
column to drop: c
yes
please type yes or no!
yes
columnn to drop: d
yes
please type yes or no!
yes
column to drop: no
as you can see, after it drops the first one (I checked and it does), for the 2nd and third it doesn't work. How can I make it frop more columns inside the while loop?
you've never asked the user to update his decision. You can use the new :=
operator.
while (rep := input("Enter the loop? (yes) ")) == "yes":
print("We are inside!")
print("Exit! Moving on...")
You can also notice that checking for negative input is unnecessary. You let the user the opportunity to enter the loop with yes
input. To exit the loop the user can simply [Enter]
or type any key besides yes