Why is the while loop not working in the if loop? - python

def n():
name = input('What is the missing animal?')
if name == 'dog':
print('Well done')
else:
print('Sorry this is not right')
rep= 0
while rep < 5:
n()
rep = rep + 1
if rep == 5:
print ('You have guessed incorrectly 5 times.)
When i run this and get the answer wrong, the program keeps repeating instead of repeating a maximum of 5 times.
Any ideas?

What an awkward recursion. :)
The problem is that the rep variable is locally scoped, that is, not passed to the recursive call.
You should put the while outside and use a success variable with the while in order to test whether you need to loop again.
No recursion needed.
EDIT:
Like this:
def n():
rep= 0
success = 0
while rep < 5 or success == 1:
name = input('What is the missing animal?')
if name == 'dog':
success = 1
else:
print('Sorry this is not right')
rep = rep + 1
if rep == 5:
print ('You have guessed incorrectly 5 times.')
elif success == 1:
print('Well done')
Sorry for indentation.

def n():
for rep in range(5):
name = input('What is the missing animal?')
if name == 'dog':
print('Well done')
break
else:
print('Sorry this is not right')
else:
print ('You have guessed incorrectly 5 times.')
Since you know how many times you want to go through the loop, a for is (perhaps) more appropriate. The else clause for the for loop handles the case where you finish without getting the right answer.

You keep calling the n() method over and over within the else statement. I believe this code will work for what you desire:
def n():
rep= 0
while rep < 5:
name = input('What is the missing animal? ')
if name == 'dog':
print('Well done')
break
else:
print('Sorry this is not right')
rep = rep + 1
if rep >= 5:
print ('You have guessed incorrectly 5 times.')
This runs the loop 5 times, unless you get the answer correct. If the answer is correct, the loop will break, meaning it stops running. At the end, it checks if rep is greater than (which it never will be) or equal to (which occurs on the 5th loop) and prints the ending message if it has looped 5 times.

Here is the correct way to recurse. Although this is tail recursive, so I would unwrap it into a loop like #Prune myself.
def n(rep=0):
if n >= 5:
print ('You have guessed incorrectly 5 times.')
else:
name = input('What is the missing animal?')
if name == 'dog':
print('Well done')
else:
n(rep+1)

Related

How do i repeat the code multiple times? in python

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 want to setup a would you like to retry

I have created a guess the number game, at the end of it I want it to ask the user if they would like to retry. I got it to take invalid responses and if Yes then it will carry on, but when I say no it still carries on.
import random
from time import sleep
#Introduction & Instructions
print ("Welcome to guess the number")
print ("A random number from 0 - 1000 will be generated")
print ("And you have to guess it ")
print ("To help find it you can type in a number")
print ("And it will say higher or lower")
guesses = 0
number = random.randint(0, 1)#Deciding the number
while True:
guess = int (input("Your guess: "))#Taking the users guess
#Finding if it is higher, lower or correct
if guess < number:
print ("higher")
guesses += 1
elif guess > (number):
print ("lower")
guesses += 1
elif guess == (number):
print ("Correct")
print (" ")
print ("It took you {0} tries".format(guesses))
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer in ('y', 'n'):
break
print ('Invalid input.')
if answer == 'y':
continue
if answer == 'n':
exit()
First of all, when you check :
if answer in ('y','n'):
This means that you are checking if answer exists in the tuple ('y','n').
The desired input is in this tuple, so you may not want to print Invalid input. inside this statement.
Also, the break statement in python stops the execution of current loop and takes the control out of it. When you breaked the loop inside this statement, the control never went to the printing statement or other if statements.
Then you are checking if answer is 'y' or 'n'. If it would have been either of these, it would have matched the first statement as explained above.
The code below will work :
#Asking if they want another go
while True:
answer = input('Run again? (y/n): ')
if answer == 'y':
break
elif answer == 'n':
exit()
else:
print ('Invalid input.')
continue
Also, you might want to keep the number = random.randint(0, 1)#Deciding the number statement inside the while loop to generate a new random number everytime the user plays the game.
This is because of the second while loop in your code. Currently when you put y or n it will break and run again (you don't see the invalid message due to the break occurring before reaching that code), it should be correct if you change it to the following:
while True:
answer = input('Run again? (y/n): ')
# if not answer in ('y', 'n'):
if answer not in ('y', 'n'): # edit from Elis Byberi
print('Invalid input.')
continue
elif answer == 'y':
break
elif answer == 'n':
exit()
Disclaimer: I have not tested this but it should be correct. Let me know if you run into a problem with it.

How to insert loop counter into my definition

number = 7
def magicnumber (guess):
if number<guess:
print ("too high")
elif number>guess:
print ("too low")
elif number == guess:
print ("well done")
return magicnumber
Above is my code for my magic number guessing program. My question is how to insert a loop counter. I did some research on loop counter integration, and many people have said to use the enumerate function, problem is I have no idea how to use such a function and if it is appropriate in my case. Normally, I jus declare a counter variable as 0 then use the += function to add 1 to that variable but in my case this does not work as I cant declare the variable before the def magicnumber (guess) line and if I were to declare it, the counter would revert back to 0 after the return. I am therefore enquiring how to add a loop count as I only want the user to have 5 guesses.
Thanks
counter = 5
while counter > 0:
guess = int(raw_input())
if magicnumber(guess) == number:
break
counter -= 1
Another approach:
for i in range(5):
guess = int(raw_input())
if magicnumber(guess) == number:
break
Try using the answer from here: That's what static variables are for (among other things).
That would result in the following code
number = 7
def magicnumber (guess):
magicnumber.counter += 1
if(magicnumber.counter <= 5):
if number<guess:
print ("too high")
elif number>guess:
print ("too low")
elif number == guess:
print ("well done")
magicnumber.counter = 0#If you want to reset the counter
return
else:
print "Out of trials!"
return
magicnumber.counter = 0

python breaking if statement inside for loop

I want the if-statement to break if the condition is met, because currently if it isn't broken early then I get some mishaps in my code.
The problem is, I am not sure where to put the break. When I put it where it is shown here I get "Unexpected indent", but when I put it back a level I get an error with the else-statement saying "Invalid Syntax".
EDIT: THE IF IS INDENTED. It just didn't show up in the sites code blocks. I will try and fix it on the site.
#duck, what do you think I am trying to do? I am in my first weeks of a python course. I came here to help myself, not get my code trolled by you. If you can help me then I would appreciate the help, otherwise I don't need you telling to "learn how to code" when that's exactly what I am trying to do.
So I am not sure what to do. Any help would be appreciated.
def pTurn(CampLoc, AICampLoc, score, yourHits, cHits):
if yourHits < 5:
hGuess = int(raw_input("Enter a co-ordinate to air-strike: "))
print "Air-striking co-ordinate: %d" % hGuess
for cSpot in AICampLoc:
if hGuess == cSpot:
yConfirMsg = "Kill confirmed!!"
yourHits += 1
score += 100
AICampLoc.remove(hGuess)
break
else:
yConfirMsg= "No casualties"
You are missing an indent, as the other answer states, but also, you have a bunch of code that isn't needed. Your code can be simplified to this:
def pTurn(CampLoc, AICampLoc, score, yourHits, cHits):
if yourHits < 5:
hGuess = int(raw_input("Enter a co-ordinate to air-strike: "))
print "Air-striking co-ordinate: %d" % hGuess
yConfirMsg= "No casualties"
for cSpot in AICampLoc:
if hGuess == cSpot:
yConfirMsg = "Kill confirmed!!"
yourHits += 1
score += 100
AICampLoc.remove(hGuess)
break
Try this:
def pTurn(CampLoc, AICampLoc, score, yourHits, cHits):
if yourHits < 5:
#^This line ident is probably the offending line. ;)
hGuess = int(raw_input("Enter a co-ordinate to air-strike: "))
print "Air-striking co-ordinate: %d" % hGuess
for cSpot in AICampLoc:
if hGuess == cSpot:
yConfirMsg = "Kill confirmed!!"
yourHits += 1
score += 100
AICampLoc.remove(hGuess)
break
else:
yConfirMsg= "No casualties"
score = score #You may want to fix this, since the logic doesn't make sense
yourHits = yourHits #Fix this line as well. This is variable value assignment to the same variable.
If this doesn't work, another thing to consider is that you may be inadvertently mixing tabs and whitespace when you indent the leading spaces for your code. If so, convert all the tabs to spaces.
And, regarding the notes cited. Perhaps you meant to return those values? If so, you need to fix those logic errors.
UPDATE:
If you only have to break once and only once, then you should replace break with return.
If not, then you should capture the location, continue loop execution, and do whatever you have to do with that information.
#...
values = {}
all_values = []
for cSpot in AICampLoc:
if hGuess == cSpot:
yConfirMsg = "Kill confirmed!!"
yourHits += 1
score += 100
AICampLoc.remove(hGuess)
values['message'] = yConfirMsg
values['hits'] = yourHits
values['score'] = score
values['camploc'] = AICampLoc
all_values.append(values)
else:
yConfirMsg= "No casualties"
#...

trying to loop to the beginning of a function(sort of) in python

I am trying to go back to the top of a function (not restart it, but go to the top) but can not figure out how to do this. Instead of giving you the long code I'm just going to make up an example of what I want:
used = [0,0,0]
def fun():
score = input("please enter a place to put it: ")
if score == "this one":
score [0] = total
if score == "here"
if used[1] == 0:
score[1] = total
used[1] = 1
elif used[1] == 1:
print("Already used")
#### Go back to score so it can let you choice somewhere else.
list = [this one, here]
I need to be able to go back so essentially it forgets you tried to use "here" again without wiping the memory. All though I know they are awful, I basically need a go to but they don't exist in python. Any ideas?
*Edit: Ah sorry, I forgot to mention that when it's already in use, I need to be able to pick somewhere else for it to go (I just didn't want to bog down the code). I added the score == "this one"- so if I tried to put it in "here", "here" was already taken, it would give me the option of redoing score = input("") and then I could take that value and plug it into "this one" instead of "here". Your loop statement will get back to the top, but doesn't let me take the value I just found and put it somewhere else. I hope this is making sense:p
What you are looking for is a while loop. You want to set up your loop to keep going until a place is found. Something like this:
def fun():
found_place = False
while not found_place:
score = input("please enter a place to put it: ")
if score == "here"
if used[1] == 0:
score[1] = total
used[1] = 1
found_place = True
elif used[1] == 1:
print("Already used")
That way, once you've found a place, you set found_place to True which stops the loop. If you haven't found a place, found_place remains False and you go through the loop again.
As Ashwini correctly points out, you should do a while loop
def fun():
end_condition = False
while not end_condition:
score = input("please enter a place to put it: ")
if score == "here":
if used[1] == 0:
score[1] = total
used[1] = 1
elif used[1] == 1:
print("Already used")

Categories