Hi
I’m trying to write a display_data function which prints the first 5 rows of a data frame
acc to user input…further prints the next 5 rows acc to user input and continues until the user says no…
How do i deal with the case when the user inputs a string other than yes or no?
should i add a condition for that?
also my code is not handling the exception when user inputs an integer
code:(the if row_data ==“yes” is not inside the first while loop, try and except block is inside)
def display_data(df):
while True:
try:
row_data = str(input(“Would you like to see raw data form the table?(type yes or no):”)).lower()
break
except:
print(“That’s not a valid input…please try again”)
if row_data == "yes":
print(df.iloc[:5])
c = 5
while c < len(df.index):
try:
row_next_data = str(input("Would you like to see 5 more rows of data?(type yes or no):")).lower()
if row_next_data == "yes":
print(df.iloc[c-5:c])
c += 5
elif row_next_data == "no":
break
except:
print("That's not a valid input...please try again")
sorry…this is not a part of any mission…I’ll make sure to include the format for code…
if i change the line of the code to x = int(input(“enter a number:”)) (say i want a number)
then it checks for the input until the user enters a valid integer unlike the str case which i mentioned earlier…why?
First, the try clause (the statement(s) between the try and exceptkeywords) is executed.
If no exception occurs, the except clause is skipped and execution of the try statement is finished.
If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try statement.
If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no handler is found, it is an unhandled exception and execution stops with a message as shown above.
so in the code that I mentioned earlier…
I need to add a seperate condition for the case when the user inputs a string other than yes or no…right?
bcz it does’nt generate any error…
Yes, you need to further process this condition. But your code already has everything you need for this, you just need to add else,in which you will handle all input cases except yes and no
You will receive the following
if row_data == "yes":
print(df.iloc[:5])
c = 5
while c < len(df.index):
try:
row_next_data = str(input("Would you like to see 5 more rows of data?(type yes or no):")).lower()
if row_next_data == "yes":
print(df.iloc[c-5:c])
c += 5
elif row_next_data == "no":
break
else: # other case
print("That's not a valid input..only 'yes' or 'no'")
except:
print("That's not a valid input...please try again")