Trying to replace a break but keep the same result in python - python

I am new to coding and was told that using breaks is a bad form of programming. I was wondering if anyone knew a good way to change the break without changing how the program functions? I have attached the code I am working with.Code in question

Running your code I don't see any problems. What I would change is that you can make a an argument for the function and return True or False, like this:
def isprime(a):
c=a-1
for i in range(2, c):
b=a%i
if b == 0:
return False
else:
return True
isprime(4)
isprime(7)
In this example I replaced break with return, this will break the loop but also return whether the number is prime or not.
To clarify, there is nothing wrong with using break and I think it is a very usefull possibility when looping.

Related

I am trying to write a function xyz(a) that loops through the no.s 0 through a and returns "Jackpot" if it finds the number 777 .or else "Try again

def xyz(a):
i=0
while i>=a:
if i==777:
return"Jackpot"
else:
return"Try again"
i+=1
The above when i am running gives me no output. unable to figure out what's missing
There are many errors!
If you return before increment, you'll never have an increment.
If you return after increment , no point of while loop.
Solution
Simple if else
def xyz(a):
if a==777:
return "Jackpot"
else:
# i+=1
# return "Try again"
return ("Try Again")
Since you did not provide any information about what exactly you are trying to do all I can do is give you some advise based on what I can infer from your code. Notice that you are returning a value meaning you stop the execution of the while loop at the first iteration always (if you are 100% certain about the implementation of the function and your desired output is 'try again' then you have to 'catch' the returned value of the function and print that). Also check the while condition. I is initialised at 0 so (for me at least) it would make sense to check if i is less than a (but again this comes from my intuition about the code).

How to get out of infinite loop of Sudoku code if the Sudoku can't be solved?

I've created a code that solves sudoku using the elimination method, and it works on all properly formatted sudoku puzzles. However, I have been given a test case where the puzzle is unsolvable, and thus causes my code to run infinitely. I have created an exception SudokuUnsolvable that I need to raise in this case, but I don't know how to implement it into my code.
class SudokuUnsolvable(Exception):
pass
def sudokuSolver (s, strategies) :
counter=0
while solved(s)==False:
for strategy in strategies:
applyStrategy(strategy, s)
if applyStrategy(strategy, s)==False:
break
counter+=1
return s
There are a lot of smaller codes for functions I've used (like the applyStrategy code)
def applyStrategy(strategy, s) :
r=0
n=0
new=0
counter=0
for row in range(len(s)):
for num in range(len(s[row])):
if s[row][num]!=0:
pass
else:
new=elimination(num, row, s)
if s[row][num]!=new:
s[row][num]=new
counter+=1
if counter==0:
return False
else:
return True
It seems that the if statement in sudokuSolver automatically exits the loop if the sudoku stops changing, so an exception is never able to be raised. Is there anyway for me to raise the exception within this code if the algorithm fails to solve the puzzle?
I would validate sudoku beforehand, but you could just add if counter>MAX_STRATEGY_COUNT: break to your code.
I'm assuming that s is your sudoku board. You can check if it's changed at all after all the strategies have been applied. If it hasn't, you know you can't solve it anymore.
You can do it by keeping the original around and comparing it at the end of the loop. Or you can use some flag which is reset at the beginning and then set if you make any change.

Python simplify if and loop

Our code reviewer is telling me that flag in the code below is bad and I need to refactor code in a "Python-like" style. I really can't understand how I can avoid this flag usage, here is a sample of code:
flag = false
for (i in range(2,4)):
zoom()
if (check_condition()):
flag = true
break
if (flag):
tap()
else:
raise Exception("failed")
I can see the only way to make a tap inside if. In this case I will have to add a return statement inside a loop, which is not the best idea from the code style point of view, isn't it?
So maybe someone can suggest a better way to organize this code?
You can use an else: statement with the for statement. It's only executed if the loop finishes normally, instead of exiting with break
for i in range(2, 4):
zoom()
if check_condition():
break
else:
raise Exception("failed")
tap()
I don't think you need the falg here either, if you just call the tab() method instead of changing the flag value to true. It will work the same.
for (i in range(2,4)):
zoom()
if (check_condition()):
tab()
break
else:
raise Exception("failed")

How to return boolean value to function and evaluate with an if/elif check?

# v1.0#
#######
import time
#Definitions#
def StartOrNah():
print#Newline
time.sleep(0.5)
print("To begin, type 'start' or to exit type 'exit'...")
time.sleep(0.6)
sorn = str(raw_input("--> ")).lower()
if sorn == str("start"):
return True
elif sorn == str("exit"):
return False
else:
print#Newline
print("That is not valid, please try again.")
StartOrNah()
def program():
print#Newline
print("The main program function has been invoked.")
#Calls#
StartOrNah()
if StartOrNah:
program()
elif StartOrNah:
print#Newline
print("The program will now exit...")
time.sleep(3)
My goal is to return a boolean value to the StartOrNah function, and use an if check to see if the result is True or False. I've tried a few methods of this, but I can never get False to be recognized in the evaluation. I feel like I'm doing functions terribly wrong.
I'd appreciate it if answers are kept semi-simple, as I'm a bit new to the language.
There's three problems and no answers seem to be covering them all properly, so here goes. In this snippet:
else:
print#Newline
print("That is not valid, please try again.")
StartOrNah()
By leaving out the keyword return, you ensure that StartOrNah() will be called but its result will be lost and the caller (the original StartOrNah) will simply return None since the last statement that was executed didn't have a return. None will then be treated like False in an if statement. You need to prepend return to that last line.
To demonstrate this, run this small program:
def foo():
3
print foo()
def bar():
return 3
print bar()
In this snippet:
#Calls#
StartOrNah()
if StartOrNah:
program()
when you say if StartOrNah you are asking if the object StartOrNah, which is a function, is equivalent to True, which is misguided (it always will be). Calling StartOrNah() returns a value that you are supposed to keep and do something with, just like you were supposed to return it above. It doesn't mean you are then supposed to ask what the result was by referring to the name of the function. Instead you need to do something like this:
result = StartOrNah()
if result:
program()
To help your understanding, I recommend also adding two lines so that it looks like this:
result = StartOrNah()
print("result:", result)
print("StartOrNah:", StartOrNah)
if result:
program()
You should see that result is either True or False while StartOrNah is a function.
Next, in this snippet:
if StartOrNah:
program()
elif StartOrNah:
print#Newline
if StartOrNah is False then neither block will be executed. Use else instead of elif because elif still requires that the condition given is true (hence the contained if) which obviously isn't the case since the original if just showed it was false. On the other hand, else is always executed when the matching if (and any elifs) were not executed.
Unless all of these problems are fixed I expect that the program will not work as you imagine.
Since you have some confusion about how functions work I strongly recommend staying away from recursion (i.e. calling StartOrNah() within StartOrNah()) for now since this will only make things more confusing and difficult. Play around with some simple toy programs to improve your understanding of the foundational concepts.
The problem is that you don't return a value from your recursion. Add one word to that clause:
else:
print#Newline
print("That is not valid, please try again.")
return StartOrNah()
I am quite an newbie too...
So if you say:
if StartorNah():
pass
You're trying to see if it is True. If you want to see if it is False instead, use:
if not StartorNah():
print#Newline
print("The program will now exit...")
time.sleep(3)
You could also use a else statement, which will be used if every other if and elif statements' conditions are not met:
else:
print#Newline
print("The program will now exit...")
time.sleep(3)
As mentioned in the comment, try using StartorNah() instead of StartorNah.

How would I put an if statement inside a function?

I am very very new to Python and before this I only used extremely simple "programming" languages with labels and gotos. I am trying to make this code work in Sikuli:
http://i.imgur.com/gbtdMZF.png
Basically I want it to loop the if statement until any of the images is found, and if one of them is found, it executes the right function and starts looping again until it detects a new command.
I have been looking for tutorials and documentation, but I'm really lost. I think my mind is too busy trying to go from a goto/label to an organized programming language.
If someone could give me an example, I would appreciate it a lot!
In Python indentation matters, your code should look like this:
def function():
if condition1:
reaction1()
elif condition2:
reaction2()
else:
deafult_reaction()
I recommend reading the chapter about indentation in Dive Into Python as well as PEP 0008.
x = input( "please enter the variable")
print(" the Variable entered is " + x)
myfloat = int(x)
def compare (num):
if num%2 == 0:
print(" entered variable is even")
else:
print("entered variable is odd")
compare(myfloat)

Categories

Resources