importing 'games' and window closes [closed] - python

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")

Related

Variable not define newbie in 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.

how to better organize your code in python? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I've been wonder how to clean up code to make my code easier and more readable for others reviewing my code. I'm fairly new to python, so I write everything into functions instead of using classes. Should I use more classes to better understand python more? I know that if the code works then it doesn't matter the way you did it but I just want to learn how to decrease my lines of code.
def paymentData():
calculateTotal = {}
remainingAmount = []
balance = int(raw_input('What is the balance of your bank account? \n'))
amount = int(raw_input('What is the amount you would like to subtract? \n'))
calculateTotal[balance]=amount
total = balance - amount
print('your total is: ' + str(total))
remainingAmount.append(total)
while True:
choice = raw_input('To continue press "Enter" or type "q" to exit (For options type "o"). \n')
if choice == '':
clearScreen()
paymentData()
break
elif choice.lower() == 'q':
clearScreen()
menuBudget()
break
elif choice.lower() == 'o':
return calculateTotal, remainingAmount
clearScreen()
options_menu()
break
else:
print('Invalid value.')
continue
This is a function from one of my programs that is a budget program that takes the value balance that the user puts in and subtracts it from the amount value.
This function calls three different functions, one of them being clearScreen() that clears the terminal:
def clearScreen(numlines=100):
if os.name == "posix":
os.system('clear')
elif os.name in ("nt", "dos", "ce"):
os.system('CLS')
else:
print('\n' * numlines)
The options_menu() function that tells you the results of all the amount you put in (This is not completed nor do I plan to complete this project).
def options_menu():
print('Do you want to see all of you total amounts?\n(Enter 1 for Yes, 2 for no.)')
choice = int(raw_input())
if choice == 1:
time.sleep(3)
elif choice == 2:
menuBudget()
else:
print('Invalid Response.')
and the `menuBudget()` function that is the main menu for this script:
def menuBudget(): # this is a menu for budget fast.
menuRunning = True
while menuRunning:
print("""
1. payment calculator.
2. Comming Soon.
3. Comming Soon.
4. Exit/Quit.
""")
ans = input('Pick on the options above.\n')
if ans == 1:
clearScreen()
paymentData()
break
elif ans == 2:
print('Comming soon!')
continue
elif ans == 3:
print('Comming soon!')
continue
elif ans == 4:
break
else:
print('Unknown Option Seleted!')
continue
The use of classes means the use of OOP (Oriented Object Programmation). Sometimes your code will be very simple and doesn't need the use of classes. This paradigm depends of the type of project you want to build.
If you use imperative programmation, the best practice is to use functions as you're doing. If you want to improve your code, here are some tips :
Use meanful variable names
Use meanful function names
Sort your code into many files, feel free to have as much as you need. Try to call them once more with meanful names.
Simplify your code as much as needed, and use python libraries functions (this comes with experience). For example, use the max() function instead for re-write other functions.
Add comments to your code to make it re-usable even after month
Feel free to update this answer with other good-programmation pattern !

How do I make this small, but simple food questionnaire work? [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 5 years ago.
I am trying to make a simple food game/questionnaire, and the code keeps printing both lines. I want to have it print one or the other, and no matter what I try, I get the same end result. I am also using Tkinter. (Those of you that do not know, don't worry... This is for those that know what Tkinter does/is.)
Here is my code:
def Waffles():
input ("Do you like Waffles? ")
if input is not ('yes'):
print ("Ok, so you don't like Waffles...")
input ("Do you like Pancakes? ")
if input is not ('no'):
print ("Then let's fix some!!!")
if input is ("no") or ("No"):
print ("Ok, so you don't like Pancakes...")
input ("Do you like French Toast? ")
if input is not ("no"):
print ("Then let's fix some!!!")
if input is not 'yes':
food = input ("Then what do you like? ")
print ("Oh! Ok.")
Here is what gets printed:
Do you like Waffles? no
Ok, so you don't like Waffles...
Do you like Pancakes? no
Then let's fix some!!!
Ok, so you don't like Pancakes...
Do you like French Toast? no
Then let's fix some!!!
Then what do you like? food
Oh! Ok.
Can you help me make this print one or the other? ("Then let's fix some!!!" and "Do you like __________").
"input" is a function. So you are testing if the built-in function is (or is not) various strings, which it never is.
You need to store the result of "input" in a variable and test that. Here's a simplified version of Waffles() demonstrating the concept.
def Waffles():
answer = input ("Do you like Waffles? ")
if answer != 'yes':
print ("Ok, so you don't like Waffles...")
In case that isn't clear, here's a more contrived function that should really drive the example home.
def demonstrate_input():
input("do you like waffles ")
print(input)
answer = input("do you like waffles? I will remember this time ")
print(answer)
Here's what happens when you run that function:
do you like waffles no
<built-in function input>
do you like waffles? I will remember this time nope
nope
Note how printing "input" prints out a strange looking reference to the function, but printing "answer" returns the thing that was answered to the input prompt.
Here's how I would've written it:
def waffles():
response = input("Do you like Waffles?\t\t\t")
print(response.lower())
if response.lower() != "yes":
print("Ok, so you don't like Waffles...")
response = input("Do you like Pancakes?\t\t\t")
if response.lower() != "no":
print("Then let's fix some!!!")
else:
print("Ok, so you don't like Pancakes...")
response = input("Do you like French Toast?\t\t")
if response.lower() != "no":
print("Then let's fix some!!!")
if response.lower() != "yes":
input("Then what do you like?\t\t\t")
print ("Oh! Ok.")
waffles()

How to run an input statement until you get what you want in python? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 5 years ago.
I am running the code below, where program = MainFormula() defines a function used in my program. What I want to achieve is that the program last until the input to the question - "Do you want to change alpha? (Yes/No)" is No. I get what I want, but the program gives me two times "Do you want to change alpha? (Yes/No)" once I reply to the question as "Yes". Can anyone help me to avoid asking "Do you want to change alpha? (Yes/No)" "Do you want to change alpha? (Yes/No)" two times? (just one is needed)
input_value1 = input("Do you want to change alpha? (Yes/No) ").lower()
while input_value1=="yes":
input_value1 = input("Do you want to change alpha? (Yes/No) ").lower()
if input_value1 == "yes":
program = MainFormula() print(program)
else:
print("Congratulations! You are done with the task.")
while True:
input_value = input("Do you want to change alpha? (Yes/No) ").lower()
if 'no' in input_value: # When this condition is met we break from the loop
break
elif 'yes' in input_value:
program = MainFormula()
print(program)
else:
print("Congratulations! You are done with the task.")
break
I believe this is what you're trying to accomplish - let me know if this is not exactly what you're looking for and I will adjust my answer accordingly.
With some formatiing you appear to have this
input_value1 = input("Do you want to change alpha? (Yes/No) ").lower()
while input_value1=="yes":
input_value1 = input("Do you want to change alpha? (Yes/No) ").lower()
if input_value1 == "yes":
program = MainFormula()
print(program)
else:
print("Congratulations! You are done with the task.")
A simple thing to do this avoid asking the question twice:
while input("Do you want to change alpha? (Yes/No) ").lower()=="yes":
program = MainFormula()
print(program)
print("Congratulations! You are done with the task.")

I've created a recipe program for GCSE Computing, but I am missing one step [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
This is my first post here and I am quite unsure on how to implement a vital piece of code in my coursework. I have created a very crude and basic recipe program on Python 3.4. Below is the piece I am missing.
• The program should ask the user to input the number of people.
• The program should output:
• the recipe name
• the new number of people
• the revised quantities with units for this number of people.
I am a complete beginner to programming and our teacher hasn't been very helpful and only explained the basics of file handling which I have attempted to implement into this program.
I will attach the code I have so far, but I would really appreciate some tips or an explanation on how I could implement this into my code and finally finish this task off as it is becoming very irksome.
Thank you!
Code:
I apologise if the code is cluttered or doesn't make sense. I am a complete novice.
#!/usr/bin/env python
import time
def start():
while True:
User_input = input("\nWhat would you like to do? " "\n 1) - Enter N to enter a new recipe. \n 2 - Enter V to view an exisiting recipe, \n 3 - Enter E - to edit a recipe to your liking. \n 4 - Or enter quit to halt the program " "\n ")
if User_input == "N":
print("\nOkay, it looks like you want to create a new recipe. Give me a moment..." "\n")
time.sleep(1.5)
new_recipe()
elif User_input == "V":
print("\nOkay, Let's proceed to let you view an existing recipe stored on the computer")
time.sleep(1.5)
exist_recipe()
elif User_input == "E":
print("\nOkay, it looks like you want to edit a recipe's servings. Let's proceed ")
time.sleep(1.5)
modify_recipe()
elif User_input == "quit":
return
else:
print("\nThat is not a valid command, please try again with the commands allowed ")
def new_recipe():
New_Recipe = input("Please enter the name of the new recipe you wish to add! ")
Recipe_data = open(New_Recipe, 'w')
Ingredients = input("Enter the number of ingredients ")
Servings = input("Enter the servings required for this recipe ")
for n in range (1,int(Ingredients)+1):
Ingredient = input("Enter the name of the ingredient ")
Recipe_data.write("\nIngrendient # " +str(n)+": \n")
print("\n")
Recipe_data.write(Ingredient)
Recipe_data.write("\n")
Quantities = input("Enter the quantity needed for this ingredient ")
print("\n")
Recipe_data.write(Quantities)
Recipe_data.write("\n")
for n in range (1,int(Ingredients)+1):
Steps = input("\nEnter step " + str(n)+ ": ")
print("\n")
Recipe_data.write("\nStep " +str(n) + " is to: \n")
Recipe_data.write("\n")
Recipe_data.write(Steps)
Recipe_data.close()
def exist_recipe():
Choice_Exist= input("\nOkay, it looks like you want to view an existing recipe. Please enter the name of the recipe required. ")
Exist_Recipe = open(Choice_Exist, "r+")
print("\nThis recipe makes " + Choice_Exist)
print(Exist_Recipe.read())
time.sleep(1)
def modify_recipe():
Choice_Exist = input("\nOkaym it looks like you want to modify a recipe. Please enter the name of this recipe ")
Exist_Recipe = open(Choice_Exist, "r+")
time.sleep(2)
ServRequire = int(input("Please enter how many servings you would like "))
start()
EDIT: This is the new code, however I can still not figure out how to allow a user to multiply the original servings by entering how many servings are required, as the default servings are in a text file. Does anyone know how this can be done? I am new to file-handling and have been researching constantly but to no avail.
For the number of people, you can get that from user input similar to how you got any other input in your code, with num_people = input("How many people?").
Something a little more concerning you should look at. Your start() function calls its self. Unless you are using recursion, functions should not call themselves, it will build up on the stack. Use a while loop with something like
while ( 1 ):
userinput = input("what would you like to do?")
if( userinput == "n"):
#new recipe
....
if (user input == "quit"):
sys.exit(1) #this will halt the program
else:
print "not valid input"
You stored the whole data in a text file. This makes storage and retrieval easy, but makes changing values real hard. In these cases, you usually use ... well nevermind: you asked the same question again and got a useful answer.

Categories

Resources