How can you make a function go to another function? [duplicate] - python

This question already has an answer here:
Python function NameError [duplicate]
(1 answer)
Closed 3 years ago.
So I have this game:
import sys
def Start():
print("Hello and welcome to my first Python game. I made it for fun and because I am pretty bored right now.")
print("I hope you enjoy my EPIC TEXT GAME")
play = input("do you want to play? (Y / N) ")
if play == "Y":
game()
if play == "N":
sys.exit()
def game():
print("That's pretty much what I've done so far! :P -- yea yea, it's nothing -- IT IS!. Bye now")
input("Press enter to exit")
If I type "Y" I want to go to game(). It doesn't.

You have defined game after you tried and use it. You need to define functions, variables, etc. before you use them.
Also, your code only matched on upper case Y and not lower case y. To make all input upper case, you should use the .upper() method on it
Change the code to:
def game():
print("That's pretty much what I've done so far!")
input("Press enter to exit")
if play.upper() == "Y":
game()
elif play.upper() == "N":
sys.exit()
It is usually best form to not have any global code, and instead include it in a main function if the python code is being run as the main. You can do this by using:
if __name__ == "__main__":
Start()
And then put all that global code into the Start method.
Again, make sure you declare before you use.

You're using the input() function which executes the input as a command immediately after reading it from stdin.
You probably want to use raw_input() which will simply return what the user entered

Related

Having trouble with while loops, input and strings in python

I am learning python and practicing my skills my making a simple text based adventure game.
In the game, I want to ask the player if they are ready to begin. I did this by creating a begin() function:
def begin():
print(raw_input("Are you ready to begin? > "))
while raw_input() != "yes":
if raw_input() == "yes":
break
print(start_adventure())
else:
print("Are you ready to begin? > ")
print(begin())
below this in my code is the function start_adventure()
def start_adventure():
print("Test, Test, Test")
When I run the program it starts up and I get to the point where it asks if I am ready to begin. Then it just loops infinitely and I can only exit the program if I completely close Powershell and restart Powershell. What am I doing wrong? How can I get the loop to stop once the player inputs "yes"?
What do you expect this to do? The solution to your problem is to try to understand what the code does, instead of just throwing stuff together. (Don't worry; at least 80% of us were at that stage at one point!)
As an aside, I strongly recommend using Python 3 instead of Python 2; they made a new version of Python because Python 2 was full of really strange, confusing stuff like input causing security vulnerabilities and 10 / 4 equalling 2.
What do you want this to do?
Repeatedly ask the user whether they are ready to begin until they answer "yes".
Call start_adventure().
Ok. Let's put what we've got so far into a function:
def begin():
while something:
raw_input("Are you ready to begin? > ")
start_adventure()
There are a lot of gaps in here, but it's a start. Currently, we're getting the user's input and throwing it away, because we're not storing it anywhere. Let's fix that.
def begin():
while something:
answer = raw_input("Are you ready to begin? > ")
start_adventure()
This is starting to take shape. We only want to keep looping while answer != "yes"...
def begin():
while answer != "yes":
answer = raw_input("Are you ready to begin? > ")
start_adventure()
Hooray! Let's see if this works!
Traceback (most recent call last):
File "example", line 2, in <module>
while answer != "yes":
NameError: name 'answer' is not defined
Hmm... We haven't set a value for answer yet. In order to make the loop run, it has to be something that isn't equal to "yes". Let's go with "no":
def begin():
answer = "no"
while answer != "yes":
answer = raw_input("Are you ready to begin? > ")
start_adventure()
This will work!
Python 3 Solution
You should not be calling raw_input() multiple times. Simply instantiate x and then wait until the user inputs Y to call your start_adventure function. This should get you started:
def start_adventure():
print('We have started!')
#do something here
def begin():
x = None
while x!='Y':
x = input('Are you ready to begin (Y/N)?')
if x=='Y':
start_adventure()
begin()
Your Raw input function (I'm assuming it works correctly) is never assigned to a variable. Instead you call it in your print statement, print the result of it and then you call it again in your while loop condition.
You never actually satisfy the while loop condition because your input isn't assigned to a variable. Assign Raw_input("Are you ready to begin? >") to a variable to store the input. Then while loop with the variable. Make sure in your while loop when the condition is met you reset the variable to something else.
Your program flow is wrong too, you need to call your raw input function inside the while loop. This will change the while loop condition so that when the condition is met (user types "yes") it won't loop infinitely. Hope this helps!
Example of what you need in code form:
//initialize the condition to no value
condition = None;
#check the condition
while condition != "yes"
#change the condition here based on user input **inside the loop**
condition = raw_input("are you ready to begin? >")
if condition == "yes":
#condition is met do what you need
else:
#condition not met loop again
#nothing needs to go here to print the message again

Python Function requesting input doesn't execute if statement - no error shown

I thoroughly searched for an answer to my question but couldn't find anything that would explain my results. I truly hope that anyone of you can point me in the right direction.
At the moment I am trying to program a text-based adventure game using Python 3 in order to better understand the language.
While doing so I created a function that should ask the user for input and print a specific statement depending on the users input. In case the users input is invalid the function should then keep asking for input until it is valid.
Unfortunately the function only seems to keep asking for input, without ever executing the if/elif statements within the function. Due to no errors being shown I am currently at a loss as to why this is the case...
print("If You want to start the game, please enter 'start'." + "\n" +
"Otherwise please enter 'quit' in order to quit the game.")
startGame = True
def StartGame_int(answer):
if answer.lower() == "start":
startGame = False
return "Welcome to Vahlderia!"
elif answer.lower() == "quit":
startGame = False
return "Thank You for playing Vahlderia!" + "\n" + "You can now close
the window."
else:
return "Please enter either 'r' to start or 'q' to quit the game."
def StartGame():
answ = input("- ")
StartGame_int(answ)
while startGame == True:
StartGame()
You fell into the scoping trap: you are creating a new variable startGame inside the function that is discarded after you leave it. You would instead need to modify the global one:
def StartGame_int(answer):
global startGame # you need to specify that you want to modify the global var
# not create a same-named var in this scope
# rest of your code
This other SO questions might be of interest:
Python scoping rules
Asking the user for input until they give a valid response
Use of global keyword
and my all time favorite:
How to debug small programs (#1) so you enable yourself to debug your own code.
The last one will help you figure out why your texts that you return are not printed and why the if does not work on 'r' or 'q' and whatever other problems you stumble into. It will also show you that your if are indeed executed ;o)
Other great things to read for your text adventure to avoid other beginner traps:
How to copy or clone a list
How to parse a string to float or int
How to randomly select an item from a list

Function returns "None" (not using any fancy functions in the code) [duplicate]

This question already has an answer here:
print statement inside of input returns with a "none"
(1 answer)
Closed 6 years ago.
I am writing a game using loops and I haven't defined any functions in my code, but only using basic ones like print(). My code itself does exactly what it's supposed to do, but it throws in a None where the user is supposed to give input to the code.
while loca == 22:
if (lever=="back") and (dial=="red"):
print("congratlations! You have won the game!")
play=input(print("Would you like to play again? Type 'Y' for yes and 'N' for no."))
while play in ["yes","y","Y","Yes"]:
loca = 1
play="reset"
while play in ["no","n","N","No"]:
print("Thanks for playing!")
quit()
while (not play == "reset"):
while (not play == ["no","n","N","No"]) and (not play == ["yes","y","Y","Yes"]):
play=input(print("Sorry, I didn't understand. Please enter 'Y' for yes, or 'N' for no."))
else:
print("Hmm.. You don't quite have the right combination yet!")
I know the quit() is a function, but I also tried the code with it removed and it still returned a None. I have never had this problem with other programs I wrote that used the same function I am using in this code.
For this assignment, we are supposed to implement the quit function into the code, or some variation of it but we haven't learned about a return for functions (this code isn't supposed to have any author defined functions) and it seems that the only answer I can find online is to do with a return. I thought I would try my luck here and maybe it is just something small that I am missing.
The print function returns None, which you're then passing to input, remove the calls to print, since input already takes care of printing the string passed.
Instead of:
play=input(print("Would you like to play again? Type 'Y' for yes and 'N' for no."))
Use:
play=input("Would you like to play again? Type 'Y' for yes and 'N' for no.")
The line where you create the variable play. You misuse the input function the prompt you write in the function already is displayed for the user. However by putting in print() you return none.
That line should be:
play = input("Would you like to play again? Type 'Y' for yes and 'N' for no.")
P.S. you should try and conform to the PEP 8 - python style guide

Python is saying that a variable has not been assigned when it has

import random
import time
name=input("Welcome to the game what is your name")
print(("This is a numbers game"),(name),("you will be playing against the computer."))
print("The idea of the game is to get closer to 21 to the computer without going over 21"),
ready="N"
ready=input("Are you ready to play the game yet?").lower
if ready=="yes" or ready=="y":
score=0
while (score)<21 and (ready == "Y" or ready == "Yes" or ready =="YES" or ready == "yes" or ready =="y"):
player1=random.randint(1,21)
score=(score+player1)
time.sleep(3)
print(("you have scored"),(score))
if score <21:
ready=input("Do you want to add more to your score?")
if score>21: *THE PROBLEMS ON THIS LINE HERE*
print("Sorry Over 21 , The Computer Wins!")
else:
print("ok Well done let us see what the computer can do with their turn")
computerscore=0
while(computerscore)<21 and (computerscore)<(score):
computer=random.randint(1,21)
computerscore=(computerscore+computer)
time.sleep(3)
print(("The computer has scored"),(computerscore))
if (computerscore)<=21 and (computerscore)>(score):
print("Sorry the computer wins")
else:
print("You win well done")
break
I get an error that says if score>21:
NameError: name 'score' is not defined
but I have put score=0 so isn't that defining it?
I am guessing you are inputting the value yes correctly, the issue may be because of the line -
ready=input("Are you ready to play the game yet?").lower
You are assigning the reference to the lower function in ready , instead you should call lower() and assign the return value in ready . Example -
ready=input("Are you ready to play the game yet?").lower()
Also, if you want your code to work, when you do not input ready as yes , you should set score=0 , before the if condition - if ready=="yes" or ready=="y":
The variable score is declared inside an if block.
Suppose ready is different from "yes" and "y", then the line score=0 is never reached.
So if score>21: raises an error.
You have to set a default value like score = 0 before entering to the first if condition.
Moreover, you made a typo:
ready=input("Are you ready to play the game yet?").lower
You should call the function using .lower().
You need to intend the if score>21: line and everything that follows so that part of the code is included within the upper if coverage.
import random
import time
name=input("Wecome to the game what is your name")
print(("This is a numbers game"),(name),("you will be playing against the computer."))
print("The idea of the game is to get closer to 21 to the computer without going over 21"),
ready="N"
ready=input("Are you ready to play the game yet?").lower
if ready=="yes" or ready=="y":
score=0
while (score)<21 and (ready == "Y" or ready == "Yes" or ready =="YES" or ready == "yes" or ready =="y"):
player1=random.randint(1,21)
score=(score+player1)
time.sleep(3)
print(("you have scored"),(score))
if score <21:
ready=input("Do you want to add more to your score?")
if score>21: *THE PROBLEMS ON THIS LINE HERE*
print("Sorry Over 21 , The Computer Wins!")
else:
print("ok Well done let us see what the computer can do with their turn")
#same with the rest
On a different note, this script might be flawed because there is a lot of possibility that someone will key in something different. You may want to include in the line:
ready=input("Are you ready to play the game yet? Type 'Y' for Yes").lower()
some more text about what you want the player to specifically put in.
However, as mentioned above, the main point is lower(), this contributes to the error.

How to loop back to the beginning of a programme - Python [duplicate]

This question already has answers here:
How to make program go back to the top of the code instead of closing [duplicate]
(7 answers)
Closed 8 years ago.
I've written a BMI calculator in python 3.4 and at the end I'd like to ask whether the user would like to use the calculator again and if yes go back to the beginning of the code. I've got this so far. Any help is very welcome :-)
#Asks if the user would like to use the calculator again
again =input("Thank you again for using this calculator, would you like to try again? Please type y for yes or n for no-")
while(again != "n") and (again != "y"):
again =input("Please type a valid response. Would you like to try again? Please type y for yes or n for no-")
if again == "n" :
print("Thank you, bye!")
elif again == "y" :
....
Wrap the whole code into a loop:
while True:
indenting every other line by 4 characters.
Whenever you want to "restart from the beginning", use statement
continue
Whenever you want to terminate the loop and proceed after it, use
break
If you want to terminate the whole program, import sys at the start of your code (before the while True: -- no use repeating the import!-) and whenever you want to terminate the program, use
sys.exit()
You just need to call the function if the user wants to start again:
def calculate():
# do work
return play_again()
def play_again():
while True:
again = input("Thank you again for using this calculator, would you like to try again? Please type y for yes or n for no-")
if again not in {"y","n"}:
print("please enter valid input")
elif again == "n":
return "Thank you, bye!"
elif again == "y":
# call function to start the calc again
return calculate()
calculate()

Categories

Resources