Basic Polling System in Python

Submitted by: 
Visitors have accessed this post 539 times.

This tutorial is on how to create a simple, hardcoded polling system in Python.

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.

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.

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.

Finally we just need to call the 'main' function...

  1. main()

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.