I'm very new to Python, and I'm just having a play with making some very simple little programs to get a feel for it, so probably best to keep any explanations really simple haha!
I'm currently making a little program that asks if you want to roll a dice, rolls it, gives you the answer and asks if you want to roll again.
The issue I'm having trouble figuring out is the following (copied from console):
What is your name: Nasicus
Greetings Nasicus!
Would you like to roll the dice? [Y/N]? : Y
Let's do this!
Rolling...
You rolled a 3!
Do you want to roll again? [Y/N]?: Y
Yahoo!
Would you like to roll the dice? [Y/N]? : N
Oh, Okay. Maybe next time.
Would you like to roll the dice? [Y/N]? : N
Oh, Okay. Maybe next time.
Process finished with exit code 0
As you can see, it prompts twice when you select N before it closes.
I'm probably missing something incredibly simple, so could anyone advise how I can either A. Stop it prompting twice or (preferably for the sake of simplicity) B. Stop it asking if You want to roll the dice after you have already selected Y to roll again, and just go straight from the Let's do this! line.
Here is my code, any pointers on how to keep things tidier/more pythonic always appreciated too! I appreciated the time.sleep() probably look a little messy, but I do like the way it paces things when I run it:
import random
import time
def diceroll():
while True:
diceyn = input ("Would you like to roll the dice? [Y/N]? : ")
if diceyn == "Y":
print ("Let's do this!")
time.sleep(0.5)
print ("Rolling...")
time.sleep(1)
rand = random.randint(1, 6)
print ('You rolled a ',rand,'!', sep='')
time.sleep(0.5)
again = str(input("Do you want to roll again? [Y/N]?: "))
if again == "Y":
print ('Yahoo!')
time.sleep(0.5)
diceroll()
else:
time.sleep(0.3)
print ('Okay, bye!')
break
elif diceyn == "N":
print ("Oh, Okay. Maybe next time.")
break
input_name = input ("What is your name: ")
print ("Greetings ",input_name,"!", sep='')
time.sleep(1)
diceroll()
Thank you for your time, and I look forward to learning more :D
The problem is in this section of code:
if again == "Y":
print ('Yahoo!')
time.sleep(0.5)
diceroll()
You're recursively calling the diceroll() function, so when that recursive call finally finishes, the iteration of the current call still continues.
You're already in a while True loop, so you don't even need the recursive call. Just take it out, and let the loop continue.
You are calling diceroll recursively.
if again == "Y":
print ('Yahoo!')
time.sleep(0.5)
diceroll()
So you call diceroll() and then whenever the user is asked
Do you want to roll again
You call diceroll() again.
Here is what is happening. You have a top level diceroll().
diceroll()
Then you have another diceroll() under it like this:
diceroll()
-- diceroll()
And then you have yet another diceroll() inside it.
diceroll()
-- diceroll()
---- diceroll()
When you call the break statement, all you are doing is breaking out of that inner diceroll() loop, not the loop where you called it.
A break in the third row sends you to
diceroll()
-- diceroll()
I would just break out your actual rolling into a separate function in your diceroll() function, that way you won't confuse the paths.
import random
import time
def diceroll():
def rollIt():
time.sleep(0.5)
print ("Rolling...")
time.sleep(1)
rand = random.randint(1, 6)
print ('You rolled a ',rand,'!', sep='')
time.sleep(0.5)
while True:
diceyn = input ("Would you like to roll the dice? [Y/N]? : ")
if diceyn == "Y":
print ("Let's do this!")
rollIt()
again = str(input("Do you want to roll again? [Y/N]?: "))
if again == "Y":
print ('Yahoo!')
rollIt()
else:
time.sleep(0.3)
print ('Okay, bye!')
break
elif diceyn == "N":
print ("Oh, Okay. Maybe next time.")
break
input_name = input ("What is your name: ")
print ("Greetings ",input_name,"!", sep='')
time.sleep(1)
diceroll()
Here is the Object Oriented approach:
import random
import time
class Rolling_Dice_Game () :
def startup (self) :
prompt = ("Would you like to roll the dice? [Y/N]? : ")
if self.query_user (prompt) == 'Y' :
self.run_the_game ()
return True
else : return False
def run_the_game (self) :
print ("Let's do this")
print ('Rolling...')
time.sleep (1)
rand = random.randint (1, 6)
print ('You rolled a ', rand, '!')
time.sleep (0.5)
return True
def query_user (self, prompt) :
return input (prompt) [0].upper ()
def continue_the_game (self) :
prompt = ("Do you want to roll again? [Y/N]?: ")
if self.query_user (prompt) != 'Y' :
print ('Oh, Okay. Maybe next time.')
return False
else : return True
my_dice = Rolling_Dice_Game ()
if my_dice.startup () == True :
while my_dice.continue_the_game () == True :
my_dice.run_the_game ()
Related
I'm trying to create a game and cant get the y/n function to work
I've tried the code below and it says y is not defined or it will just skip asking and print ("Lets go!")
import time
name = input ("Hello, what is your name?")
print ("Hello," +name)
time.sleep(1)
print ("ready to play? [y/n]")
y = print ("Let's go!")
Here's how it should look like:
Hello, what is your name? xyz
Hello, xyz
ready to play? [y/n] y
Let's go!
I wanted it to wait for my input of either y or n before it said ("Let's go!")
You are not asking for input on "ready to play" line you are just printing, so therefore it is not going to wait.
First, you need to change print ("ready to play? [y/n]") to input("ready to play? [y/n]") and put it inside a variable. Next, remove y = print ("Let's go!"), and change it with this (if you want to):
ready_status = input("are you ready? [y/n]")
if ready_status == 'y':
print("let's go!")
if ready_status == 'n':
print("...")
#do anything you want
You do not have a wait command after your print prompt. Therefore it is not going to wait.
Try this method for inputting a wait time
answer = input("y/n?")
I made the beginning of a basic text adventure game, and I want it to loop whenever you die, but any examples of code I see aren't working, and thorugh research i still cant find something that could work.
print("A tale of time version 0.0.1. by Tylan Merriam")
print("you awaken, the room is dark and you cannot see. the sheets on your
bed are damp, and you hear a faint dripping sound.")
ch0pg1 = input('>: ')
if ch0pg1 == 'turn on light':
print("you flip the light on, it turns out the dripping was from a leaky
pipe above you. you see a dresser(outisde of bed) a chair with something
glinting on it(outside of bed) and a window(outisde of bed)")
ch1p1 = input('>: ')
if ch1p1 == 'stand':
print('you stand up, the game isnt finished so this is all there is,
try saying stand at the first choice or anything else')
else:
print('sorry, but i have no fricking clue what that means')
elif ch0pg1 == 'stand':
print('since you cannot see, you bump your head on a brick and collapse.
as you think of your last words you realize the only thing that comes to
mind is wushtub.')
diemessage = input('>: ')
if diemessage == 'lol':
print('i agree, now shut up, your dead')
else:
print('shut it, your dead')
else:
print('I have no clue what that means,')
You can try embedding a while loop within a while loop kind of like this.
while(1):
while(1):
# some code
# also some code
diemessage = input('>: ')
if diemessage == 'lol':
print('i agree, now shut up, your dead')
chc = input("play again? (y,n): ")
if chc == "y":
break # break this while loop which just starts again
elif chc == "n":
exit() # exit the game entirely
else:
# You can set this bit to your liking.
print("thats no answer, bye")
exit()
else:
print('shut it, your dead')
chc = input("play again? (y,n): ")
if chc == "y":
break # break this while loop which just starts again
elif chc == "n":
exit() # exit the game entirely
else:
# You can set this bit to your liking.
print("thats no answer, bye")
exit()
It simply creates a while loop for the game inside of a while loop. Break breaks out of the while loop while being ran, so it just exits and starts again. If the user chooses to quit, it stops the whole program.
You would think that we could create a function to make it easier, but when I tried breaking with a function it won't break, so you are going to have to keep pasting this in as of what I know. :P
Could do:
while (true)
{
//print statements
//whenever you die:
continue;
}
Well, you first need to define what you want to loop. Make a function called game() with your included code. Then this would work:
if diemessage == "lol":
print("something")
else:
print("Shut it, your dead")
game()
How do i get the enter key to work in this situation? I tried searching for it, but maybe i'm wording it wrong.
also, how would i get the else statement to work in this particular situation?
thank you
import random
def roll_dice():
roll = random.randint(1,6)
print("You rolled a %n " % roll)
def main():
input("Hit ENTER to roll a single dice: ")
roll_dice()
else:
print("exiting program.")
main()
You have to store input in a variable. Let it be enter.
User will hit enter and you will check if it was enter or not.
If input was an empty string then it is okay!
import random
def roll_dice():
roll = random.randint(1,6)
print("You rolled a %d " % roll)
def main():
enter = input("Hit ENTER to roll a single dice: ")
if enter == '': # hitting enter == '' empty string
roll_dice()
else:
print("exiting program.")
exit()
main()
In a case like this, would I usually do, is something like this:
if input == "":
roll_dice()
I'm not sure if thats what you are looking for, though :3
Just use:
if not input("Hit ENTER to roll a single dice: "):
roll_dice()
else:
print("exiting program.")
Also use a while loop instead, to ask user multiple times:
import random
def roll_dice():
roll = random.randint(1,6)
print("You rolled a {} ".format(roll))
def main():
while True:
if not input("Hit ENTER to roll a single dice: "):
roll_dice()
else:
print("exiting program.")
break
main()
If input() is non empty it will exit the program.
I'm fairly new to coding and have been assigned a class project, in this project to make a game I was trying to write a function that upon losing/dying the
def playAgain(): function would ask the user if they want to play again.
from sys import exit
def playAgain():
print('Do you want to play again? (yes or no)')
while True:
if input("> ").lower().startswith('yes')== True:
start()
elif input("> ").lower().startswith('no')== True:
print ('Bye for now')
exit(0)
else:
print ("I don't understand what you mean?")
This function 'should' ask the user if they want to play again and depending on if yes or no was entered it would either go to the function start() or exit.
The issue is that when the input is entered the first time it is seemingly ignored in the code and must be entered a second time for any thing to happen in the code.
This has confused me a fair amount so any input on how to resolve this issue would be greatly appreciated.
Side note - this issue doesn't appear to happen when yes is entered first meaning this is probably an issue with the elif or else statements
from sys import exit
def playAgain():
print('Do you want to play again? (yes or no)')
while True:
choice = input("> ")
if choice.lower().startswith('yes'):
start()
elif choice.lower().startswith('no'):
print ('Bye for now')
exit(0)
else:
print ("I don't understand what you mean?")
If you want to write it as a function then really you should return a value upon which to base your next step.
def playAgain():
while True:
ans = input("Do you want to play again? (yes or no) ")
if ans.lower().startswith('y'):
return True
elif ans.lower().startswith('n'):
return False
else:
print ("I don't understand what you mean?")
def start():
print ("game restarted")
if playAgain():
start()
else:
print ("Bye for now")
quit()
Note that startswith allows you to check just y and n rather than the full words yes and no
The solution is to assign a variable to the input and compare the variable as many times as you want.
from sys import exit
def playAgain():
print('Do you want to play again? (yes or no)')
while True:
inp = input("> ").lower()
if inp.startswith('y'):
start()
elif inp.startswith('n'):
print ('Bye for now')
exit(0)
else:
print ("I don't understand, what do you mean?")
I have this word un-scrambler game that just runs in CMD or the python shell. When the user either guesses the word correctly or incorrectly it says "press any key to play again"
How would I get it to start again?
Don't have the program exit after evaluating input from the user; instead, do this in a loop. For example, a simple example that doesn't even use a function:
phrase = "hello, world"
while input("Guess the phrase: ") != phrase:
print("Incorrect.") # Evaluate the input here
print("Correct") # If the user is successful
This outputs the following, with my user input shown as well:
Guess the phrase: a guess
Incorrect.
Guess the phrase: another guess
Incorrect.
Guess the phrase: hello, world
Correct
This is obviously quite simple, but the logic sounds like what you're after. A slightly more complex version of which, with defined functions for you to see where your logic would fit in, could be like this:
def game(phrase_to_guess):
return input("Guess the phrase: ") == phrase_to_guess
def main():
phrase = "hello, world"
while not game(phrase):
print("Incorrect.")
print("Correct")
main()
The output is identical.
Even the following Style works!!
Check it out.
def Loop():
r = raw_input("Would you like to restart this program?")
if r == "yes" or r == "y":
Loop()
if r == "n" or r == "no":
print "Script terminating. Goodbye."
Loop()
This is the method of executing the functions (set of statements)
repeatedly.
Hope You Like it :) :} :]
Try a loop:
while 1==1:
[your game here]
input("press any key to start again.")
Or if you want to get fancy:
restart=1
while restart!="x":
[your game here]
input("press any key to start again, or x to exit.")
Here is a template you can use to re-run a block of code. Think of #code as a placeholder for one or more lines of Python code.
def my_game_code():
#code
def foo():
while True:
my_game_code()
You could use a simple while loop:
line = "Y"
while line[0] not in ("n", "N"):
""" game here """
line = input("Play again (Y/N)?")
hope this helps
while True:
print('Your game yada-yada')
ans=input('''press o to exit or any key to continue
''')
if ans=='o':
break
A simple way is also to use boolean values, it is easier to comprehend if you are a beginner (like me). This is what I did for a group project:
restart = True
while restart:
#the program
restart = raw_input("Press any key to restart or q to quit!")
if restart == "q":
restart = False
You need to bury the code block in another code block.
Follow the instructions below:
Step 1: Top of code def main()
Step 2: restart = input("Do you want to play a game?").lower()
Step 3: Next line; if restart == "yes":
Step 4: Next line; Indent - main()
Step 5: Next line; else:
Step 6: Indent - exit()
Step 7: Indent all code under def main():
Step 8: After all code indent. Type main()
What you are doing is encapsulating the blocks of code into the main variable. The program runs once within main() variable then exits and returns to run the main varible again. Repeating the game. Hope this helps.
def main():
import random
helper= {}
helper['happy']= ["It is during our darkest moments that we must focus to see the light.",
"Tell me and I forget. Teach me and I remember. Involve me and I learn.",
"Do not go where the path may lead, go instead where there is no path and leave a trail.",
"You will face many defeats in life, but never let yourself be defeated.",
"The greatest glory in living lies not in never falling, but in rising every time we fall.",
"In the end, it's not the years in your life that count. It's the life in your years.",
"Never let the fear of striking out keep you from playing the game.",
"Life is either a daring adventure or nothing at all."]
helper['sad']= ["Dont cry because it’s over, smile because it happened.",
"Be yourself; everyone else is already taken",
"No one can make you feel inferior without your consent.",
"It’s not who you are that holds you back, its who you think you're not.",
"When you reach the end of your rope, tie a knot in it and hang on."]
answer = input ('How do you feel : ')
print("Check this out : " , random.choice(helper[answer]))
restart = input("Do you want a new quote?").lower()
if restart == "yes":
main()
else:
exit()
main()
How to rerun a code with user input [yes/no] in python ?
strong text
How to rerun a code with user input [yes/no] in python ?
strong text
inside code
def main():
try:
print("Welcome user! I am a smart calculator developed by Kushan\n'//' for Remainder\n'%' for Quotient\n'*' for Multiplication\n'/' for Division\n'^' for power")
num1 = float(input("Enter 1st number: "))
op = input("Enter operator: ")
num2 = float(input("Enter 2nd number: "))
if op == "+":
print(num1 + num2)
elif op =="-":
print(num1 - num2)
elif op =="*":
print(num1 * num2)
elif op =="/" :
print(num1 / num2)
elif op =="%":
print(num1 % num2)
elif op =="//":
print(num1 // num2)
elif op == "^":
print(num1 ** num2)
else:
print("Invalid number or operator, Valid Operators < *, /, +, -, % , // > ")
except ValueError:
print("Invalid Input, please input only numbers")
restart = input("Do you want to CALCULATE again? : ")
if restart == "yes":
main()
else:
print("Thanks! for calculating keep learning! hope you have a good day :)")
exit()
main()
strong text
You maybe trying to run the entire code with an option for user to type "yes" or "no" to run a program again without running it manually.
This is my code for a 'calculator' in which i have used this thing.
Is that your solution?
By the way this is a reference link from where i learnt to apply this function.
https://www.youtube.com/watch?v=SZdQX4gbql0&t=183s