Jul-15-2017, 01:27 PM
You really want the else statement on the for. That is, if the for loop does not find anything, you want to print there is no such day. The old way to do this uses a boolean variable:
Python gives us a simpler way to do this, using that break statement. It allows us to put the else statement on the for loop. Then if the for loop finishes without a break statement, whatever code is in the else statement executes:
That solves the problem as you were looking at it, but the real problem is that you need a better data structure. A dictionary would be ideal here:
And while it may not be ideal, you can also solve this problem with a list:
day_found = False for number, name in days: if num_inp == number: print(name) day_found = True break if not day_found: print('There is no such day.')Notice the break statement. Once we find the correct day (if there is one), there's no point in processing further. So we use the break statement to break out of the loop.
Python gives us a simpler way to do this, using that break statement. It allows us to put the else statement on the for loop. Then if the for loop finishes without a break statement, whatever code is in the else statement executes:
for number, name in days: if num_inp == number: print(name) break else: print('There is no such day.')This set of code works the same as the previous set of code, but you don't have to track a separate variable.
That solves the problem as you were looking at it, but the real problem is that you need a better data structure. A dictionary would be ideal here:
day_dict = dict(days) if num_inp in day_dict: print(day_dict[num_inp]) else: print('There is no such day.')The first line creates a dictionary where the keys are the first item in each tuple (the numbers) and the values are the second item in each tuple (the day names). The if statement checks to see if num_inp is one of the keys (and thus a valid day). If it is valid, the next line pulls the value from the dictionary using the key (num_inp). If you're not following this, there is a tutorial on dictionaries in the tutorials section.
And while it may not be ideal, you can also solve this problem with a list:
days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'] print(days[num_inp])Now you get an error raised for an invalid day. You can either handle that error, pass it on, or prevent it by checking that the day number is between 0 and 6 before printing.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures