Basic Polling System in Python
Submitted by Yorkiebar on Wednesday, May 21, 2014 - 03:22.
Introduction:
This tutorial is on how to create a simple, hardcoded polling system in Python.
Hardcoded?
Hardcoded is when something is coded directly in to the program, other terms include; hardcoding and hardcode. I would only recommend harcoding if the amount that needs to be hardcoded is very small (such as only a few options in this polling system).
This is similar to the use of loops. You could write a simple loop to do something five times, or you could write it out five times.
Variables:
Because this is all hardcoded, we first need a variable to hold the amoutn for each option...
TITLE, OPTION1 and OPTION2 are all in capitals because they are constants/finals and will not change throughout the programs runtime. The title will hold the question while OPTION1 and OPTION2 are the option names. opt1 and opt2 hold the current values of votes for each option.
Menu:
Next we are going to have to create a menu...
This menu takes input from the user. If the input is 1, a vote is added to 'opt1'/'OPTION1', the same for 2. If the user enters '3', they get the current total amount of votes for each option. Otherwise the message 'Failed' is printed.
Calling:
Finally we just need to call the 'main' function...
- TITLE = "Favourite Scripting Language?"
- OPTION1 = "Python"
- OPTION2 = "Visual Basic"
- opt1 = 0
- opt2 = 0
- def main():
- user = input(TITLE + ", 1 = " + OPTION1 + ", 2 = " + OPTION2)
- while (user != '0'):
- try:
- u = int(user)
- if (u == 1):
- opt1+=1
- elif (u == 2):
- opt2+=1
- elif (u == 3):
- print("Opt1: " + str(opt1) + ", Opt2: " + str(opt2))
- except:
- print("Failed")
- user = input(TITLE + ", 1 = " + OPTION1 + ", 2 = " + OPTION2)
- main()
Add new comment
- 260 views