Basic Polling System in Python

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...
  1. TITLE = "Favourite Scripting Language?"
  2. OPTION1 = "Python"
  3. OPTION2 = "Visual Basic"
  4. opt1 = 0
  5. opt2 = 0
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...
  1. def main():
  2.         user = input(TITLE + ", 1 = " + OPTION1 + ", 2 = " + OPTION2)
  3.         while (user != '0'):
  4.                 try:
  5.                         u = int(user)
  6.                         if (u == 1):
  7.                                 opt1+=1
  8.                         elif (u == 2):
  9.                                 opt2+=1
  10.                         elif (u == 3):
  11.                                 print("Opt1: " + str(opt1) + ", Opt2: " + str(opt2))
  12.                 except:
  13.                         print("Failed")
  14.                 user = input(TITLE + ", 1 = " + OPTION1 + ", 2 = " + OPTION2)
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...
  1. main()

Add new comment