I am fairly new to Python. I wrote a program to take the user inputs which are service, the top-up time, the top-up amount, and exit or stay on the program.
Please review my code. And, can my code be organized? I think it looks a bit messy, maybe it can be shorter?
- First, I wrote everything under function, so I can restart the program later on.
- Second, I want to take user input about the service that they want to top up by limiting the choice of service to only 3 which are Green, Blue, or Red. If none of it, display "Try Again!, Wrong Service" otherwise, "Welcome to Top-up Service".
- Third, after passed service versification, the user can top up but limit to only 50,100,300,500,1000. Also, the user can only choose "How many times they want to top-up".
- Forth, after top-up, the list of top-up and sum of top-up is presented.
- Last, the user can choose to stay or exit the program. If stay, the program is restarted, if exit, the program is terminated.
Here is the code that I wrote
def main():
# Letting user choose a service
service = None
while service not in {"Green", "Blue", "Red"}:
service = input("Please enter Green, Blue or Red: ")
# Now service is either Green, Blue or Red
if service in {"Green", "Blue", "Red"}:
print("Welcome to Top-up Service")
else:
print("Try Again!, Wrong Service")
# Doing Top up(s)
top_list = []
n=int(input("How many times do you want to top up? "))
for i in range(1,n+1):
top_up = None
while top_up not in {50,100,300,500,1000}:
top_up = int(input("Please enter 50,100,300,500 or 1000: "))
# Now top_up is either 50,100,300,500 or 1000"
if top_up in {50,100,300,500,1000}:
top_list.append(top_up)
else:
print("Try Again!, Wrong Top-up")
# Show all top up(s) information & Sum all top up(s)
print("Top up(s) information : ", top_list)
print("Total top up(s): ", sum(top_list))
# Letting user choose to stay or exit
restart = input("Do you want to start again?,Y or else ").upper()
if restart == "Y":
main()
else:
print("Thank you for using our service")
exit()
main()
This is the example of output
Please enter Green, Blue or Red: o
Try Again!, Wrong Service
Please enter Green, Blue or Red: Blue
Welcome to Top-up Service
How many times do you want to top up? 2
Please enter 50,100,300,500 or 1000: 20
Try Again!, Wrong Top-up
Please enter 50,100,300,500 or 1000: 50
Please enter 50,100,300,500 or 1000: 500
Top up(s) information : [50, 500]
Total top up(s): 550
Do you want to start again?,Y or else n
Thank you for using our service