Any reason why my Python code is not showing up? - python

I am learning how to code in Python and using the IDLE, I have put in this code, however when I hit F5, nothing happens... no output occurs.
Is this due to maybe the fact that the code I have put in doesn't need an output? Or maybe I am saving it wrongly. Would love to know the reason as it is slightly upsetting.
X = "X" #This is to indicate one piece of the game
O = "O" #this is to indicate another piece of the game
EMPTY = "" # an empty square on the board.
TIE = "TIE" #represents a tie game
NUM_SQUARES = "9" #number of squares on the board
def display_instruct(): #this is a function with the name display_instruct.
"""display game instructions."""
print \
""" Welcome to the greatest challenge of all time: Tic-tac toe. This would be a showdown betweene your human brain
and my silcon processor You will mkae your move known by entering a number
0 | 1 | 2
---------
3 | 4 | 5
---------
6 | 7 |8
Prepare yourself, human. The ultimate battle is about to begin. \n """
def ask_yes__no(question):
"""Ask a yes or no question"""
response = None
while response not in ("y", "n"):
response = raw_input(question).lower()
return response
#this produces a function. It receives a question and thenn responds with an answer which is either yes or not
def ask_number(question, low, high):
"""Ask for a number within the range"""
response = None
while response not in range(low, high):
response - int(raw_input(question))
return response
#remember that when defining the functions, you have to put in colons. The user recieves a question and then has to give an answer.
def pieces():
"""Determine if player or computer goes first""" #docstrings are used to name the functions.
go_first = ask_yes_no("Do you requre the first move?y/n: ")
if go_first == "y": #important to have two equal signs because you are giving a variable a name. Notice that one function callled another.
print "\n Then take the first move, you will need it."
human = X
computer = 0
else:
print "\n Your bravery will beyour undoing .... I will go first."
computer = X
human = O
return computer, human

You need to define and call a main function
def main():
display_instruct()
#the rest of the code
if __name__ == "__main__":
main()
The reason your code doesn't run is because what you have is function definitions
def func() ...
and value assignments
x=5
To actually run something you will either need to define a main function that takes all the things you have defined and combines them in a meaningful way or append to the bottom of the code something similar to what you would write in the main function.

Related

Why when I use two functions in a program only one works

Im doing a simple code jam for school and my question is why when I use two functions in a program only one works or it doesn't work at all. one_player_# is the name of my function. I want to use if- statement to call the functions for the user to choose a game-mode. My game modes is one player and two player. So I made the code for the game a function so I can make it possible for the user to choose a game mode through the if -statement but when you choose a game-mode it doesn't work. Is what im trying to do not possible? Hope that makes sense plz explain what i'm dong wrong thanks.
# choose your game mode
op = input("Choose gamemode - Two player = 2 One player = 1 : ")
if op == 2 :
print (two_player_op())
if op == 1:
print(one_player_op())
#One player Function
def one_player_op():
# I put game code for 1st play here
#Two player function
def two_player_op():
# I put game code for two player here
#code ends
I expect for it to allow the user to choose a game-mode and run it rather than giving me a blank response
Your script is reading from top to bottom.
First define the functions, and then call them. Also, use "int" before input.
#One player Function
def one_player_op():
# I put game code for 1st play here
#Two player function
def two_player_op():
# I put game code for two player here
#code endsenter code here
# choose your game mode
op = int(input("Choose gamemode - Two player = 2 One player = 1 : "))
if op == 2:
print (two_player_op())
if op == 1:
print(one_player_op())
You need to make sure you are comparing an int to another int if you want to get a True result. Keep in mind the types of data you are manipulating. Also in python, you must define functions before code that runs them. Not code that defines them, but the code that is actually executing the function.
So in your case:
#One player Function
def one_player_op():
# I put game code for 1st play here
#Two player function
def two_player_op():
# I put game code for two player here
# choose your game mode
op = int(input("Choose gamemode - Two player = 2 One player = 1 : "))
if op == 2 :
print (two_player_op())
if op == 1:
print(one_player_op())
#code ends
Incorporating the comment, if you want to make it clear that only one game mode is to run, for code readability purposes, and to make sure any future additional conditional options you might add do what you intend them to do you can write the conditionals as:
if op == 2 :
print (two_player_op())
elif op == 1:
print(one_player_op())
#code ends
You need to handle other options added by user and not only (1 or 2)
# choose your game mode
op = input("Choose gamemode - Two player = 2 One player = 1 : ")
try:
user_input = int(op)
except ValueError:
# handles characters added in input e.g "one", "play"
print("Please enter values between 1 or 2 only ")
if user_input == 2 :
print (two_player_op())
elif user_input== 1:
print(one_player_op())
else:
print("Please enter values between 1 or 2 only ")
#One player Function
def one_player_op():
# I put game code for 1st play here
#Two player function
def two_player_op():
# I put game code for two player here
#code ends
Need to convert input string to int.
op = int(input("........'))

Initializing and displaying grid - python

I'm attempting to create a game similar to battleship, and I'm having trouble figuring out how I would initialize the board by having each cell begin with an 'O' and displaying it to the user. A requirement for the function player_board() is that it's supposed to take in a grid representing the player's game board as an argument and output it to the user's screen. This is a portion of my code that I'm struggling with. I'm also not sure why it keeps printing out an extra 'O' at the end. Any help or feedback would be appreciated!
import random
sizeof_grid = 9
chance = 10
def mines():
grid = [{("M" if random.randint(0, chance) == 0 else " ") for i in
range(sizeof_grid)} for i in range(sizeof_grid)]
return grid
def initialize_board():
start_board=[["O" for i in range(sizeof_grid)] for i in range(sizeof_grid)]
return start_board
def players_board():
for r in initialize_board():
for c in r:
print (c, end="")
print()
return c
print(players_board())
You get the extra "O: because of the last line of code. You call the function with print(players_board) and in the function itself you return c (which has the value of one "O"). This means you print out the return value of the function which is "O".
You can execute the function with players_board() and remove the print().
Also you can remove the return c at the bottom of the function.

Creating Decision Tree for Simple Game

I am currently a new student learning python. This is my first real experience doing much computer coding. For my project I must create a fill in the blank quiz with three different levels of difficulty. Once the user chooses a difficulty the game should print a different paragraph based on the difficulty. Each section of the game works fine but I am having trouble creating the "difficulty chooser." No matter the difficulty I choose, the game rolls through the easy, medium, and the hard level in order and then crashes.
Below I have included the introductory text and the difficulty chooser. I would love some help. I am sure there are really obvious things I don't see. Thank you!
def introduction():
print '''Welcome to Kevin's European Geography Quizzes.
Test your knowledge of European geography. \n'''
difficulty = raw_input('''Do you want to play an easy, medium, or hard game?
Please type the number 1 for easy, 2 for medium, or 3 for hard.\n''' )
game_chooser(difficulty)
def game_chooser(difficulty):
cursor = 0
difficulty_choice = [easy_game(), medium_game(), hard_game()]
#each element of the above list links to a procedure and starts one of the
#mini-games.
while cursor < len(difficulty_choice):
if difficulty != cursor:
cursor += 1
else:
difficulty_choice[cursor]
break
You can do with if else if you only want to print something but if you have separate code block for each level then define a function for each level and use this pattern :
You can define the function blocks and call them basis on user input something like:
# define the function blocks
def hard():
print ("Hard mode code goes here.\n")
def medium():
print ("medium mode code goes here\n")
def easy():
print ("easy mode code goes here\n")
def lazy():
print ("i don't want to play\n")
# Now map the function to user input
difficulty_choice = {0 : hard,
1 : medium,
4 : lazy,
9 : easy,
}
user_input=int(input("which mode do you want to choose : \n press 0 for hard \n press 1 for medium \n press 4 for lazy \n press 9 for easy "))
difficulty_choice[user_input]()
Then invocation of function block will be:
difficulty_choice[num]()
Add a conditional for the input.
if difficulty == 'easy':
print("here is an easy game")
elif difficulty == 'medium':
print('here is a medium game')
elif difficulty == 'hard':
print('here is hard')
else:
print('Please enter valid input (easy, medium, hard)')
Under each if statement put your game code.
The reason your code goes through all the difficulties is because of this line:
difficulty_choice = [easy_game(), medium_game(), hard_game()]
When Python sees something like easy_game(), it calls the easy_game function and replaces it with the result. You don't want to call the function yet though, so you can take off the parenthesis to store just the function instead:
difficulty_choice = [easy_game, medium_game, hard_game]
This will mean you have to call the function after you take it out of the array.
As for the crash, when you use raw_input() you get a string back. That means when you type in the 1 to decide for an easy game, you get the character 1, which is represented by the number 49. That's why your code goes through everything and crashes: Your 1 is really a 49. In fact, if you type 1 < '1' into the interpreter, you'll get True back.
To fix that, you can pass the result of raw_input() to the int() function, which will parse it and give you the proper integer (or throw an exception if it can't be parsed). The last line of introduction would then look like game_chooser(int(difficulty)).
You could also skip most of the code of game_chooser by just indexing into the array (that's what they're for, after all):
def game_chooser(difficulty):
# the lack of parens here means you get the function itself, not what it returns
difficulty_choice = [easy_game, medium_game, hard_game]
#each element of the above list links to a procedure and starts one of the
#mini-games.
# note the parens to actually call the retrieved function now
difficulty_choice[difficulty]()

How do I keep track of score increments in Python?

I am writing a simple game program in Python where a user is prompted to select from "healthy" and "unhealthy" items in a grocery store. Each time the user selects a healthy item their "Health Score (initially 100) goes up. Each time they select from the unhealthy items their score goes down.
My code adds and subtracts from the initial Health Score of 100, but doesn't keep track of the most updated score after each selection. I want to give the user their new total after each transaction (new_hscore) and their grand total at the end (final_score), but I'm not sure how to do that.
Is it done with lists? Do I use .append? Any help would be greatly appreciated! Thanks in advance!
Here is my code: http://pastebin.com/TvyURsMb
You can see right away what I'm trying to do when you scroll down to the "def inner():" function.
EDIT: I got it working! Thank you all who contributed. I learned a lot. My final 'score-keeping' working code is here: http://pastebin.com/BVVJAnKa
You can do something simple like this:
hp_history = [10]
def initial_health():
return hp_history[0]
def cur_health():
return hp_history[-1]
def affect_health(delta):
hp_history.append(cur_health() + delta)
return cur_health()
Demonstration:
>>> cur_health()
10
>>> affect_health(20)
30
>>> affect_health(-5)
25
>>> affect_health(17)
42
>>> cur_health()
42
>>> print hp_history
[10, 30, 25, 42]
You can't store module level variables like that. Any attempt to write to that variable will create a local variable. Examine the behavior of this script:
s = 0
def f():
s = 10
print s
f()
print s
Output:
10
0
Instead you should be moving towards an object-oriented approach. Start placing your code in a class:
class HeathlyGame():
def __init__(self):
self.init_hscore = 100
self.final_score = 0
# Beginning. Proceed or quit game.
def start(self):
print "Your shopping habits will either help you live longer or they will help you die sooner. No kidding! Wanna find out which one of the two in your case?", yn
find_out = raw_input(select).upper()
...
game = HeathlyGame()
game.start()
This will allow you to create multiple versions of the game in memory at once, and each can store their own copy of the score.
For more on classes, try this link: http://en.wikibooks.org/wiki/A_Beginner%27s_Python_Tutorial/Classes
The problem seems to be you are always starting at init_hp, forgetting your cur_hp doing
init_hp = 10
while True:
food = choose_food()
if "cereal" in food:
cur_hp = init_hp - 5
# ..
But you need:
init_hp = 10
cur_hp = init_hp
while True:
food = choose_food()
if "cereal" in food:
cur_hp -= 5
# ..
You can use a generator!
A generator is basically a function that keeps track of the state of its objects even after you leave the function and call it again. Instead of using 'return' and the end, you use 'yield'. Try something like this:
def HealthScore(add):
score = 100
while 1:
score += add
yield score
if you call HealthScore(-5), it will return 95. If you then call HealthScore(5), it will return 100.

only letting user do a function once in Python?

I am very new to Python. running on windows while I wait for some stuff for my Pi.
I am writing a game where the user travels through a tower via text inputs.
the user can use "a" "d" "w" to look around a room to collect sutff. but if the user has already looked in "a" (which is "look left") i need to let them know they have already been there.
this is my code but it has an obvious flaw.
#if user hits 'a' they look left
def roomOneLeft():
print '-- You search some loose rubble and find some cloth'
return roomOneMoves()
#where the user selects a movement
def roomOneMoves():
left = 0
move = raw_input("")
if left == 1:
print 'you have already looked here'
return roomOneMoves()
if move == "a":
left = left + 1
roomOneLeft()
can i set "left" to static? and ant work out how to set it as global variable like java. this obviously doesn't work because when it returns, it sets itself back to 0. any help would be greatly appreciated!
You can define "left" as global. Like this:
left = 0
#where the user selects a movement
def roomOneMoves():
global left
move = raw_input("")
if left == 1:
print 'you have already looked here'
return roomOneMoves()
if move == "a":
left = left + 1
roomOneLeft()
To make a variable global, declare in the module scope, and then to change it in a function, use the global keyword.
left = 0
def some_func()
global left
left = 1
That will allow you to edit global variables inside a function.
To address your static variable question, I believe you cannot do this in python. See this question.

Categories