I know how to use a while loop, but I'm not sure about the part where I need to make a command to double the previous score.
The task is to double or quit.
And this is my current code :
import random
play = 'y'
Original = 1
while play.lower() == 'y':
chance = random.randint(0,3)
if chance == 0:
print("Unlucky.... better luck next time")
else:
newnumber = Original*2
print (newnumber)
play = input("Play again?[y/n]: ")
A for-loop is better suited for your problem:
from itertools import count
import random
for pot in count():
if random.randint(0, 3) == 0:
print("Unlucky.... better luck next time")
break
print(2 ** pot)
if input("Play again?[y/n]: ").lower() != 'y':
break
You are currently repeating the same fixed output calculation over and over again:
newnumber = Original*2
Original is a constant since you only define it at the beginning and never change it.
You should instead use the result from the last run iteratively:
import random
play = 'y'
result = 1
while play.lower() == 'y':
chance = random.randint(0,3)
if chance == 0:
print("Unlucky.... better luck next time")
break
else:
result *= 2
print(result)
play = input("Play again?[y/n]: ")
Related
I am new to Python and writing a program for a number guessing game. Here's the code:
import random
import math
def guessing_game_func():
name = input("Enter your name: ")
print("Welcome ", name)
lower_bound = 0
upper_bound = 50
#generating random number between 0 and 50
random_number = random.randint(lower_bound, upper_bound)
min_guessing_num = int(math.log(upper_bound - lower_bound + 1, 2))
print("INSTRUCTION: Guess a number between 0 and 50"
"\nHOT means you are close to the correct number and COLD means you are far from it")
print("You have only ", round(min_guessing_num), "tries")
#initializing number of guesses
count = 0
while count < min_guessing_num:
count += 1
guess = int(input("Guess a number: "))
if random_number == guess:
print("Congratulations. You guessed correctly after", count, "tries")
break
elif random_number > guess:
print("Hot")
elif random_number < guess:
print("Cold")
if count >= min_guessing_num:
print("Fail! The number is", random_number)
decision = input("Do you wish to play again? YES or NO").lower()
while decision == "yes":
guessing_game_func()
#if decision == "yes":
#guessing_game_func()
if decision == "no":
print("Close IDE")
guessing_game_func()
When I run this code, in the case where the user selects No, the game starts again but I do not want it to.
I just want it to print Close IDE and that should be it. However, the game starts again and I know this is because I am calling the function after it, but if I do not do that, then nothing will happen. What I mean by this is that, the code will run and all I'll see is Process finished with exit code 0
How do I fix this please?
The problem you have is with the loop that calls your function recursively:
decision = input("Do you wish to play again? YES or NO").lower()
while decision == "yes":
guessing_game_func()
if decision == "no":
print("Close IDE")
You have the recursive call which effectively implements a loop, and a while loop around that. When the inner call returns, remember that decision does not change within the outer function's while loop. That means that another call will be made and the loop will continue forever.
The simple solution is to decide whether you want to iterate via loop or recursion. I would recommend the former, but since you've already chosen the latter, just replace the while loop with a simple if:
decision = ""
while decision not in {"yes", "no"}:
decision = input("Do you wish to play again? YES or NO").lower()
if decision == "yes":
guessing_game_func()
else:
print("Close IDE")
Mad Physicist's answer covers the why does this happen and suggests a simple fix. However, I'd discourage you from using recursion to implement a replayed game. Instead, move the logic that decides whether to replay a game outside the function that implements the game logic.
def guessing_game_func():
...
while count < min_guessing_num:
...
# The function ends immediately after this while loop
# Now we're OUTSIDE the function
# Initialize decision to "yes", so the while loop is entered by default
decision = "yes"
while decision == "yes":
guessing_game_func()
decision = input("Do you wish to play again? YES or NO").lower()
if decision == "no":
print("Close IDE")
This way, you aren't limited to the recursion limit and can replay as many times as you like, since the next call of guessing_game_func only happens after the first call has ended.
I'm not sure why you want to print Close IDE only when "no" is entered -- what if decision is something other than "yes" and "no"? If you want to force decision to be one of those two options, you can pop it in another while loop, as shown in Asking the user for input until they give a valid response:
while decision == "yes":
guessing_game_func()
while True:
decision = input("Do you wish to play again? YES or NO").lower()
if decision in ("yes", "no"):
break # Acceptable input, so break out of the infinite loop
# Close IDE can be unguarded by an `if`, because the only way to get here is to enter "no" when asked for decision
print("Close IDE")
import random
import math
def guessing_game_func():
name = input("Enter your name: ")
print("Welcome ", name)
lower_bound = 0
upper_bound = 50
#generating random number between 0 and 50
random_number = random.randint(lower_bound, upper_bound)
min_guessing_num = int(math.log(upper_bound - lower_bound + 1, 2))
print("INSTRUCTION: Guess a number between 0 and 50"
"\nHOT means you are close to the correct number and COLD means you are far from it")
print("You have only ", round(min_guessing_num), "tries")
#initializing number of guesses
count = 0
while count < min_guessing_num:
count += 1
guess = int(input("Guess a number: "))
if random_number == guess:
print("Congratulations. You guessed correctly after", count, "tries")
break
elif random_number > guess:
print("Hot")
elif random_number < guess:
print("Cold")
if count >= min_guessing_num:
print("Fail! The number is", random_number)
decision = input("Do you wish to play again? YES or NO").lower()
while decision == "yes":
guessing_game_func()
break
#if decision == "yes":
#guessing_game_func()
if decision == "no":
print("Close IDE")
guessing_game_func()
Try this . I have added break after you call your function.now it works.
How do I make the code reapte such that users can guess the answer to the random number only three times, how do I make it stop at a point? Thanks.
This is a random number guessing game, I'm a total beginner to python and can't find anything that helps me on the web (or it may be that I'm just dumb)
import random
print('what difficulty do you want? Type Easy or Hard accordingly')
difficulty = input('')
if difficulty == 'Hard':
print('your going to have a tough time')
hardrandomnum = random.randint(1,100)
def main():
print('try to guess the number')
playerguess = float (input(""))
if playerguess > hardrandomnum:
print ("guess a lower number")
if playerguess < hardrandomnum:
print("guess a higher number")
if playerguess == hardrandomnum:
print("correct")
restart = 4
if restart >4:
main()
if restart == 4:
exit()
main()
Loops and breaks.
For example if you want to run the code three times wrap it in a for loop:
for i in range(3):
[here goes your code]
or you could make a while loop and break:
while(True):
[here goes your code]
if condition is met:
break
you could use a for loop:
for i in range(3):
#your code
the number in range() indicates how many times you visit the code inside
there are also while loops but for your usecase a for loop should do the trick
Use a looping structure as below answer mentions.
Example with while loop
def repeat_user_input(num_tries=3):
tries = 0
result = []
while tries < num_tries:
tries += 1
result.append(float(input()))
return result
print(repeat_user_input())
Example with a list comprehension and range
def repeat_user_input(num_tries=3):
return [float(input()) for _ in range(num_tries)]
I believe you are looking for something like the below?
import random
import sys
guess_counter = 0
random_number = 0
easy_hard = input('Chose your difficulty lever by typing "easy" or "hard" ')
if easy_hard.lower() == 'easy':
print('Your in luck! You are about to have fun')
random_number = random.randint(1,10)
elif easy_hard.lower() == 'hard':
print('Woow this game is not going to be easy')
random_number = random.randint(1,100)
else:
print('You need to type either easy or hard and nothing else')
sys.exit()
while guess_counter < 4:
user_number = int(input('Guess: '))
if user_number < random_number:
print('Try higher number')
guess_counter += 1
elif user_number > random_number:
print('Trye lower number')
guess_counter += 1
else:
print('Congrats! You Won')
break
else:
print('Ooops! Looks like you luck run out.')
I’m just starting to learn functions and I am practicing on implementing some into my code. Just a simple example... how can I code this to loop properly and break out when the user wants?
def profit(i,c):
gain = c - i
print('Your profit is:' + '' + str(gain))
def beginning():
x = float(input("What was your initial investment?"))
y = float(input("What is your investment worth now?"))
profit(x,y)
beginning()
ans = 'y'
while ans == 'y' or ans == 'Y':
ans = str(input('Would you like to calculate another investment? (Y/N)'))
beginning()
if ans != 'y' or ans != 'Y':
break
There are two ways to break out of a while loop. The first way is obviously the break statement, kind of like you have done. For it to work correctly, you need to change the condition:
if ans != 'y' or ans != 'Y':
break
This will always be true, since ans cannot be "y" and "Y" at the same time. You should change it into:
if ans not in ["y", "Y"]:
Or
if ans.upper() != "Y":
In your case however, you don't need it at all. Since in both the if statement and the while condition you are checking ans, you can get rid of the if and just rely on this.
while ans.upper() == "Y":
This will end the loop automatically when ans becomes anything other than "Y" or "y".
The only reason you would use a break here is if you wanted to exit the loop immediately, and not complete the current iteration. For example:
while ans.upper() == "Y":
ans = input("Enter selection: ")
if ans == "I want to stop right now!":
break
print("Do other things, even if ans is not Y")
In this example, "Do other things" will always be printed regardless of ans, unless ans is "I want to stop", in which case it won't get printed.
One thing you can do is ans = ans.capitalize() after you get the user input. Then remove the ans != 'y' since that's causing your loop to break.
I know how to use a while loop, but I'm not sure about the part where I need to make a command to double the previous score.
The task is to double or quit.
And this is my code at the moment:
import random
play = 'y'
Original = 1
while play.lower() == 'y':
chance = random.randint(0,3)
if chance == 0:
print("Unlucky.... better luck next time")
else:
newnumber = Original*2
print (newnumber)
play = input("Play again?[y/n]: ")
No need for defining a new var newnumber, just rewrite the Original
by doing original = original*2
import random
play = 'y'
original = 1
while play.lower() == 'y':
chance = random.randint(0,3)
if chance == 0:
print("Unlucky.... better luck next time")
else:
original = original*2
print (original)
play = input("Play again?[y/n]: ")
No need to bring in variable newnumber. Also, dont use mix of upper and lower case variables.
import random
play = 'y'
original = 1
while play.lower() == 'y':
chance = random.randint(0,3)
if chance == 0:
print("Unlucky.... better luck next time")
else:
original= original*2 # or shorthand: original *= 2
print (original)
play = input("Play again?[y/n]: ")
You were assigning the new variable value (original * 2) to a locally scoped variable to the loop, so every iteration, original is still 1.
import random
play = 'y'
original = 1
while play.lower() == 'y':
if (random.randint(0, 3) == 0):
print('Unlucky... better luck next time')
else:
original *= 2; print(original)
play = input('Play again? [y/n]: ')
If you are trying to get the Original variable to be doubled, there's no need for bringing newNumber into the mix. Just use
Original = Original * 2 (or Original *= 2, for short).
Hello fellow programmers,
I'm quite a Python and overall programming newbie and I don't know how to process user input the bestimmt. A friend of mine suggested while loops and they worked quite well but now I have a serious problem.
The program is about asking the user which one of 3 ways to calculate Pi he wants. After his/her selection, e.g. the way to calculate Pi using a polygon which doubles the number of corners after each iteration, it asks how many digit the user wants to see or how many loops should be calculated etc. I also have added some code that checks what the user has written, e.g. if the user is asked to either type y or n but types b the program reminds him of that and asks again.
This style has led to whiles, inside whiles, inside whiles and now looks more like HTML code than Python and is a little complicated to understand...
Take a look:
#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
prgrm_ctrl_main_while_start = 0
while prgrm_ctrl_main_while_start == 0:
print "Please select the type of algorithm you want to calculate Pi."
usr_ctrl_slct_algrthm = raw_input("'p' to use polygons, 'm' to use the Monte-Carlo algorithm or 'c' for the Chudnovsky algorithm: ")
print " "
if usr_ctrl_slct_algrthm == 'p':
#import libraries
import time
from mpmath import *
#starting values
n_corners = mpf(8)
counter = 0
while_loop_check_itertions = 0
while while_loop_check_itertions == 0:
print "Pi will be calculated more precisely the more iterations you select but it'll also take longer!"
loops = int(input("Please select number of iterations (1 - 10.000.000): "))
print " "
if 1 <= loops <= 10000000:
loops = loops - 1
decimals = int(input("Please select the amount of decimals you want to see: "))
print " "
decimals = decimals + 1
starttime = time.clock()
mp.dps = decimals
while counter <= loops:
counter = counter + 1
n_corners = mpf(n_corners) * mpf(2)
circle = mpf(360)
alpha = mpf(circle) / mpf(n_corners)
beta = mpf(alpha) / mpf(2)
radiansBeta = mpf(mp.radians(beta))
opp_leg = mpf(mp.sin(radiansBeta))
edge_lngth = mpf(opp_leg) * mpf(2)
circmfrnce = mpf(n_corners) * mpf(edge_lngth)
pi = mpf(circmfrnce) / mpf(2)
print "Pi: ", mpf(pi)
print "Time to calculate: ", time.clock() - starttime, "seconds"
print " "
prgrm_ctrl_p_algrthm_while_start = 0
while prgrm_ctrl_p_algrthm_while_start == 0:
usr_ctrl_slct_p_algrthm = raw_input("Would you like to try this algorithm again? (y/n): ")
print " "
if usr_ctrl_slct_p_algrthm == 'y':
usr_ctrl_slct_p_algrthm_slction = 0
break
elif usr_ctrl_slct_p_algrthm == 'n':
usr_ctrl_slct_p_algrthm_slction = 1
break
else:
print "You must either type 'y' or 'n'!"
continue
if usr_ctrl_slct_p_algrthm_slction == 0:
continue
else:
usr_ctrl_slct_diffrt_algrthm_while_start = 0
while usr_ctrl_slct_diffrt_algrthm_while_start == 0:
usr_ctrl_slct_diffrt_algrthm = raw_input("Do you want to use another algorithm? (y/n): ")
print " "
if usr_ctrl_slct_diffrt_algrthm == 'y':
usr_ctrl_slct_diffrt_algrthm_slction = 0
break
elif usr_ctrl_slct_diffrt_algrthm == 'n':
print "See you next time!"
print " "
usr_ctrl_slct_diffrt_algrthm_slction = 1
break
else:
print "You must either type 'y' or 'n'!"
continue
if usr_ctrl_slct_diffrt_algrthm_slction == 0: #The program gets to this line and in case of the user selecting 'y' should continue in the first while-loop
continue
else: #if the user says 'n' the program should interrupt and stop, in the best case it should close the command line (in my case IDLE)
break #instead of doing all this the code gets executed again in the 2nd while loop not the 1st
"""NOTE: I also know the lines above continue or quit the 2nd while-loop"""
elif loops < 1:
print "Please select at least one iteration!"
while_loop_check_algrthm_slct = 0
while while_loop_check_algrthm_slct == 0:
usr_ctrl_slct_algrthm_p_try_agn = raw_input("Do you want to try it again? (y/n): ")
print " "
if usr_ctrl_slct_algrthm_p_try_agn == 'y':
usr_ctrl_slct_algrthm_p_try_agn_slction = 0
break
elif usr_ctrl_slct_algrthm_p_try_agn == 'n':
usr_ctrl_slct_algrthm_p_try_agn_slction = 1
break
else:
print "You must either type 'y' or 'n'!"
continue
if usr_ctrl_slct_algrthm_p_try_agn_slction == 1:
break
else:
continue
else:
print "The maximum amount of iterations is 10 million!"
while_loop_check_algrthm_slct = 0
while while_loop_check_algrthm_slct == 0:
usr_ctrl_slct_algrthm_p_try_agn = raw_input("Do you want to try it again? (y/n): ")
print " "
if usr_ctrl_slct_algrthm_p_try_agn == 'y':
usr_ctrl_slct_algrthm_p_try_agn_slction = 0
break
elif usr_ctrl_slct_algrthm_p_try_agn == 'n':
usr_ctrl_slct_algrthm_p_try_agn_slction = 1
break
else:
print "You must either type 'y' or 'n'!"
continue
if usr_ctrl_slct_algrthm_p_try_agn_slction == 1:
break
else:
continue
I have commented the lines that are effected...
I can't solve the problem with the main-while-loop therefore I'm asking you how I can solve this. Is there a better way of handling user input and checking if it's correct? I'm stuck at a point where I wish I had goto because I can't imagine any other solution.
Hopefully you can help me and thank you for reading this long code! I appreciate that! :)
holofox
My first thought is simplify things, please see this "pseudo-code":
while True: #select algorithm type
#code: ask for algorithm
if answer not in "pmc":
#some message
continue #non-valid algorithm selected, ask again
#...
if answer == 'p':
while True: #select iteration range
#code: ask for iteration
if answer_not_in_range:
#some message
continue #non-valid iteration value, ask again
#...
#perform calculation upon valid selections
#...
#calculation ends
#code: ask for try again with other iteration (algorithm stays same)
if answer != "yes":
break #break out of "iteration" loop
#else loop continues asking for new iteration
#code: ask for try again with other algorithm
if answer != "yes":
break #"algorithm" loop ends, program ends
As Robert Rossney says in an answer to another question:
My first instinct would be to refactor the nested loop into a function and use return to break out.