Condition checking for IF and WHILE loops while executing the statements of the loop - pseudocode

Considering following two loops :
if condition 1:
Statement1;
Statement2;
Statement3;
While condition2:
Statement1;
Statement2;
Statement3;
Now for IF loop; does condition1 is checked after executing each statement (statement1, statement2, statement3) or only after executing statement3?
Same question for While loop; Does condition2 is checked after executing each statement (statement1, statement2, statement3) or only after executing statement3?
(Statement1, statement2, and statement3 could manipulate the conditions)

x = 1
while x==1:
x = 2
print(x)
x = 3
print(x)
if x == 3:
x = 4
print(x)
x = 5
print(x)
'''
output:
2
3
4
5
No conditions were checked
before the statements inside the
block were finished
'''
And as stated in the comments, if is not a loop, and its condition is only checked once at the start. while is checked every time after it cycles through the indented part

Related

How to return to beginning of program from inside of if statement?

I'm practicing some basic coding, I'm running a simple math program running in the terminal on Visual Studio Code.
How do I create an option to return to the beginning of the program, or exit the program after getting caught in an if statement?
Example:
#beginning of program
user_input=input('Please select "this" or "that": ')
findings=user_input
If findings == this:
print(this)
# How can I redirect back to first user input question, instead
# of just ending here?
if findings == that:
print (that)
# Again, How do I redirect back to first user input, instead of
# the program ending here?
# Can I setup a Play_again here with options to return to user_input,
# or exit program? And then have all other If statements
# redirect here after completion? How would I do that? with
# another If? or with a for loop?
#end program
You can try wrapping the whole program in a while loop like this:
while(True):
user_input=input('Please select "this" or "that": ')
this = 'foo'
if user_input == this:
print(this)
continue
if user_input == this:
print(this)
continue
Unfortunately, that 'another technique' I thought of using didn't work.
Here's the code (the first example modified):
import sys
def main():
# Lots of setup code here.
def start_over():
return #Do nothing and continue from the next line
condition = 1==1 #Just a sample condition, replace it with "check(condition)".
float_condition = condition
def play(*just_define:bool):
if not just_define:
play_again = input('play again? "y" or "n"')
if play_again == 'y':
start_over() #Jump to the beginning of the prohram.
if play_again == 'n':
sys.exit() #Exit the program
while True:
if float_condition == True:
# print(float_condition)
play() #skip to play_again from here?
if float_condition == False:
#print(float_condition)
play() #skip to play_again from here?
#I removed the extra "main()" which was here because it'd cause an infinite loop-like error.
main()
Output:
play again? "y" or "n"y
play again? "y" or "n"n
Process finished with exit code 0
The * in the play(*just_define:bool) function makes the just_define parameter optional. Use the parameter if you want to only tell Python to search for this function, so it doesn't throw a ReferenceError and not execute anything that's after the line if not just_define:. How to call like so: play(just_define=True).
I've used nested functions. I've defined play so that you can call it from other places in your code.
Thanks to #Hack3r - I was finally able to choose to return back to the beginning of the program or exit out. But it resulted in a new issue. Now my print(results) are printing 4 or 5 times...
Here is the actual code I built and am working with:
def main():
math_Options=['Addition +','Subtraction -','Multiplication *','Division /']
math_func=['+','-','*','/']
for options in math_Options:
print(options)
print('Lets do some Math! What math function would you like to use? ')
while True:
my_Math_Function = input('Please make your choice from list above using the function symbol: ')
my_Number1=input('Please select your first number: ')
x=float(my_Number1)
print('Your 1st # is: ', x)
my_Number2=input('Please select your Second Number: ')
y=float(my_Number2)
print('Your 2nd # is: ', y)
z=float()
print('')
for Math_function in math_func:
if my_Math_Function == math_func[0]:
z=x+y
if my_Math_Function == math_func[1]:
z=x-y
if my_Math_Function == math_func[2]:
z=x*y
if my_Math_Function == math_func[3]:
z=x/y
if (z % 2) == 0 and z>0:
print(z, ' Is an EVEN POSITIVE Number')
if (z % 2) == 1 and z>0:
print(z, ' IS a ODD POSTIVE Number')
if (z % 2) == 0 and z<0:
print(z, ' Is an EVEN NEGATIVE Number')
if (z % 2) ==1 and z<0:
print(z, ' IS a ODD NEGATIVE Number')
if z==0:
print(z, 'Is is Equal to Zero')
print('')
play_again=input('Would you like to play again? "y" or "n" ')
if play_again == 'y':
continue
if play_again == 'n':
break
main()
main()

Get line number where first occurrence of a value appears?

I have a CSV file like below:
E Run 1 Run 2 Run 3 Run 4 Run 5 Run 6 Mean
1 0.7019 0.6734 0.6599 0.6511 0.701 0.6977 0.680833333
2 0.6421 0.6478 0.6095 0.608 0.6525 0.6285 0.6314
3 0.6039 0.6096 0.563 0.5539 0.6218 0.5716 0.5873
4 0.5564 0.5545 0.5138 0.4962 0.5781 0.5154 0.535733333
5 0.5056 0.4972 0.4704 0.4488 0.5245 0.4694 0.485983333
I'm trying to use find the row number where the final column has a value below a certain range. For example, below 0.6.
Using the above CSV file, I want to return 3 because E = 3 is the first row where Mean <= 0.60. If there is no value below 0.6 I want to return 0. I am in effect returning the value in the first column based on the final column.
I plan to initialize this number as a constant in gnuplot. How can this be done? I've tagged awk because I think it's related.
In case you want a gnuplot-only version... if you use a file remove the datablock and replace $Data by your filename in " ".
Edit: You can do it without a dummy table, it can be done shorter with stats (check help stats). Even shorter than the accepted solution (well, we are not at code golf here), but additionally platform-independent because it's gnuplot-only.
Furthermore, in case E could be any number, i.e. 0 as well, then it might be better
to first assign E = NaN and then compare E to NaN (see here: gnuplot: How to compare to NaN?).
Script:
### conditional extraction into a variable
reset session
$Data <<EOD
E Run 1 Run 2 Run 3 Run 4 Run 5 Run 6 Mean
1 0.7019 0.6734 0.6599 0.6511 0.701 0.6977 0.680833333
2 0.6421 0.6478 0.6095 0.608 0.6525 0.6285 0.6314
3 0.6039 0.6096 0.563 0.5539 0.6218 0.5716 0.5873
4 0.5564 0.5545 0.5138 0.4962 0.5781 0.5154 0.535733333
5 0.5056 0.4972 0.4704 0.4488 0.5245 0.4694 0.485983333
EOD
E = NaN
stats $Data u ($8<=0.6 && E!=E? E=$1 : 0) nooutput
print E
### end of script
Result:
3.0
Actually, OP wants to return E=0 if the condition was not met. Then the script would be like this:
E=0
stats $Data u ($8<=0.6 && E==0? E=$1 : 0) nooutput
Another awk. You could initialize the default return value to var ret in BEGIN but since it's 0 there is really no point as empty var+0 produces the same effect. If the threshold value of 0.6 is not met before the ENDis reached, that is returned. If it is met, exit invokes the END and ret is output:
$ awk '
NR>1 && $NF<0.6 { # final column has a value below a certain range
ret=$1 # I want to return 3 because E = 3
exit
}
END {
print ret+0
}' file
Output:
3
Something like this should do the trick:
awk 'NR>1 && $8<.6 {print $1;fnd=1;exit}END{if(!fnd){print 0}}' yourfile

How to select specific element list

I want to select a specific value provided by functions.
For example, p-value of shapiro.test.
Later to use unlist, I get lost in the next step to obtain this goal.
set.seed;df<-data.frame(A=runif(1:10),B=sample(0:50,10),C=rnorm(1:10,5));
A<-lapply(df, shapiro.test);B<-data.frame(unlist(A))
Column=colnames(df)
for(i in 1:3){
W[[i]]=A[[i]]$statistic
p[[i]]=A[[i]]$p.value
}
Finaldf=data.frame(Column,W,p)
Finaldf
It is possible to select in the same way presented in the loop.
The result with the method B is:
A.statistic.W A.p.value A.method A.data.name "0.861406032778689" "0.0792763017546299" "Shapiro-Wilk normality test" "X[[i]]"
B.statistic.W B.p.value B.method B.data.name
"0.924827600249041" "0.398982034565022" "Shapiro-Wilk normality test" "X[[i]]"
C.statistic.W C.p.value C.method C.data.name
"0.944304879567238" "0.601828906713825" "Shapiro-Wilk normality test" "X[[i]]"
The result after the loop is this:
Column W p
1 A 0.8614060 0.0792763
2 B 0.9248276 0.3989820
3 C 0.9443049 0.6018289
>

For-loop in lua with löve2D, deleting variable

i'm a bit beginner about coding, and my english isn't great, i hope i'll be able to make my question clear:
So I have a for-loop in my code, and 2 if in it, in each if, I see if something is true or false, if it's true, I delete a portion of the loop. like that:
for n=#Test,1, -1 do
if Test[n].delete == true then
table.remove(Test, n )
end
if Test[n].y > 0 then
table.remove(Test, n )
end
end
kind of like that, and my problem is, if the first if make Test[n] being deleted, then the game crash at the next if because Test[n] Doesn't exist anymore. I solved the problem by making 2 for-loop, one for each if.
But I saw someone who did it without 2 for-loop, and it's not crashing, I tried to figure what was wrong but I can't find it.
If someone could find what is wrong with what I wrote, I would be thankful!
So here is the moment that makes problem in my code, on line 9, if the condition are met, i table.remove(ListeTirs, n ), then on line 17, when code try to find it again for test it, it bug :
for n=#ListeTirs,1, -1 do
if ListeTirs[n].Type == "Gentils"
then local nAliens
for nAliens=#ListeAliens,1,-1 do
if
Collide(ListeTirs[n], ListeAliens[nAliens]) == true
then
ListeTirs[n].Supprime = true
table.remove(ListeTirs, n )
ListeAliens[nAliens].Supprime = true
table.remove(ListeAliens, nAliens)
end
end
end
if
ListeTirs[n].y < 0 - ListeTirs[n].HauteurMoitie or ListeTirs[n].y > Hauteur + ListeTirs[n].HauteurMoitie or ListeTirs[n].x > Largeur + ListeTirs[n].LargeurMoitie or ListeTirs[n].x < 0 - ListeTirs[n].LargeurMoitie
then
ListeTirs[n].Supprime = true
table.remove(ListeTirs, n)
end
end
I hope it's clear, I could post the whole code but I don't feel it's necessary, if it is, I will add it.
Thank you :)
for n=#Test,1, -1 do
local should_be_removed
-- just mark for deletion
if Test[n].delete = true then
should_be_removed = true
end
-- just mark for deletion
if Test[n].y > 0 then
should_be_removed = true
end
-- actually delete (at the very end of the loop body)
if should_be_removed then
table.remove(Test, n )
end
end

ruby multiple loop sets but with limited rows per set

Alrightie, so I'm building an CSV file this time with ruby. The outer loop will run up to length of num_of_loops, but it runs for an entire set rather than up to the specified row. I want to change the first column of a CSV file to a new name for each row.
If I do this:
class_days = %w[Wednesday Thursday Friday]
num_of_loops = (num_of_loops / class_days.size).ceil
num_of_loops.times {
["Wednesday","Thursday","Friday"].each do |x|
data[0] = x
data[4] = classname()
# Write all to file
#
csv << data
end
}
Then the loop will run only 3 times for a 5 row request.
I'd like it to run the full 5 rows such that instead of stopping at Wed/Thurs/Fri it goes to Wed/Thurs/Fri/Wed/Thurs instead.
class_days = %w[Wednesday Thursday Friday]
num_of_loops.times do |i|
data[0] = class_days[i % class_days.size]
data[4] = classname
csv << data
end
The interesting part is here:
class_days[i % class_days.size]
We need an index into class_days that is between 0 and class_days.size - 1. We can get that with the % (modulo) operator. That operator yields the remainder after dividing i by class_days.size. This table shows how it works:
i i % 3
0 0
1 1
2 2
3 0
4 1
5 2
...
The other key part is that the times method yields indices starting with 0.

Resources