Variable not define newbie in Python - python

I made a menu to play a game in python. (Please See Below). However, I can t use my lists when I call setup_game or init_trigger. I tried to put them into the while and to also add a variable play so I can avoid the user to press 2 if he never played before. my issues are the following:
Why setup_game(possible_answers, female_charactere, male_charactere) or init_trigger(possible_answers, charactere_attributes) does not work if I put the list out of the while?
why is play not defined?
Please also give me feedback on the code itself, I am a newbie and I want to improve. Thank you!
### create the menu
def menu():
print (30 * "-" , "MENU" , 30 * "-")
print ("1. Replay")
print ("2. Back to my first choice")
print ("3. Exit")
print (67 * "-")
## setup number of time player try the game
play=0
## lists needed to run setup_game and init_trigger
possible_answers= ["female","Female","F","girl","answer","Answer","a","yes","y","Yes","Y","kitchen","Kitchen","K","k","1","Leave","leave"]
female_charactere= ["boy","girl","he","his","him","prince"]
male_charactere= ["girl","boy","she","her","her","princess"]
loop=True
while loop: ## While loop which will keep going until loop = False
menu() ## Displays menu
choice = int(input("Enter your choice [1-3]: "))
if choice==1:
print ("Your story is about to start")
play=play+1 ##count number of time user play
setup_game(possible_answers, female_charactere, male_charactere) ## launch game
elif (choice==2 and play>=1):
print ("Your are back to your first choice")
play=play+1 ##count number of time user play
init_trigger(possible_answers, charactere_attributes) ##lauch game at first choice
elif (choice==2 and play==0):
print ("You have not played yet, you are starting a new story")
setup_game()
elif choice==3:
print("Thank you for playing!")
loop=False # This will make the while loop to end as not value of loop is set to False
else:
print("Thank you for playing!")
break

Why setup_game(possible_answers, female_charactere, male_charactere)
or init_trigger(possible_answers, charactere_attributes) does not work
if I put the list out of the while?
Here you're calling 2 functions you've yet to create. Unless you have more code that you did not share. Your app has no idea what to do with start_game() or init_trigger().
why is play not defined?
Python requires proper indentation, when you step into something like a function, loop, if statement, etc, you have to indent the code that belongs to it.
In your case, you've indented play = 0 under the menu() function. Because of this, play only exists in the scope of menu (). If you align play = 0 left, that warning will disappear.

Related

Can I make a print statement run before a module I imported?

I am a beginner to python and coding in general and I was wondering how I can make a print statement run before a module I imported. I am making a number guessing game and in my main file where I combine all the modules, I have a general function for running all the code together. It would be best if I show my code so you guys will have a better understanding of what I am dealing with:
import random
import lvl1
import time
level1 = lvl1.Level_1_activated()
# This is the main file combining everything together to make this game playable
introduction = """
Hello and welcome to NumGuess by Sava. Here is a little bit about the game:
The game works by having 3 levels, each where you must pick a number between a range of
1-10 (level 1), 1-20 (level 2), and 1-50 (level 3).
You are given 5 attempts in the first level, 10 in the second level, and 20 in the final one.
You can also access a hint by typing ‘hint’. You win the game by picking the right number in each level.
You lose the game when you run out of tries. You can get a free bonus with 5 extra tries if you type ‘hlp’.
"""
def start_game(time, lvl1):
print(introduction)
level1
start_game(time, lvl1)
This is just the code for the main module, I have the code for lvl1 (which is the first level of my 'game'), and I have a class which has all the functions which then take part in the while loop. I will also show that file:
import random
import time
# I will fist make variables for the time breaks. S is for short, M is for medium and L is for long
S = 0.2
M = 0.7
L = 1.1
class Level_1_activated():
def get_name(self):
# This function simply asks the name of the player
name = input("Before we start, what is your name? ")
time.sleep(S)
print("You said your name was: " + name)
def try_again(self):
# This asks the player if they want to try again, and shows the progress of the level
answer = (input("Do you want to try again? "))
time.sleep(M)
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(M)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
# Return statement for if the player wants to play again
return True
else:
print("Thank you for playing the game, I hope you have better luck next time")
# This is the return statement that stops the while loop
return False
def find_rand_num(self, random):
# This is the core of the level, where the player just chooses numbers between 1 and 10
time.sleep(S)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(L)
# The list of numbers for the level that the player is on at the moment
num_list = [1,10]
number = random.choice(num_list)
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(S)
print("Congratulations! You got the number correct!")
# Yet another return statement for the while loop
return "Found"
elif input != number:
time.sleep(M)
print("Oops, you got the number wrong")
# This variable is fairly self-explanatory; it is what controls how many itterations there are in the while loop
tries = 1
while tries < 6:
if tries < 2:
Level_1_activated().get_name()
res = Level_1_activated().find_rand_num(random)
if res == "Found":
break
checker = Level_1_activated().try_again()
if checker is False:
break
tries += 1
If you go back to this function in the main file:
def start_game(time, lvl1):
print(introduction)
level1
I intentionally put the print statement before the module to make it run first, and I have tried different approaches to this and still can't seem to get a grasp on what I'm doing wrong here. Thank you for taking the time to read the code and I would be very grateful if any of you have a possible solution to this.
there are number of thing you can do, one is encapsulate your code into functions that only run when you ask for it
lvl1
... #all the previous code
def run_game():
tries = 1
while tries < 6:
...
tries += 1
you can also make a distinction between being executed directly vs being imported, to do that is simple, you include the following check (usually at the end of the file)
if __name__ == "__main__":
#if true it mean that you're executing this module directly, otherwise it was imported
#and you include here whatever you want that happens when you execute the module directly but not when is imported, like for example running a game
run_game()
__name__ is a special variable and python will assigned the value "__main__" if executed directly, otherwise it will be the name of the file, like "lvl1" for example
And in your main you can import it and do stuff like
import lvl1
...
def start_game():
print(introduction)
lvl1.run_game()

python dice rolling restart script

i want to restart my script automatically i have a dice rolling script and i don't want to have to reset my script manually between each roll this is my script.
import random
from random import randrange
from random import randint
r = randint
min = 1
max = 6
rolls = int(float(input('how menny times do you want to roll:')))
for x in range(rolls):
print ('Rolling the dices...')
print ('The value is....')
print (r(min, max))
i have tried a few ways to do it but none of them worked
I'm not 100% sure what you were actually trying to do, but here is a program that I wrote that will roll 2 die at a time, and will generate however many rolls you would like to roll. -not the best practice to use recursive (main calls main from within itself), but it's not really an issue with something this basic.
*replace raw_input with input if you are using Python 3+. I use 2.7 so I use raw_input
import time
import random
def roll_multiple():
#honestly this is all you need to do what you want to do, the rest just turns it into a game and allows multiple runs
roll_number = int(raw_input("How Many Times Would You Like to Roll?\n"))
for i in range(roll_number):
print"You Rolled A ", random.randrange(1,6,1), " and a ", random.randrange(1,6,1)
#that's it! if you do these 3 lines, it will ask for how many times, and for each item in range of roll_number (whatever you input) it will run the print below and generate new numbers for each roll.
def main():
print("Welcome to Craps 2.0")
playing = raw_input("Press Enter to Roll or Q to quit")
if playing == 'q':
print("Thanks for Playing")
time.sleep(2)
quit()
elif playing != 'q':
roll_multiple()
main()
main()

importing 'games' and window closes [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am attempting to make a program that opens up other programs (games that i have made previously) and the window closes instantly.
#Program that runs game i have made
import subprocess
choice = input("What would you like to do? \nGuess my number game (1) \nCalorie counter (2) \nWord jumble game (3) \nInsert your decision here - ")
while choice == "1":
print("Let us begin")
def start_guess_my_number():
subprocess.call(['python', 'Guess my number game2.py'])
start_guess_my_number()
choice = input("What would you like to do now? 1 2 or 3 ? - ")
while choice == "2":
print("Let us begin")
def start_calorie_counter():
subprocess.call(['python', 'Calorie counter.py'])
start_calorie_counter()
choice = input("What would you like to do now? 1 2 or 3 ? - ")
while choice == "3":
print("Let us begin")
def start_guess_my_number():
subprocess.call(['python', 'Word jumble game.py'])
start_guess_my_number()
choice = input("What would you like to do now? 1 2 or 3 ? - ")
input("Press enter to exit")
note: I have made sure that the programs I am calling upon are working, and when opened in the black command window, they stay open, unlike when I open them via this program.
You had the following problems:
You need to compare the input to an int, not a string
You need to open the game in the right folder, by default the new process runs in the folder that contains the python executable.
You were using while loops instead of if statements, your code would have been caught in an infinite loop.
There was no way to get out of the main loop, you need a break statement to achieve that.
I also separated the code into functions.
#Program that runs a game I have made
import os
import subprocess
def play_game(name):
print("Let us begin")
subprocess.call(['python', os.path.dirname(os.path.realpath(__file__))+os.path.sep+name])
choice = input("What would you like to do? \nGuess my number game (1) \nCalorie counter (2) \nWord jumble game (3) \nInsert your decision here - ")
while True:
if choice == 1:
play_game('Guess my number game2.py')
elif choice == 2:
play_game('Calorie counter.py')
elif choice == 3:
play_game('Word jumble game.py')
else:
break
choice = input("What would you like to do now? 1 2 or 3 ? - ")
print("Goodbye")

Python programming for card game War

This program is supposed to play the card game War. Okay so I need to be able to prompt the user to keep playing and have them respond by hitting the enter key. I'm not sure how to make this happen. Help?
import cards
# Create a deck of cards
the_deck = cards.Deck()
# Shuffle the deck, then display it in 13 columns
the_deck.shuffle()
print( "===== shuffled deck =====" )
the_deck.display()
def main():
'''This function deals out half the deck to each
player. It sorts the rank so as to solve the problem
with Aces causing an infinite game'''
player1_list=[]
player2_list=[]
for i in range( 26 ):
p1_temp= the_deck.deal()
player1_list.append( p1_temp )
p2_temp= the_deck.deal()
if (p2_temp.rank()==1):
player1_list.append(p2_temp)
player2_list.append(player1_list.pop(0))
else:
player2_list.append(p2_temp)
print()
# Card dealt to Player #1
player1_card = player1_list.pop( 0 )
print( "===== player #1 =====" )
print( "Card dealt to player #1:", player1_card )
print( player1_list )
print()
#Card dealt to Player #2
player2_card=player2_list.pop(0)
print( "===== player #2 =====" )
print("Card dealt to player #2:",player2_card)
print( player2_list )
# Compare the two cards using overloaded operators
print()
if player1_card == player2_card:
print( "Tie:", player1_card, "and", player2_card, "of equal rank" )
elif player1_card > player2_card:
print("Player #1 wins:",player1_card,"of higher rank than",player2_card)
else:
print("Player #2 wins:",player2_card,"of higher rank than",player1_card)
print()
main()
def keep_playing():
'''Determines whether the player wants to continue. If so they press the
Enter key and the function calls main to start all over.'''
still_playing=input('Press "Enter" to continue playing')
Enter=1
while still_playing==Enter:
main()
keep_playing()
Assuming the rest of your main is working (and the imported Deck class): your two main problems are you forgot to call your main and the method you are using to test the variable Enter. Since your taking an input for Enter you just need to test this against an empty string or just test that it is empty - as input strips newlines by default.
def play_hand():
print ("all the play code goes here")
#just a simple exit here no return needed
'''This function deals out half the deck to each
player. It sorts the rank so as to solve the problem
with Aces causing an infinite game
player1_list=[]
player2_list=[] ... etc ...'''
def keep_playing():
'''Determines whether the player wants to continue. If so they press the
Enter key and the function calls main to start all over.'''
return input('Press "Enter" to continue playing')
def main():
# the_deck = Card.Deck() # create deck instance (depending on how shuffle method is written this may need to go in while loop)
still_playing = "" #Set still_playing to empty string to more easily use input
while not still_playing: #this will keep going as long as still_playing is an empty string
print("hello main") # cause it fun :) - also as you can put an intro here or the shuffle so:
# the_deck.shuffle()
# print( "===== shuffled deck =====" )
# the_deck.display()
play_hand()
# Do all your other stuff here
still_playing = keep_playing() #Calls the function and stores returned value (can do this with just input but using return to show an option)
main()
As a secondary note, you need to learn how to isolate the problem within your code. To that end: the following shows a testable instance (and solution) of the enter to continue problem your having. Run this and it will only test (in this case solve) the enter problem, this is what Stack Overflow means by a minimal, complete, verifiable example.
As #IanAuld mentioned, you have not called your Keep_playing() function anywhere. Instead of calling main(), simply call Keep_playing(). If you'd like to just start the game without the "Press Enter to continue playing," just make the first line of the Keep_playing() function a call to main(), so that it runs and then keeps checking if the user wants to continue.
Also, you have an infinite loop in Keep_playing(). Put the input(...) part inside the while loop after you call main(). That way, it will reprompt every loop and change the still_playing variable.
It should look like this:
def keep_playing():
'''Determines whether the player wants to continue. If so they press the
Enter key and the function calls main to start all over.'''
still_playing=""
Enter=""
while still_playing==Enter:
main()
still_playing=input('Press "Enter" to continue playing')
keep_playing()
You can read this SO question to figure out how to implement reading the "enter" key as input (it's quite simple, so don't worry)
Additionally, as a good practice in Python (and most other languages), make variables and function names lowercase, as uppercase names are typically reserved for class use. Even if this isn't going to be spread or maintained around, it's good to get into the habit.

Python While loop keeps repeating

I am trying to use this program I created and I want the program not to repeat the option a lot of times here is the program:
# A Program to show how to use a menu
menu=int(input("What would you like? \n\
1. A compliment \n\
2. An insult \n\
3. A proverb \n"))
y=True
while y==True:
if menu==1: #compliment
print ("You look nice today")
elif menu==2: #insult
print("You smell")
elif menu==3: #proverb
print("A bird in the hand is worth two in the bush!")
else:
y==False
print("Invalid option")
break
What happens is that when I type in the option for example 2 the program repeats
You smell
You smell
You smell
You smell
You smell
infinite times.
You have 2 issues. As #Arrjun Ram mentioned you have y==False when you need y=False
The other issue you have is that your call to input is outside the while loop. This means the value of menu will never change. You need to move it to the inside of the while loop.
You might also add an option, say 4, to exit the loop.
Your while loop never ends. You have a break under your final 'else', but you're assuming that your variable menu will actually be modified. You shouldn't be looping on the response, but instead overall as such:
y=True
while y==True:
menu=int(input("What would you like? \n\
1. A compliment \n\
2. An insult \n\
3. A proverb \n"))
if menu==1: #compliment
print ("You look nice today")
elif menu==2: #insult
print("You smell")
elif menu==3: #proverb
print("A bird in the hand is worth two in the bush!")
else:
print("Invalid option ")
y = False
The above will run until an invalid option is entered and then the loop will break. Your original code would never break since y can never be modified. Your y==False is a comparison operation, NOT an assignment operation. However, that STILL would never be hit, because you're not asking for additional input within your loop so it would remain TRUE forever.

Categories

Resources