python breaking if statement inside for loop - python

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"
#...

Related

Why cant i sum up all of my values (user values) problem with while?

I'm new to the coding world. I have a problem with adding up all of the users' input values, as I don't know how many there will be. Any suggestions?
This is how far I've gotten. Don't mind the foreign language.
import math
while(True):
n=input("PERSONS WEIGHT?")
people=0
answer= input( "Do we continue adding people ? y/n")
if answer == "y" :
continue
elif answer == "n" :
break
else:
print("You typed something wrong , add another value ")
people +=1
limit=300
if a > limit :
print("Cant use the lift")
else:
print("Can use the lift")
You don't need to import math library for simple addition. Since you did not mention that what error are you getting, so I guess that you need a solution for your problem. Your code is too lengthy. I have write a code for you. which has just 6 lines. It will solve your problem.
Here is the code.
sum = 0;
while(True):
n = int(input("Enter Number.? Press -1 for Exit: "))
if n == -1:
break
sum = sum+n
print(sum)
Explanation of the Code:
First, I have declared the variable sum. I have write while loop, inside the while loop, I have prompt the user for entering number. If user will enter -1, this will stop the program. This program will keep on taking user input until unless user type "-1". In the end. It will print total sum.
Output of the Code:
Here's something for you to learn from that I think does all that you want:
people = 0
a = 0
while True:
while True:
try:
n = int(input("PERSONS WEIGHT?"))
break
except ValueError as ex:
print("You didn't type a number. Try again")
people += 1
a += int(n)
while True:
answer = input("Do we continue adding people ? y/n")
if answer in ["y", "n"]:
break
print("You typed something wrong , add another value ")
if answer == 'n':
break
limit = 300
if a > limit:
print("Total weight is %d which exceeds %d so the lift is overloaded" % (a, limit))
else:
print("Total weight is %d which does not exceed %d so the lift can be operated" % (a, limit))
The main idea that was added is that you have to have separate loops for each input, and then an outer loop for being able to enter multiple weights.
It was also important to move people = 0 out of the loop so that it didn't keep getting reset back to 0, and to initialize a in the same way.

Python: Printing something changes the outcome?

So I'm new to this programming thing... But this has me stumped. To the point that I'm wondering if the website I'm running Python on is wrong. (repl.it is the website).
So I did one of those guess the number games as a small fun challenge. This is the code that I came up with:
from random import randint
print ("Welcome to guess the number!")
answer = str(randint(0,100))
print (answer)
print ()
def something():
answerTwo = str(randint(0,100))
print (answerTwo)
idea(answerTwo)
def idea(x):
number = str(input("Guess a number between 0 and 100:"))
if number != x:
if (number > x):
print()
print(number + " is too high!")
print()
idea(x)
elif (number < x):
print()
print(number + " is too low!")
print()
idea(x)
else:
print()
print ("That is correct!")
again = input("Would you like to play again?:")
if again == "yes":
something()
else:
print ("Thanks for playing!")
idea(answer)
On the 4th and 8th line I print out the random number chosen so that I can quickly test to make sure everything works. Then I removed the print functions in the final product and tested again. Except when I removed the print functions it stopped working after some amount of time. For example, it'll say 39 is too low but 40 is too high, which is impossible since they're is no number in between them. If you put the print functions back in it works again, but remove them and it'll start acting up eventually.
I apologize if it's something really obvious but I just don't understand how this is possible.
Here is the github thingy for it
https://gist.github.com/anonymous/4a370664ae8ddb29aec5915eb20e686f
Thanks for your time!
There is no integer i such that 39 < i < 40.
There is however a numeric string s such that "39" < s < "40". Observe:
>>> "39" < "4" < "40"
True
In short: It has nothing to do with your print calls, instead, just work on actual numbers and cast your input to a number using int(). print() can handle numbers just fine.

Python gives a "Syntax Error" on "else:"

My Error
Python throws a syntax error pointed at the last "e" of "else:", preceded by an if statement and inside a while loop.
My Objective
Test if certain parameters are true, if true then go to the beginning of the loop and if not true then perform certain statements and increment a value.
My Source Code
from random import randint
def returnDigRoot(num):
digs = []
while len(str(num)) != 1:
num = str(num)
for each in num:
digs.append(each)
num = int(num)
digs = [int(i) for i in digs]
num = sum(digs)
return(num)
def rnum():
return(randint(1,99999))
ran_nums = []
sols = []
it = 1
The problem area is here
while it <= 3:
print("Generating numbers")
current = randint(1,99999)
print("randomly intializing the 'current' int value")
print("testing if the digital root is greater than 6")
if returnDigRoot(current) > 6:
print("going back to start of loop")
continue
print("testing if it isnt")
else:
ran_nums.append(current)
print("append 'current' to ran_nums")
sols.append(returnDigRoot(current))
print("appending its digital root to sols")
it += 1
print("incrementing the iterator variable")
My Research
I looked at many questions on StackOverflow and other sites and could not find a solution to my problem; most problems people had with else statements were related to tabbing errors, preceding errors (which I checked for), no preceding if statement, or multiple else statements.
Thanks in advance for any help.
print("testing if it isnt") needs to be indented. As it stands, your code doesn’t really relate the if with the else because of the indentation. It’s like writing something like this in C:
if(<condition>)
{
<action>
}
prinf(...)
else
{
<action>
}
Just align the print line with the rest of the code under the if statement.
The line:
print("testing if it isnt")
isn't indented correctly. You can't have anything in between an if block and the else block.
Your statement:
print("testing if it isnt")
is indented to the wrong level; that makes the else: that follows an independent statement, which is syntactically wrong. Probably you meant that print statement to follow the else and be indented one level.
This is most likely a indentation/space/tabbing issue since I copy pasted the code and I don't get any errors. Though I am on Python 2.7.10. (Repasting it here to ensure you can copy paste the same and try):
from random import randint
def returnDigRoot(num):
digs = []
while len(str(num)) != 1:
num = str(num)
for each in num:
digs.append(each)
num = int(num)
digs = [int(i) for i in digs]
num = sum(digs)
return(num)
def rnum():
return(randint(1,99999))
ran_nums = []
sols = []
it = 1
while it <= 3:
current = randint(1,99999)
if returnDigRoot(current) > 6:
continue
else: # this is where the error is pointed
ran_nums.append(current)
sols.append(returnDigRoot(current))
it += 1
On an unrelated note, that while loop will take a long time to exit since the exit criteria is very small (two current <=36 only will cause exit).

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

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)

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