How do I re-run code in Python? - python

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

Related

Python 3 Y/N Loop Issue

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

Code not printing what I seek

For the first bit, as I print out the "ask2", it prints out "exit" as opposed to the licence plate that it's supposed to be printing.
ask = input("-Would you like to 1 input an existing number plate\n--or 2 view a random number\n1 or 2: ")
ask2 = ""
plate = ""
if int(ask) == 1:
ask2 = ""
print("========================================================================")
while ask2 != 'exit':
ask2 = input ("Please enter it in such form (XX00XXX): ").lower()
# I had no idea that re existed, so I had to look it up.
# As your if-statement with re gave an error, I used this similar method for checking the format.
# I cannot tell you why yours didn't work, sorry.
valid = re.compile("[a-z][a-z]\d\d[a-z][a-z][a-z]\Z")
#b will start and end the program, meaning no more than 3-4 letters will be used.
# The code which tells the user to enter the right format (keeps looping)
# User can exit the loop by typing 'exit'
while (not valid.match(ask2)) and (ask2 != 'exit'):
print("========================================================================")
print("You can exit the validation by typing 'exit'.")
time.sleep(0.5)
print("========================================================================")
ask2 = input("Or stick to the rules, and enter it in such form (XX00XXX): ").lower()
if valid.match(ask2):
print("========================================================================\nVerification Success!")
ask2 = 'exit' # People generally try to avoid 'break' when possible, so I did it this way (same effect)
**print("The program, will determine whether or not the car "+str(plate),str(ask)+" is travelling more than the speed limit")**
Also I am looking for a few good codes that are good for appending (putting the data in a list), and printing.
This is what I've done;
while tryagain not in ["y","n","Y","N"]:
tryagain = input("Please enter y or n")
if tryagain.lower() == ["y","Y"]:
do_the_quiz()
if tryagain==["n","N"]:
cars.append(plate+": "+str(x))
print(cars)
When you print ask2 it prints 'exit' because you set it to exit with ask2 = 'exit', and your loop cannot terminate before ask2 is set to 'exit'.
You could use ask2 for the user's input, and another variable loop to determine when to exit the loop. For example:
loop = True
while loop:
# ...
if valid.match(ask2) or ask2 == 'exit':
loop = False
I am not quite sure what your other block of code is trying to achieve, but the way that you test tryagain is incorrect, it will never be equal to a two element list such as ["y","Y"], perhaps you meant to use in?, This change shows one way to at least fix that problem:
while tryagain not in ["y","n","Y","N"]:
tryagain = input("Please enter y or n")
if tryagain.lower() == "y":
do_the_quiz()
else:
cars.append(plate+": "+str(x))
print(cars)

Need Solution for incorrect guess loop

Ok, I am creating a memory game. I have developed where the programme asks the user what word was removed, and have successfully developed the part that moves on if they get it right. However, I am struggling to find how to get it to only fail the user if they get it wrong three times. Here's what I have so far:
def q1():
qone + 1
print("\n"*2)
while qone <= 3:
question1 = input("Which word has been removed? ")
if question1 == removed:
print("\n"*1)
print("Correct")
print("\n"*2)
q2()
else:
print("Incorrect")
q1()
else:
print("You're all out of guesses!")
input("Press enter to return to the menu")
menu()
return
`
My approach is to remove recursion and simply increase the counter of failed tries.
def q1():
qone = 0
print("\n"*2)
while qone < 3:
question1 = input("Which word has been removed? ")
if question1 == removed:
print("\n"*1)
print("Correct")
print("\n"*2)
q2()
return
else:
print("Incorrect")
qone += 1
print("You're all out of guesses!")
input("Press enter to return to the menu")
menu()
return
When you do qone + 1, you need to assign it to something (so perhaps qone += 1)
What is the else outside the while loop linked to?
You seem to have a recursive definition going. Think carefully about the chain of calls that would be made and what your base case should be. Once you know these things, it would be easier for you to write the code. Also, think about whether you need recursion at all: in this case, it doesn't seem like you would.
You should not have the function calling itself, use range for the loop, if the user gets the question correct go to the next question, if they get it wrong print the output:
def q1(removed):
print("\n"*2)
for i in range(3):
question1 = input("Which word has been removed? ")
if question1 == removed:
print("\nCorrect")
return q2()
print("\n\nIncorrect")
input("You're all out of guesses!\nPress enter to return to the menu")
return menu()
If the user has three bad guesses the loop will end and you will hit the "You're all out of guesses!\nPress enter to return to the menu"

Python 2.7 While Loop Issue

I am trying to write a code for a text based chat-bot as my first full scale project and I am having a weird problem with while loops that I can't figure out. My primary loop is dependent on text input, what is supposed to happen is when the user types "bye" the program ends. The only problem is when I run it, no matter what I say to it, it just prints out the same response over and over until I hit cntrl.+c or close the window. Here is the code:
import datetime
print("Hi I am ChatBot V 0.0.1. I am here to converse. ")
user_name=raw_input("What is your name?")
print("Hello " + user_name + "!")
user_input=raw_input().lower().replace(" ","").replace("?","")
is_user_finished=0
while (is_user_finished == 0):
if user_input == "hi" or "hello":
print("Hello. How are you?")
elif user_input == "whatisyourname":
print("I do not have a name at the moment. What do you think I should be named?")
user_input=raw_input().lower().replace(" ","").replace("?","")
print("Good choice! I like that name!")
elif "where" and "you" in user_input:
print("I was typed up by some kid in California")
else:
print("I do not currently understand what you said. Sorry.")
if user_input == "bye":
print("Good bye. It was nice talking to you!")
is_user_finished = 1
What happens is that the line
if user_input == "hi" or "hello":
don't do what you think. Instead, you should do
if user_input == "hi" or user_input == "hello":
or even, in a more compact way:
if user_input in ["hi","hello"]:
Something similar happens with the line
elif "where" and "you" in user_input:
which should be
elif "where" in user_input and "you" in user_input:
syntax issue.
the correct form should be : if A == B or A == C, instead of A == B or C, which is incorrect.
You should change the line
if user_input == "hi" or "hello": to if user_input == "hi" or user_input == "hello":
and
"where" and "you" in user_input: to "where" in user_input and "you" in user_input:,
because "hello" and "where" is always True .
Besides you should put user_input=raw_input().lower().replace(" ","").replace("?","") into the while loop.
Provided you have proper indentation, which if the loop keeps running I assume you do, the problem, besides the things pointed out above about proper use of compound if statements is you need to add a "break" to the "bye" case.
if user_input == "bye":
print("Good bye. It was nice talking to you!")
is_user_finished = 1
break

How to properly quit a program in python

Im a middle school student, and im starting to learn coding in python. I have been watching video tutorials, but i cant seem to figure out how to make the game quit if you type q. here what i have..
print('How old do you thing Fred the Chicken is?')
number = 17
Quit = q
run = 17
while run:
guess = int(input('Enter What You Think His Age Is....'))
print('How old do you thing Fred the Chicken is?')
number = 17
Quit = 'q'
run = 17
while run:
guess = int(input('Enter What You Think His Age Is....'))
if guess == number:
print('Yes :D That is his age...')
run = False
elif guess < number:
print('No, Guess a little higher...')
elif guess > number:
print('No, Guess a little lower....')
print('Game Over')
print('Press Q to Quit')
if run == False:
choice = input('Press Q to Quit')
if choice == 'q'
import sys
exit(0)
Getting Q as input
Quit = int(input('Press Q to Quit')
You're asking for Q as the input, but only accepting an int. So take off the int part:
Quit = input('Press Q to Quit')
Now Quit will be whatever the user typed in, so let's check for "Q" instead of True:
if Quit == "Q":
Instead of sys.exit(0), you can probably just end your while look with break or just return if you're in a function.
Also, I don't recommend the name "Quit" for a variable that just stores user input, since it will end up confusing.
And remember that indentation is important in Python, so it needs to be:
if run == False:
choice = input('Press Q to Quit')
if choice == "Q":
# break or return or..
import sys
sys.exit(0)
That may just be a copy/paste error though.
Indentation and Syntax
I fixed the indentation and removed some extraneous code (since you duplicate the outer loop and some of the print statements) and got this:
print('How old do you thing Fred the Chicken is?')
number = 17
run = True
while run:
guess = int(input('Enter What You Think His Age Is....t'))
if guess == number:
print('Yes :D That is his age...')
run = False
elif guess < number:
print('No, Guess a little higher...')
elif guess > number:
print('No, Guess a little lower....')
if run == False:
print('Game Over')
choice = input('Press Q to Quit')
if choice == 'q'
break
This gave me a syntax error:
blong#ubuntu:~$ python3 chicken.py
File "chicken.py", line 23
if choice == 'q'
^
SyntaxError: invalid syntax
So Python is saying there's something wrong after the if statement. If you look at the other if statements, you'll notice that this one is missing the : at the end, so change it to:
if choice == 'q':
So with that change the program runs, and seems to do what you want.
Some suggestions
Your instructions say "Press Q to Quit", but you actually only accept "q" to quit. You may want to accept both. Python has an operator called or, which takes two truth values (True or False) and returns True if either of them is True (it actually does more than this with values besides True and False, see the documentation if you're interested).
Examples:
>> True or True
True
>>> True or False
True
>>> False or True
True
>>> False or False
False
So we can ask for Q or q with if choice == "Q" or choice == "q":.
Another option is to convert the string to lower case and only check for q, using if choice.lower() == "q":. If choice was Q, it would first convert it to q (with the .lower()), then do the comparison.
Your number is always 17. Python has a function called random.randint() that will give you a random number, which might make the game more fun. For example, this would make the chicken's age between 5 and 20 (inclusive):
number = random.randint(5, 20)
There are many ways to exit certain things. For loops, it is using break, and for functions you can use return. However, for programs, if you wish to exit your program before interpretation finishes (end of the script) there are two different types of exit() functions. There is sys.exit() which is part of the sys module, and there is exit() and quit() which is a built-in. However, sys.exit() is intended for programs not in IDLE (python interactive), while the built-in exit() and quit() functions are intended for use in IDLE.
You can use the break statement to break out of a while loop:
while True:
guess = int(input("...")
# ...rest of your game's logic...
# Allow breaking out of the loop
choice = input("Enter Q to quit, or press return to continue")
if choice.lower() == "q":
break
That means the interpreter exits the while loop, continues looking for more commands to run, but reaches the end of the file! Python will then exit automatically - there's no need to call sys.exit
(as an aside, you should rarely use sys.exit, it's really just used to set non-zero exit-status, not for controlling how your program works, like escaping from a while loop)
Finally, the main problem with the code you posted is indentation - you need to put the appropriate number of spaces at the start of each line - where you have something like:
if run == False:
choice = input('Press Q to Quit')
It must be like this:
if run == False:
choice = input('Press Q to Quit')
Same with anything like while, for, if and so on.

Categories

Resources