PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, November 7, 2022

[FIXED] How to make menu using dict evaluation for small python guessing game

 November 07, 2022     dictionary, eval, function, menu, python     No comments   

Issue

menu = {
"1": "start_game()"
"2": "player_stats()"
"3": "high_scores()"
"0": "exit_game()"
}

So let's say if user inputs 1 in menu screen, I want to call start_game() function, I know there is other way to do this but just interested in this particular way because I think its neat.


Solution

Don't put strings in the dictionary, put references to the function.

menu = {
    "1": start_game,
    "2": player_stats,
    "3": high_scores,
    "0": exit_game
}

Then you can do:

choice = input("Please enter 1, 2, 3, or 0: ")
menu[choice]()

to execute the user's choice.



Answered By - Barmar
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

1,213,064

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © 2025 PHPFixing