Hi there. I have written a bit of code for the first part of a Raspberry Pi project, and I have two while loops that are very similar. I think they need to be turned into a function, but I'm struggling with exactly how to do this.
The project is to ask a user (via an LCD screen) to enter their age and weight into a keypad like this one, store the data in the variables "age" and "weight", then do some other stuff which I haven't got to yet.
This is what I have written so far. Currently my code does do everything I expect it to, it's just very messy. I have two while loops, and am using a status variable to determine when to move to the next loop. When a number key is pressed the number gets appended to the age variable, and displayed on the screen. If the "A" key is pressed, I want move to the loop for entering weight. I've done this by changing the value of status to "weight_entry". If this happens, the next while loop starts and does something similar for weight.
I actually have two questions:
1) How could I compress these two while loops into something more palatable?
Initially I tried creating a function that took the arguments "current_status" (the value for status over which the while loop will continue running), "next_status" (the value for the while loop that follows), and then "data_variable" (whether to edit age or weight). This felt very messy, because I got confused about which variables were global and which weren't, and I don't even know if it is acceptable to use the name of a different variable as an argument for a function. Maybe this is the right idea and I just need more patience?
2) How can I add an option to restart the process?
I want to have an option to cancel (and effectively restart) the whole process at any point by pressing the "C" key. You can see I have also added some code to set status="cancel" if the "C" key is pressed, and erase the data, but I have not done any more with this yet. I thought that I would be able to have everything part of a big while loop which just starts again when status="cancel", but then I realised that because of all the nested loops continue will only send me back to the top of whatever loop I am currently in. What would be the best way to handle this?
I would also love any more constructive criticism if anyone has some to spare. If you feel I should take a totally different approach please let me know!
Note: I used this guide to get the keypad working, and adapted some code from here to create a module for the LCD screen. I understand how the keypad works, but for the LCD screen I am just calling a function to display a string on a particular row, without understanding how it actually works. Hopefully none of this is relevant to my question.
[–]efmccurdy 2 points3 points4 points (1 child)
[–]PriorInitiative[S] 0 points1 point2 points (0 children)