Learning python? It’s an incredible programming language to have in your tool belt.
This project is inspired by an early example from Automate The Boring Stuff with Python.
1. Flow Control
This python project is to impliment this flow chart:
Let’s write the steps is psuedoe code:
- Ask if it’s raining?
- If no, go outside.
- If yes, ask if there’s an umbrella?
- If umbrella no, wait and ask if raining again.
- If umbrella yes, go outside.
2. While Loop
Let’s start with the outside variable and it’s while loop.
outside = False while outside == False: # Other code goes here. print('Go outside.') exit()
As all paths lead to outside, it makes sense for the program to check if the user can go outside or not.
As long as outside is set to False, the user isn’t able to go out. But once other conditions are met and outside is True, then the program ends.
3. Input Validation
Let’s make a simple input validation when asking if there’s rain or not. This way the user can’t put in anything but what is expected.
While rain isn’t equal to y or n, continue asking the same question.
rain = 0 while (rain != 'y' or rain != 'n'): rain = input('Rain? y/n ') break if rain == 'y': # More code goes here elif rain == 'n': outside = True
We’ll use this same input validation for our other questions that require user input.
If there is rain, the program will continue asking questions. But if there’s no rain, then outside is set to True and will break the original while loop.
4. If Else Statements
Let’s add the last variable, umbrella.
umbrella = 0 if rain == 'y': print('Get an umbrella.') while (umbrella != 'y' or umbrella != 'n'): umbrella = input('Umbrella? y/n ') break if umbrella == 'n': print('Wait a while.') elif umbrella == 'y': outside = True elif rain == 'n': outside = True
Depending on the users input yes or no, either it will tell them to wait and then go back to the rain question or it will end the main while loop.
5. Failed Attempts
Just for a bit of fun, here are two of my failed attempts on the road to figuring out this program.
rain = input('Is it raining? y/n ') while rain == 'y': print(' if rain == 'n': print('Go outside!') else: break
raining = input('Is it raining? y/n ') if raining == 'y': print('It\\'s raining!') umbrella = input('Do you have an umbrella? y/n ') if umbrella == 'n': print('Wait a while.') print('Time passes...') raining = input('Is it raining? y/n ') if raining == 'y': print('Wait a while, again.') else: print('Go outside.') else: print('Go outside.') else: print('''It\\'s not raining! Go outisde!''')
If you have any feedback, please send me a message via Twitter.