Python loop controler continue is not working properly - python

As I know, "continue" will jump back to the top of the loop. But in my case it's not jumping back, continue don't like me :(
for cases in files:
if ('python' in cases.split()):
execute_python_scripts(cases.split())
elif run_test_case(cases.split()):
continue
else:
logger("I am here")
break
In my case run_test_case() gives 1, 2, 3, 4 etc... But it always performs first(1) and jump to the else part. So I am getting the "I am here" message. It should not work like this. As I am using "continue", it should jump to the for loop.
Following is the run_test_case():
def run_test_case(job):
for x in job:
num_of_cases = num_of_cases - 1
test_type = x.split('/')
logger(log_file,"Currently "+ x +"hai!!")
if test_type[0] == 'volume':
backdoor = test_type[1].split("_")
if backdoor[0] == 'backdoor':
return get_all_nas_logs()
else:
if perform_volume_operations(x,num_of_cases) == False:
return False
else:
logger(log_file,"wrong ha!!")
Why is it always going to the else part, without jumping back to the for loop? Thanks in advance.

Here elif run_test_case(cases.split()): you are calling the run_test_case method, that will run your code to evaluate the result for the elif condition.
It only enters the block delimited by elif (in your case, continue), if the result of that method evaluates to True, otherwise it will jump to the else clause.
The problem is probably in your run_test_case code, that is never returning True, and so you'll never get the behavior that you're expecting.
It's hard to say without knowing exactly what you want to accomplish, but I'd say that you're missing a return True in the end of that code, meaning, if everything executes correctly right until the end, you want it to return True... but I'm only guessing here, you need to think about what that method is supposed to do.
In python an if or elif clause is evaluated for not only the True and False constants, but more generally for True-like and False-like values. None, for instance, is a false-like value, a non-empty string is a true-like value, etc.
Check this from the documentation on values that are considered true or false:
http://docs.python.org/library/stdtypes.html

Related

Problem with if statements within while loop

The code at line 7 works when 'Add' is typed. But the code at line 7 keeps repeating when 'View' prompt is entered. This is my password storing programe
import string
master_pass = input('Lost in Soul Sand be everything, but the KEY! \n')
while master_pass == 'Soul':
action = input('Add/View Soul?').lower()
if action == 'add':
U = input('Soulname: ')
P = input('Soul Sand: ')
with open('sandvalley.txt','a') as f:
f.write( U + '|' + P + '\n')
print('Souls saw the light')
if action == 'view':
with open('sandvalley.txt','r') as narrate:
narrate.readlines()
for row in narrate:
print(row)
if action != 'add' or 'view':
print('Soul has left the storm')
break
print ('End')
I don't know what you mean by
The code at line 7 works when 'Add' is typed. But the code at line 7 keeps repeating when 'View' prompt is entered.
since all options (add, view, and other strings) will not keep the program stay in the loop in my test and line 7 is a blank line.
But I do know if you want to use the variable action to control the program, then if action != 'add' or 'view: is certainly not the guy you looking for.
What if action != 'add' or 'view': acutally does is if (action != 'add') or ('view'):, which means if the variable action is NOT 'add' OR 'view', and the so-called Truth Value Testing is coming around. According to doc, any string whose length is not zero is considered True, hence the conditional expression will always be True and the ending process will always be done.
If you want to fix it, if action not in ['add', 'view'] will be good, but I will use
if action == 'add':
# do something
elif action == 'view':
# do something
else:
# end the program
instead, which is better IMO.
BTW, in Python 3.10+, match-case is introduced (link to doc), and this kind of cases is definitely the best time to use it.
match action:
case 'add':
# do something
case 'view':
# do something
case _:
# end the program
Give it a try.
The .readlines() function RETURNS a value so you want to save in a variabl, insted of say narrate.readlines(), say narrate = narrate.redlines().
That should work. Let me known if it work i try it already and i think it works fine:
Code
OutPut
Also you can add somthing like this:
ForCodeRepeat
this make your code repeat while your imput is != add and view.
The way you code putting action != 'add'or 'view' doesnt work because if you make the input "view" the condition action != 'add'or 'view' will be true because "view" != add. And if your input is "add" the condition will be true again because "add" != "view.
That why you want to use and instead of or becaose you want that your code stops whenyour input isn´t one of them.
Another solution could be use elif:
Elif
Because if the code won´t run if the option above is true.
Hope it helps u.

Is there an alternative to .endswith()?

I am trying to write an if, elif else clause, so that depending on the German word ending, we can see is it should go with der, die or das.
Here is my code:
word = input ("Enter word: ")
if (word.endswith('er' 'ismus')):
print ("der")
elif (word.endswith('falt' 'heit' 'keit' 'schaft' 'ung')):
print ("die")
else (word.endswith('chen' 'lein')):
print ("das")
I have also tried using suffix with square brackets but everything goes grey when I do that and so I can assume it won't work. And clearly true and false are not adequate responses for what I need. Is there anything else I can try?
Thanks in advance!
The endswith method really only checks if the word ends with one thing, but you can do something like:
def word_ends_with_one_of(word, options):
for option in options:
if word.endswith(option):
return True
return False
Then call that with:
suffix_die = ['falt', 'heit', 'keit', 'schaft', 'ung']
suffix_der = ['er', 'ismus']
suffix_das = ['chen', 'lein']
if word_ends_with_one_of(word, suffix_die):
print ("die")
elif word_ends_with_one_of(word, suffix_der):
print ("der")
elif word_ends_with_one_of(word, suffix_das):
print ("das")
As an aside, your else clause is currently problematic, it should not have a condition attached to it (unless it's a typo and you meant to have an elif instead).
Now, even though that you be a useful function to have for other purposes, you may want to consider a more application focused method since you'll be introducing a function anyway. By that, I mean something more closely suited to your specific needs, such as:
def definite_article_for(word):
# Could also use word_ends_with_one_of() in here.
if word.endswith('er'): return 'der'
if word.endswith('ismus'): return 'der'
if word.endswith('falt'): return 'die'
:
if word.endswith('lein'): return 'das'
return None
}
Then use article = definite_article_for(my_word) to get the article you want.

or condition in while loop python

Does or condition work in a while loop in python? I can't seem to make it work. This is the sample of how my code works.
newslot = 3
moved = False
while newslot > 0 or moved != True:
enabled = query something on the database where slot = newslot
if enabled:
print 'do something here'
moved = True
else:
newslot-=1
print 'slot disabled'
So when the newslot gets to value of zero it still proceeds to go inside the while loop.
I seem to be missing something here.
or is working as should be expected. A while loop will continue until its condition is false. If its condition is two separate conditions connected with an or, it will only be false when the two conditions are both false.
Your loop will continue repeating until moved is false and newslot is <= 0. I'm guessing you actually want to use and in this case, as you want the loop to stop once either condition is met.

Why won't my WHILE loops run in Python?

I'm a beginner programmer, learning in Python, but I was pretty sure I had a decent grasp of how to make most things run, until I came across this. As i was attempting to run a piece of code with an if..then statement nested inside, Python decided to throw me a curve ball by not running the if...then statements. When I try to run the program, all it does is continually run the one line of code I have inside the while loop, coming before the if...then statement.
Here's the code:
def deg_or_rad():
global deg_rad
deg_rad = False
while deg_rad == False:
query = raw_input("Are you working in 'degrees' or 'radians'? > ").lower
if query == "deg" or \
query == "degrees":
deg_rad = "deg"
print "Cool! I like degrees."
elif query == "rad" or \
query == "radians":
deg_rad = "rad"
print "Cool! I like radians."
else:
"Umm... I'm confused..."
I've tried a few other variables for the while loop, such as:
def deg_or_rad():
global deg_rad
deg_rad = False
while_variable = True
while while_variable == True:
query = raw_input("Are you working in 'degrees' or 'radians'? > ").lower
if query == "deg" or \
query == "degrees":
deg_rad = "deg"
print "Cool! I like degrees."
while_variable = False
elif query == "rad" or \
query == "radians":
deg_rad = "rad"
print "Cool! I like radians."
while_variable = False
else:
"Umm... I'm confused..."
Anyone have any ideas? I'm really confused by this point.
First, in this line:
query = raw_input("Are you working in 'degrees' or 'radians'? > ").lower
you're not calling the .lower() method, because there are no (). You're just setting query equal to the lower method of strings, so you're always taking the else branch.
Second, in this line:
"Umm... I'm confused..."
You're not printing anything, you just made a string. So even though that branch is being taken, you're not doing anything you can see.
This is a combination of two things that make it seem like nothing is happening.
To lower a string, you do s.lower(), not s.lower. s.lower is a method.
What you're doing is you're assigning that method to query. So, none of the ifs will ever match. This means the else branch is executed. But, you don't print "Umm... I'm confused...", you just have the string itself there. This leads to you not getting any output.
couple of things
lower is a function call, you should use it like lower()
You are not printing the string in the else: statement. So it appears like nothing is happening even though you are getting here. This is because that function itself will not match your previous conditions (the results of the function may)
Don't say while_variable == True or deg_rad == False just use while_variable or not deg_rad respectively. (This isn't really part of the problem, just bad style.)
You could trying printing things to try and debug where your function is deviating from expected behavior to try and narrow it down. For instance if you put in a debug print just after you capture query input you could see that it wasn't what you were hoping for.
example:
def deg_or_rad():
global deg_rad
deg_rad = False
while not deg_rad:
query = raw_input("Are you working in 'degrees' or 'radians'? > ").lower()
if query in ("deg", "degrees"):
deg_rad = "deg"
print "Cool! I like degrees."
elif query in ("rad", "radians"):
deg_rad = "rad"
print "Cool! I like radians."
else:
print "Umm... I'm confused..."
raw_input("Are you working in 'degrees' or 'radians'? > ").lower
You haven't called the lower method, so at this point query is always going to be a bound method object (something along the lines of <built-in method lower of str object at 0x1001a0030>).
Furthermore, in your else clause you have not used print, so the string is created then thrown away without being displayed.
Thus you get the raw_input, then nothing.

If vs. else if vs. else statements?

Are:
if statement:
if statement:
the same as
if statement:
elif statment:
and
if statement:
else statement:
the same?
If not, what's the difference?
No, they are not the same.
if statement:
if statement:
If the first statement is true, its code will execute. Also, if the second statement is true, its code will execute.
if statement:
elif statment:
The second block will only execute here if the first one did not, and the second check is true.
if statement:
else:
The first statement will execute if it is true, while the second will execute if the first is false.
The first one is different
if True:
print 'high' #printed
if True:
print 'low' #printed
than the second
if True:
print 'high' #printed
elif True:
print 'low' #not printed
and the third is invalid syntax
See tutorial.
Statement like if , else and else if are used in almost all programming languages to take a decision by the machine or software like Chrome ,Firefox and some other software....
if will be written initially in the if statement code.
else if will be executed if code if is not true.
else will be executed if none of them are true.
Below example will gives you more understanding about it.
if( something is true ){ // execute this code; }
else if( if previous condition is not true){ // then execute this code;}
else { //if none of the above are true finally execute this code. }
you can use number of else if statements between if and else, like example shown above also in the below. And remember "if" statement should start with if and ends with else
here I declared if code in two different ways.
below examples written in JavaScript ( concept apply same with Python )
Remember :
`elif` in (python) --same as-- `else if` in ( Java Script ).
print() in (python) --and-- document.write() in ( Java Script ).
Example 1:
var a=10; // declared variable with value `10`
if(a==20){ document.write("Twenty"); }
//above code is false because "a" value is not 20
else if(a==10){ document.write("Ten"); }
//above is true output comes as "Ten" a==10 //true
else if(a==10){ document.write("Forty"); }
// above also true because "a" is equal to 10 but it won't print in console
else{ document.write("None of them are correct!"); } //also not printed.
In the code above we declared var a=10 and else if a==10 is true in 2 cases, but "Ten" will be printed in console. And rest of the code will not be executed (or) run.
we can do it another way, we declare it with all if statements like below.
Example 2:
var a = 10;
if(a==10){ document.write('ten'); } // it will be printed because condition is `true`;
if(a==20){ document.write('twenty') } // not printed `false`
if(a==10){ document.write("hundred") } // this also `true` therefore printed in console.
else{ //document.write("none")} // not printed because `false`
Difference explained here.
in the " 1st example " we write code with if and else if statements , where code was terminated, because condition is true at-least one time. And rest of the code will not be executed even the condition is true.
In the "2nd example" we write code with all if statements, the code was executed in all cases and prints all true conditions in console, but in the 1st example it was not printed.
if statement:
if statement:
It is like individual conditions; each if statement is checked one after another.
The same as:
if statement:
elif statment:
It is like: the first if condition failed then check the next after the condition.
And:
if statement:
else statement:
It is like: Check the first if condition, and then execute the else block.
no, not the same.
if statement:
if statement:
second if executes whether first if executed or not.
if statement:
elif statment:
elif only executes if first if passes the statement to it. you can have any number of elif statements.
if statement:
else statement:
this is nearly same as if and elif statement. if first if condition doesn't satisfy the requirements, then it passes to the else which can be happen if the conditions not satisfied.
They are not the same. if executes if the condition is True, elif executes if the if is false and the elif is true, and else executes if the if is false.
Example:
if True:
print('This will be printed') #This will be printed
if True:
print('This will also be printed') #This will also be printed
if True:
print('This will be printed') #This will be printed
elif True:
print('This will not be printed')
if False:
print('This will not be printed')
else:
print('This will be printed') #This will be printed

Categories