Force Python code to restart itself properly - python

I have tried to figure out a way on how to restart my code in Python, but I can't get it to work properly.
if keepLooping == True:
if userInput == randomNumber:
if attempt == 1:
print()
print("Correct, First try!")
stop = time.time()
print("It took", int(stop - start), "seconds.")
replay = input("Do you want to play again?: ")
if replay.lower() in ("yes"):
print()
os.execl(sys.executable, '"{}"'.format(sys.executable), *sys.argv) # Restart code. You are here
elif replay.lower() in ("no"):
break
else:
print("Invalid input, Yes or No?")
continue # Restart segment. You are here
replayAttempt += 1
print()
As you can see, I have tried using os.execl(sys.executable, '"{}"'.format(sys.executable), *sys.argv). Sure, it works, but then one of my inputs turn red, as you can see here. I have been trying to solve this but I can't find a solution.
I found a solution for the text being red, I added '\033[37m' before my inputs. The only problem I have now is that it can only restart once. When I try it again I get this error code here.

One way to this is to encapsulate thing into function
going from this
#start of scrip
#... game logic
#end of script
to
def game():
#...game logic
game()
encapsulated like this allow for easier reuse of stuff, and allow you to reduce repetition, if you do same thing in your code two or more times that is when you should factor that out into its own function, that is the DRY principle, Don't Repeat Yourself.
You can do something like this for example
def game():
#...game logic
return game_result
def main():
done=False
result=[]
while not done:
result.append( game() )
reply = input("Do you want to play again?: ")
if reply=="no":
done=True
#display the result in a nice way
main()
Here the main function do a couple of simple thing, play one round of the game, save the result, ask if you want to play again and display the result, and the game function do all the heavy work of playing the game.
Here is a simple working example of guess the number between 0 and 10
import random
def game(lower,upper):
answer = str(random.randint(lower, upper))
user_answer = input(f"Guess a number between {lower} and {upper}: ")
game_result = user_answer == answer
if game_result:
print("you win")
else:
print("you lose, the answer was:",answer)
return game_result
def main(lower=0,upper=10):
done=False
result=[]
while not done:
result.append( game(lower,upper) )
reply = input("Do you want to play again?: ")
if reply=="no":
done=True
print("Your result were",sum(result),"/",len(result) )
main()
Notice that the game function take 2 arguments, so you can play this game not just with 0 and 10, but any two number you desire, in turn the main function also take those same arguments but assign them default value so if you don't call this function with any of them it will use those default value and use them to call the game function, doing so allow for flexibility that you wouldn't have if you lock it to just 0 and 10 in this case.
(the sum(result) is because boolean are a subclass of int(numbers) so in math operation they are True==1 and False==0)

Related

Why does my code make me type "yes" or "no" twice to get the result I want instead of just once?

Why does this code make me type yes or no twice to get the result I want instead of just once?
This is for the python dice roll text game, btw...
import random
min = 1
max = 20
# <!--TWO D-20's, A-LA DUNGEONS AND DRAGAONS--!>
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print("Rolling the dice")
print("The values are --- ")
print(random.randint(min, max))
print(random.randint(min, max))
roll_again = input("Would you like to play again?")
answer = input()
if answer == ('yes'):print("OK, here we go!")
elif answer == ("no"):print("Sorry about that, please try again another time.")
I am entering into a python class on Monday, this is one of the more common types of beginners code (granted I spiced it up by changing the dice from 6 sided to 20 sided, but it's more fun that way...lol) that I have read in some of the python books and sites I have visited, so I wanted to kind of get my feet wet a bit before I start my class.
So, any idea why I have to type yes or no twice, hitting enter after each time, to get it to run properly?
For the record, I am on Win10 right now but I also mostly use Parrot Security OS (Linux)...
Thanks for any and all feedback which anyone can provide...I know it's probably a stupid noob mistake or oversight, since I don't really know or understand the basics, but the quicker I can grasp them the better...
Python's function input() asks for users to input and waits the answer. As it can be seen in your code, you're doing it two times:
roll_again = input("Would you like to play again?")
answer = input()
The variable roll_again is being redeclarated to the first user's input, then the variable answer is getting the second user's input. You maybe meant to do something like:
roll_again = input("Would you like to play again?")
answer = roll_again
But first of all, there is no need to create an answer variable, you could simply use the roll_again on the if. Also the if statement is out of the while so your code might not work as you're trying to anyways~ (it will re-roll if user inputs yes but it will not print the message you're trying to; that will only happen when the user inputs no as that will go out of the while and blah blah blah)
This should be alright:
import random
min = 1
max = 20
# <!--TWO D-20's, A-LA DUNGEONS AND DRAGAONS--!>
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print("Rolling the dice")
print("The values are --- ")
print(random.randint(min, max))
print(random.randint(min, max))
roll_again = input("Would you like to play again?")
if roll_again == 'yes' or roll_again == 'y': print("OK, here we go!")
else: print("Sorry about that, please try again another time.")
Every time you call the input() function, it prompts for input. Since you call it twice for each iteration of your while loop, the user is prompted twice per iteration. You should instead only call the input() function once in your while loop.
You can also avoid using the answer variable if you just use the roll_again variable for your conditions for your if and elif.

How do I stop a while loop if something happens inside a function that should stop the itterations?

Hello fellow programmers! I am a beginner to python and a couple months ago, I decided to start my own little project to help my understanding of the whole development process in Python. I briefly know all the basic syntax but I was wondering how I could make something inside a function call the end of the while loop.
I am creating a simple terminal number guessing game, and it works by the player having several tries of guessing a number between 1 and 10 (I currently made it to be just 1 to test some things in the code).
If a player gets the number correct, the level should end and the player will then progress to the next level of the game. I tried to make a variable and make a true false statement but I can't manipulate variables in function inside of a while loop.
I am wondering how I can make it so that the game just ends when the player gets the correct number, I will include my code down here so you guys will have more context:
import random
import numpy
import time
def get_name(time):
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
# The Variable 'tries' is the indication of how many tries you have left
tries = 1
while tries < 6:
def try_again(get_number, random, time):
# This is to ask the player to try again
answer = (input(" Do you want to try again?"))
time.sleep(2)
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
else:
print("Thank you for playing the game, I hope you have better luck next time")
def find_rand_num(get_number, random, time):
num_list = [1,1]
number = random.choice(num_list)
# Asks the player for the number
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
try_again(get_number, random, time)
def get_number(random, try_again, find_rand_num, time):
# This chooses the number that the player will have to guess
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
find_rand_num(get_number, random, time)
if tries < 2:
get_name(time)
tries += 1
get_number(random, try_again, find_rand_num, time)
else:
tries += 1
get_number(random, try_again, find_rand_num, time)
if tries > 5:
break
I apologize for some of the formatting in the code, I tried my best to look as accurate as it is in my IDE. My dad would usually help me with those types of questions but it appears I know more python than my dad at this point since he works with front end web development. So, back to my original question, how do I make so that if this statement:
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
is true, the while loop ends? Also, how does my code look? I put some time into making it look neat and I am interested from an expert's point of view. I once read that in programming, less is more, so I am trying to accomplish more with less with my code.
Thank you for taking the time to read this, and I would be very grateful if some of you have any solutions to my problem. Have a great day!
There were too many bugs in your code. First of all, you never used the parameters you passed in your functions, so I don't see a reason for them to stay there. Then you need to return something out of your functions to use them for breaking conditions (for example True/False). Lastly, I guess calling functions separately is much more convenient in your case since you need to do some checking before proceeding (Not inside each other). So, this is the code I ended up with:
import random
import time
def get_name():
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
def try_again():
answer = (input("Do you want to try again? "))
time.sleep(2)
# Added return True/False to check whether user wants to play again or not
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
return True
else:
print("Thank you for playing the game, I hope you have better luck next time")
return False
# Joined get_number and find_random_number since get_number was doing nothing than calling find_rand_num
def find_rand_num():
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
num_list = [1,1]
number = random.choice(num_list)
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
# Added return to check if correct answer is found or not
return "Found"
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
tries = 1
while tries < 6:
if tries < 2:
get_name()
res = find_rand_num()
if res == "Found":
break
checker = try_again()
if checker is False:
break
# Removed redundant if/break since while will do it itself
tries += 1

How to update a variable within multiple functions: Powerball game

New to Python, but learning through struggling and trying to make good practices. Hoping someone can point me in the right direction for my python program: the powerball. It's between the computer and user, where each pick 3 unique (non duplicated) numbers between 1-9, and a powerball number between 1-3. I wanted to add a money variable that would be shared between the main() function, (which tells you 'welcome' and 'your current money is: (money)), and also shared between the compare_winnings() function, which compares my two lists, and adds the total to the (money) variable.
I've done some research through google and SO, and found that placing my money variable outside of every function turns it into a 'global variable', which seems useful since it'll be used in 2 functions. I've also learned that using the syntax 'global' is bad practice. However, the code runs fine and within the compare_winnings() function, the money is updated. When the game prompts you if you would like to play again (another function), it then starts over, and the money is back to its original value. (which starts at 20).
def main():
print("Each ticket costs $1. Your winnings will be totaled. Current money is",money, "dollars." )
start = input("\n Are you ready? [y/n]: ")
if start == "y" or start == "yes":
#erased variables for legibility; gathers numbers from computer and user
compare_winnings(actual, chosen,cpb, comp_cpb,money)
else:
play_again()
def compare_winnings(actual, chosen, cpb, comp_cpb,money):
counter = 0
print("You chose: ", chosen) #user-inputted
print("Ticket was actually: ", actual) #random (actual)
same_values = set(actual) & set(chosen)
#print ("These are the values that are the same",same_values)
if len(same_values) > 0:
counter += len(same_values)
print("Numbers correct was : ",counter)
if counter == 1 and cpb != comp_cpb :
print("You won $1")
money += 1
print("total money is:", money)
play_again()
def play_again():
play = input("Do you want to play again? ")
if play == "y" or play == "yes":
main()
else:
print("Program will exit. Thanks for playing.")
I expect for the money variable to be updated (and kept) until they decide to stop playing the game. However, it seems to be restarted when they decide to play again and or at main().

Need help fixing random number

I'm learning Python and was working on the random dice throw. When I run it, it repeats the same number that is first shown after asked if you want to play again. I need help finding where I'm going wrong here.
I've tried moving code around and also putting different varieties of the code. I'm just stumped.
import sys
import random
import time
greeting = "Welcome to my Dice Game!"
roll = "Lets roll this die!"
die = random.randint(0, 6)
print(greeting)
time.sleep(2)
answer = input("Want to play?")
while answer == "yes" or answer == "y":
print(roll)
time.sleep(2)
print(die)
answer = input("Want to play again?")
print("Thanks for playing!")
This is what I get:
Welcome to my Dice Game!
Want to play?yes
Lets roll this die!
5
Want to play again?yes
Lets roll this die!
5
Want to play again?y
Lets roll this die!
5
You need to recompute the value of the dice each time in your loop like:
import sys
import random
import time
greeting = "Welcome to my Dice Game!"
roll = "Lets roll this die!"
print(greeting)
time.sleep(2)
answer = input("Want to play?")
while answer == "yes" or answer == "y":
print(roll)
time.sleep(2)
die = random.randint(0, 6) # recompute it here instead
print(die)
answer = input("Want to play again?")
print("Thanks for playing!")
When you run the command die = random.randint(0, 6), what you're telling Python is "Use the random.randint() function to pick a random integer between 1 and 6, and then set the variable named die equal to the integer that got chosen". Once that's done, the rest of your code doesn't do anything to update the value of die. This means print(die) within the loop is just going to keep printing whatever value it was initially given. In other words, the command die = random.randint(0, 6) doesn't mean "Re-run the command random.randint(0, 6) and get another random number each and every time I refer to die". Rather, die is just some variable with a specific, constant value.
Since random.randint() is what does the actual number generation, one way to keep updating die is to simply move the command you have outside of the loop to the inside of the loop:
while answer == "yes" or answer == "y":
print(roll)
die = random.randint(0, 6) # Generate a new random number, then assign it to 'die'
time.sleep(2)
print(die)
answer = input("Want to play again?")
In fact, if you aren't really doing anything with the number other than printing it, you could forget using a variable altogether and just stick the random.randint() command inside of your print command:
while answer == "yes" or answer == "y":
print(roll)
time.sleep(2)
print(random.randint(0, 6))
answer = input("Want to play again?")

How to break out of while loop in Python?

I have to make this game for my comp class, and I can't figure out how how break out of this loop. See, I have to play against the "computer," by rolling bigger numbers, and seeing who has the bigger score. But I can't figure out how to "break" from my turn, and transition to the computers turn. I need "Q" (quit) to signal the beginning of the computers turn, but I don't know how to do it.
ans=(R)
while True:
print('Your score is so far '+str(myScore)+'.')
print("Would you like to roll or quit?")
ans=input("Roll...")
if ans=='R':
R=random.randint(1, 8)
print("You rolled a "+str(R)+".")
myScore=R+myScore
if ans=='Q':
print("Now I'll see if I can break your score...")
break
A couple of changes mean that only an R or r will roll. Any other character will quit
import random
while True:
print('Your score so far is {}.'.format(myScore))
print("Would you like to roll or quit?")
ans = input("Roll...")
if ans.lower() == 'r':
R = np.random.randint(1, 8)
print("You rolled a {}.".format(R))
myScore = R + myScore
else:
print("Now I'll see if I can break your score...")
break
What I would do is run the loop until the ans is Q
ans=(R)
while not ans=='Q':
print('Your score is so far '+str(myScore)+'.')
print("Would you like to roll or quit?")
ans=input("Roll...")
if ans=='R':
R=random.randint(1, 8)
print("You rolled a "+str(R)+".")
myScore=R+myScore
Don't use while True and break statements. It's bad programming.
Imagine you come to debug someone else's code and you see a while True on line 1 and then have to trawl your way through another 200 lines of code with 15 break statements in it, having to read umpteen lines of code for each one to work out what actually causes it to get to the break. You'd want to kill them...a lot.
The condition that causes a while loop to stop iterating should always be clear from the while loop line of code itself without having to look elsewhere.
Phil has the "correct" solution, as it has a clear end condition right there in the while loop statement itself.
ans=(R)
while True:
print('Your score is so far '+str(myScore)+'.')
print("Would you like to roll or quit?")
ans=input("Roll...")
if ans=='R':
R=random.randint(1, 8)
print("You rolled a "+str(R)+".")
myScore=R+myScore
else:
print("Now I'll see if I can break your score...")
ans = False
break
Walrus operator (assignment expressions added to python 3.8) and while-loop-else-clause can do it more pythonic:
myScore = 0
while ans := input("Roll...").lower() == "r":
# ... do something
else:
print("Now I'll see if I can break your score...")

Categories