Beginner project review.
I made a simple guess the random number game and set it up so it should run continuously until you say you don't want to play again. I used some code I found online for the base of the game. So i was wondering if you guys could look at the end of the code and tell me if i did this the best way possible. I've tested it a bunch and it does. Just wondering if im doing it the most efficient way.
def playAgainfunc():
print("You won't play again. To play again press 'Y'. To exit press anything else.")
playAgainresponse = input()
if playAgainresponse == 'Y':
baseGamefunction()
playAgainfunc()
if playAgainresponse == 'y':
baseGamefunction()
playAgainfunc()
else:
print("Ok, I didn't want to play again anyway")
baseGamefunction()
playAgainfunc()
Thanks!
def baseGamefunction():
....
while True:
baseGamefunction()
if input("Do you want to play again? (y/N) ").lower() not in ["y", "yes"]:
break
Use a while loop and quit if the user inputs anything other than y or yes.
If using python2, use raw_input() instead of input().
Although I have no experience with Python myself, I do have a little bit with Java. I think it would be more efficient to use a while loop instead, if you have learned them. As a general rule of thumb, if you are repeating code, you will be losing a bit of efficiency.
while playAgain.lower() == 'y':
baseGamefunction()
playAgainfunc()
else:
print("Ok, I didn't want to play again anyway")
It's not efficient in terms of code volume as you do a separate tests for the upper and lower case Y. Instead convert the input to lower (or upper) case and test against that case.
See the below code, which defines your functionality in less code, with no repetition.
def baseGameFunction():
print('placeholder for actual game.')
while True:
baseGameFunction()
resp = input('play again? ')
if resp.lower() != 'y':
break
print('thanks for playing')
Related
I am just starting out on a python Nat5 course so I'm sorry if the answer is glaringly obvious but what I'm trying to do is ask the user if they want the code to restart or not and ask again if the user inputs an incorrect answer
print("would you like to ask again?")
go = input("enter yes/y or no/n")
if(go == 'y') or (go == 'yes'):
#replay here
elif(go == 'n') or (go == 'no'):
exit()
else:
print("It's a yes or no question")
#ask to replay again
I do not know if this is the best practice, but it works for me and I have had no issues.
Put the code in a function
def code():
#insert the code here
and then call the function
if (go=='y'):
code()
It is also worth noting that you will need to also call the function at the end of the code so that it actually runs the first time round.
I'm trying to teach myself python, I recently learned how to use raw input in an if statement (yes or no). However, when I answer yes, the program asks me the same if question.
Can anyone help? I'm not really good at programming but love doing it.
import time
name = raw_input("what is your name? ")
print "Hello " + name
#yes no statement with raw input
while True:
yesno = raw_input("would you like to play hangman?")
if yesno.lower().startswith("n"):
print("ok bye")
exit()
elif yesno.lower().startswith("y"):
print("cool, let me prep for e second")
time.sleep(5)
# this is where it goes wrong
# below is what is supposed to follow
word = "kaasblok"
guesses = ''
turns = 6
while turns > 0:
If you use a while true loop, your program will keep on running.
In Python, the tabs or whitespace tell the interpreter when a loop ends.
So what happens in your code is this:
While True is running,
It asks if you want to play
If you write no it works as intended
If you write yes, it sees that the loop is over so it restarts.
Also your code has several errors, like syntax from both Python 3 and Python 2 and a while loop that doesn't terminate.
I wrote some updates to make the code sort of work but it is not "good" code because I tried to keep it as similar as possible. Also I chose a syntax (python 3) so make sure to change that if you're using Python 2.
I recommend you modularize your code and look at other people's code, it'll make your code better. Avoid using a while True loop, at least at the beginning. The code I wrote sort of tries to address it, but it probably doesn't do such a great job.
Maybe try editing the code a bit and updating with an answer later? I think you meant to write input, not raw_input but it could be that's the way you do it in Python 2. You should really learn Python 3 if you're trying to pick up Python btw as Python 2 is at its end of life cycle.
Place your game in the loop and it'll run. Try something like this:
import time
name = input("what is your name? ")
word = "kaasblok"
turns = 6
print("Hello " + name)
#yes no statement with raw input
trueorfalse = True
while trueorfalse:
yesno = input("would you like to play hangman?")
if yesno.lower().startswith("n"):
print("ok bye")
#trueorfalse = False
break
elif yesno.lower().startswith("y"):
print("cool, let me prep...")
time.sleep(1)
# Place your code in the elif block
while turns > 0:
guess = input("what is the word")
if guess == word:
print('win')
#trueorfalse = False
break
else:
turns -=1
print("you have these many turns left", turns)
print("you lost")
break
All that's missing is a way to break out of the while loop. So, use the break command.
import time
name = raw_input("what is your name? ")
print "Hello " + name
#yes no statement with raw input
while True:
yesno = raw_input("would you like to play hangman?")
if yesno.lower().startswith("n"):
print("ok bye")
exit()
elif yesno.lower().startswith("y"):
print("cool, let me prep for e second")
time.sleep(5)
break # <-- break out of of the current loop
print "made it!"
I am trying to add a function that asks the player If they want to restart and If they type yes, then the game should restart.
I have looked it up but found nothing that helps me
elif response_turn3 == "right":
print("You carry on down the path, whistling a merry tune.")
time.sleep(4)
print("Suddenly, a flash flood sweeps you away, freezing you to death in the cold, icy water.GAME OVER :(")
print("Try again?")
Then it would be something like
(if yes then restart)
How would this work in code?
In order to do this, I would need to define a function like game_start().
How can I do this?
Input validation, even minimal, is a useful tool.
valid_answer = False
while not valid_answer:
answer = input("Try again? (y/n)")
if answer == 'y' or answer == 'n':
valid_answer = True
if answer == 'y':
restart_game()
else:
quit()
You might want to try the input function in python.
try_again = input("Try again?")
if (try_again == True):
game_start()
And then depending on the input, you can call the function that starts the game again.
Welcome to StackOverflow.
A simple way to achieve what you require would be to use a while loop. At the end of each iteration (game) you should ask the user if they would like to continue, and if not break out of the loop.
I would suggest you take your existing code and re-cast it as a play_game function that returns when the game is over. This will allow you to terminate the game with a return statement at any point in your logic, which will probably make your logic simpler too.
Supposing you had done that, you could then write a loop like
while True:
play_game()
answer = input("Would you like to play again? ")
if not ('y' in answer.lower()):
break
The dialogue with the user could be more sophisticated, but this is the basic idea.
Well, it isn't possible to restart a script only using python commands (You can use os.System() but it's rather complicated). But you can enclose the script in a function game() then call it when the user says yes.
elif response_turn3 == "right":
print("You carry on down the path, whistling a merry tune.")
time.sleep(4)
print("Suddenly, a flash flood sweeps you away, freezing you to death in the cold, icy water. GAME OVER :(")
response=input("Try again?")
if(response=="yes"):
game()
Hi guys I just recently started doing my own projects and I'm hoping that as I work through these things that I can make sure to make the code as neat and polished as possible since I am mostly teaching myself.
So I was wondering if this was the best way to do this Dice rolling code:
Game = input("Hello there! Would you like to bet your luck on a dice roll?\n")
if Game == "yes"or"Yes":
print("Well great! Here we go!");
import random;
print(random.randint(1, 6));
else:
print("I guess next time then...");
specifically around the "if statement" and trying to account for people using capitalization or non-capitalization. Or just how to create a better way for people to put in a variety of answers.
Thank you
So I was wondering if this was the best way to do this Dice rolling
code:
To be short: No.
Game = input("Hello there! Would you like to bet your luck on a dice roll?\n")
This will work, but it you should use lowercase for your 'Game' variable, as this style (called 'CapWords' in PEP 8) are reserved for class names.
if Game == "yes"or"Yes":
This is basicly executed as:
if (Game == "yes") or "Yes":
You see what will go wrong here? You probably want something like:
if Game == "yes" or Game == "Yes":
But even better would be to this:
if Game.lower() == "yes":
This converts the input to lower case first, so basicly ignoring any capitalization used by the user.
print("Well great! Here we go!");
Nothing wrong with this line, except the ';' are not needed in Python.
import random;
Imports should be at the top of the file.
print(random.randint(1, 6));
Again, the ';' should not be used.
else:
print("I guess next time then...");
Again, the ';' should not be used.
If I were to write this program, it would look as follows:
import random
answer = input("Hello there! Would you like to bet your luck on a dice roll?\n")
if answer.lower() == "yes":
print("Well great! Here we go!")
print(random.randint(1, 6))
else:
print("I guess next time then...")
Or just how to create a better way for people to put in a variety of answers.
If you were to expand the possible answers, your if statement would get pretty long and ugly:
if game.lower() == "yes" or game.lower() == "y" or game.lower() == "uh huh" # and so on...
So, it would be best to put these in a tuple, and then check if their answer is in the tuple:
if game.lower() in ("yes", "y", "uh huh"):
# the rest of your code here...
How do i make it loop back to the start after doing this? After each transaction, it ends and doesn't go back to see if you can pick another option.
Thanks and it's greatly appreciated.
balance=7.52
print("Hi, Welcome to the Atm.")
print("no need for pin numbers, we already know who you are")
print("please selection one of the options given beneath")
print("""
D = Deposit
W = Withdrawal
T = Transfer
B = Balance check
Q = Quick cash of 20$
E = Exit
Please select in the next line.
""")
option=input("which option would you like?:")
if option==("D"):
print("How much would you like to deposit?")
amount=(int(input("amount:")))
total=amount+balance
elif option ==("W"):
print("How much would you like to withdrawl?")
withdrawl=int(input("how much would you like to take out:?"))
if balance<withdrawl:
print("Error, insufficent funds")
print("please try again")
elif option == "T":
print("don't worry about the technicalities, we already know who you're transferring to")
transfer =int(input("How much would you like to transfer:?"))
print("you now have", balance-transfer,"dollars in your bank")
elif option=="B":
print("you currently have",balance,"dollars.")
elif option=="Q":
print("processing transaction, please await approval")
quicky=balance-20
if balance<quicky:
print("processing transaction, please await approval")
print("Error, You're broke.:(")
elif option=="E":
print("Thanks for checking with the Atm")
print("press the enter key to exit")
It seems like you are asking about a loop with a sentinel value.
Somewhere right before you print your menu, set a sentinel value:
keep_going = True
Then, preferably on the next line (before you print the first thing you want to see when it loops), you start your loop.
while keep_going: # loop until keep_going == False
As written, this is an infinite loop. Everything in the indented block beneath the while statement will be repeated, in order, forever. That's obviously not what we want -- we have to have some way to get out so we can use our computer for other things! That's where our sentinel comes in.
Build in a new menu option to allow the user to quit. Suppose you key that to "Q", and the user picks it. Then, in that branch:
elif option == 'Q':
keep_going = False
Since that's all there is in that branch, we "fall off" the bottom of the loop, then go back to the while statement, which now fails its check. Loop terminated!
By the way, you should think about reading The Python Style Guide. It's very easy to read and gives you an idea how to make your code also very easy to read. Most every Python programmer abides by it and expects others to do the same, so you should too! If you want help learning it, or aren't sure if you're doing it right, there are tools to check your code to help you keep it clean and error-free.
Happy programming!