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
Related
i am having a bit of trouble understanding why the "while" loop in my code doesn't stop when the condition is met.
"""
:param duration: how long the loop will last in hours
:param time_pause: every x seconds the loop restarts
"""
time_start = readTime()
time_now = readTime()
time_end = time_start.hour + duration
time_sleep = conf.SETTINGS["LIGHT_UNTIL"]
print('Time when the script was started \n', time_start)
print('Script ends', time_end)
try:
while time_now.hour <= time_end or time_now.hour < time_sleep:
temp.read_temp_humidity()
lights.Lights_Time()
water.water_plants_1ch(ch_number=2, time_water=2)
time.sleep(time_pause)
time_now = readTime()
except KeyboardInterrupt:
# here you put any code you want to run before the program
# exits when you press CTRL+C
print("Keyboard interrupt \n", readTime()) # print value of counter`
The readTime() function uses this:
try:
ds3231 = SDL_DS3231.SDL_DS3231(1, 0x68)
print( "DS3231=\t\t%s" % ds3231.read_datetime() )
print( "DS3231 Temp=", ds3231.getTemp() )
return ds3231.read_datetime()
except: # alternative: return the system-time:
print("Raspberry Pi=\t" + time.strftime( "%Y-%m-%d %H:%M:%S" ) )
return datetime.utcnow()`
The first condition of the while loop is never met and the loop ends only on the second condition.
Can somebody help me?
It is evident from your code that, you are using an 'OR' between these conditions as in (x or y).
So the loop will continue its execution until both of these conditions equate to a false value.
ex : Consider the following while loop
`while( x || y)
{
//Do something
}`
Here the loop will continue to function as long as any one among x or y continue to
return true, the exit condition is when both x & y returns false.(NB : x & y are
assumed to be 2 different conditions in the pseudo code)
you said : "The first condition of the while loop is never met and the loop ends only on the second condition". From this I infer that, the first condition('time_now.hour <= time_end') is always false and the control flow exits the loop only when the second condition('time_now.hour < time_sleep') also becomes false.
POSSIBLE SOLUTIONS
You calculate 'time_end' as 'time_start.hour + duration'. So here you might have to check whether the variable 'duration' actually holds the correct/expected value, see if you ran into any errors in the calculation of 'duration'.
If you want the looping to stop when any one of the conditions is false, then you must use an 'and' operator instead of an 'or'.
ex : Consider the following while loop
`while( x && y)
{
//Do something
}`
Here the loop will continue to function as long as both x and y continue to return
true, the exit condition is when any one among them returns false.(NB : x & y
are assumed to be 2 different conditions in the pseudo code)
You should ensure that the variables in the looping conditions are getting updated in accordance with your intended logic on looping, any errors in the dynamic calculation of the variables that determine the looping condition will yield the wrong result, for example in your code the looping variables for your first condition are 'time_now.hour' and 'time_end', so make sure they are getting updated with the intended values on looping(you might have any logical errors in the calculation).
I think your issue will be fixed on following solution 1 given above.
Write the program that reads in input three integers a, b and c. If the integer c is equal to 1, then the program displays on output (prints) the value of a + b; if c is 2 then the program displays the value of a-b; if c is equal to 3 then the output will be the value of ab. Finally, if the value 4 is assigned to c, then the program displays the value of a^2 + ba. If c contains another value, the program displays the message "Error"
a = int(input())
b = int(input())
c = int(input())
if c == 1:
print(a + b)
if c == 2:
print(a - b)
if c == 3:
print(a * b)
if c == 4:
print(a**2 + b*a)
else:
print('Error')
Seems like you got it, just make use of elif instead of a chain of ifs, you can also add a message inside input('Here') that will be printed when prompting for an input
a = int(input("Enter a number: ))
b = int(input("Enter a number: ))
c = int(input("Enter a number: ))
if c == 1 :
print(a + b)
elif c == 2 :
print(a - b)
elif c == 3 :
print(a * b)
elif c == 4 :
print(a**2 + b*a)
else:
print('Error')
Your ifs work, but you have somewhat misaligned the logic.
Use if elif and else
if c==something:
print("this")
elif c==something_else:
print("that")
else:
print("error")
After the first if statement, you should use elif, which is short for "else if". There is no error message because there is no error, you just have your logic wrong. The compiler is treating every if statement independently, so else runs as long as c is not 4.
You're nearly there. The main problem with your program is your if statements are independent, where the problem statement suggests they should not be. Change them for elif statements, which will mean your Error branch only executes when c evaluates to an integer which is not in the set {1, 2, 3, 4}.
Problem 1: program has (possibly) poor control flow
In most programming languages, the if statement is a basic construct used to execute a block of code conditionally if an expression is true. In the following Python-like pseudocode, the code behind the if block is only executed if the value obtained by evaluating EXPRESSION is true:
if EXPRESSION:
# Do something only if EXPRESSION is true
# Execution continues here after the "if" block irrespective of
# whether EXPRESSION was true and the body of the "if" statement
# was executed.
You can augment if statements with else branches. In this case, we execute the body of the if statement if EXPRESSION evaluates to true, and we execute the other arm of the branch (the else branch) if the condition does not evaluate to true (by law of the excluded middle, it's false):
if EXPRESSION:
# As before, control is passed here if EXPRESSION is true.
else:
# If EXPRESSION was false, control is passed to this arm.
# After executing either the "if" arm or the "else" arm, control
# returns to the outer scope outside the "if" statement.
A more complex construct uses an else-if construct to allow you to nest "if" statements. For example, suppose we were implementing a simple call controller which tries to reach someone on their fixed telephone, calls their portable telephone if they are unavailable, and sends an email otherwise. Using the knowledge from above, we might write:
if answers(fixed_telephone):
# Connect to the fixed telephone to communicate
else:
if answers(portable_telephone):
# Connect to the portable telephone to communicate
else:
# Not available on either telephone. Send an email.
As you can imagine, this logic will become complex quickly if there are many nested "if" conditions, which is not unusual in real-world scenarios. Most programming languages provide a construct to pull the nested "if" statements to the top-level. In Python, this is elif, and the equivalent code to the above is:
if answers(fixed_telephone):
# ...
elif answers(portable_telephone):
# ...
else:
# ...
(comments elided for brevity).
In your code as currently written, each of your if statements will be executed independently except the last if c == 4, which will fall to the else branch if c is not equal to 4. As you want the tests of c to be mutually exclusive, i.e. you don't want anything to happen if an earlier case passed, and you only want to print an error if none of the cases were executed, you should use nested if statements, which are best implemented using the above elif language construct.
Problem 2: program assumes well-formed integers
Your program also assumes the values read from STDIN for a, b and c are well-formed integers. If you enter a value which cannot be parsed as an integer, it will crash on the integer conversion in the int(...) call, and will not fall through to reach your print('Error') line. This is an example of Python raising an exception because a problem has been encountered which the interpreter cannot itself recover from. Control flow will not begin executing the if blocks, so the print statement will never be executed.
If you want to fix that issue, you'll need to catch the error returned by the int(...) method when it cannot parse the provided value as an integer. This means learning to catch exceptions, which you can find out more about in the Python docs.
(Hint: Python will raise an built-in exception of type ValueError when the input to int cannot be parsed, so you need to wrap the calls which populate the three variables a, b and c with a try... catch block which catches such an error:
try:
a = int(input())
catch ValueError:
# Implement logic to handle this error, which may include
# returning an error from your function, setting a default
# value, or taking some action. You can optionally take
# some action locally, such as print a log message, and then
# re-raise the exception so it propagates to this method's
# callers (using the "raise" keyword).
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.
I have the following code:
for i in range(0,numClass):
if breaks[i] == 0:
classStart = 0
else:
classStart = dataList.index(breaks[i])
classStart += 1
classEnd = dataList.index(breaks[i+1])
classList = dataList[classStart:classEnd+1]
classMean = sum(classList)/len(classList)
print classMean
preSDCM = 0.0
for j in range(0,len(classList)):
sqDev2 = (classList[j] - classMean)**2
preSDCM += sqDev2
SDCM += preSDCM
return (SDAM - SDCM)/SDAM
I would like to convert this code to VB.NET.
But I am not sure where the if-elseif-statement ends.
Does it end after "classStart += 1"?
I feel it a bit difficult to see where the for-next-loops end as well in Python.
The code is taken from http://danieljlewis.org/files/2010/06/Jenks.pdf
Thank you.
Yes. Python uses indentation to mark blocks. Both the if and the for end there.
In Python, where your indented block ends, that is exactly where your block will end. So, for example, consider a bit simpler code:
myName = 'Jhon'
if myName == 'Jhon':
print(myName * 5)
else:
print('Hello')
Now, when you run this code (make sure to run it from a separate module, not from the interactive prompt), it will print 'Jhon' five times (note that Python will treat the objects exactly as they are specified, it won't even bother to try to convert the variable myName's value to a number for multiplication) and that's it. This is because the code block inside of the if block is only executed. Note that if the else keyword was put anywhere but just below the if statement or if you had mixed the use of tabs and spaces, Python would raise an error.
Now, in your code,
for i in range(0,numClass):
if breaks[i] == 0:
classStart = 0
else:
classStart = dataList.index(breaks[i])
classStart += 1
See, where the indent of for's block of code starts? One tab, so, everything indented one tab after the for statement, will be inside of the for block. Now, obviously, the if statement is inside of the for statement, so it's inside the for statement. Now, let's move to next line, classStart = 0 -- this is indented two tabs from the for statement and one tab from the if statement; so it's inside the if statement and inside the for block. Next line, you have an else keyword indented just one tab from the for statement but not two tabs, so it's inside the for statement, and not inside the if statement.
Consider putting curly-braces like these if you have coded in another language(s) before:
for i in range(0,numClass)
{
if breaks[i] == 0
{
classStart = 0
}
else
{
classStart = dataList.index(breaks[i])
classStart += 1
}
}
The simple differences are that you are not required to put parenthesis for your expressions, unless, you want to force operator precedence rule and you don't need those curly braces, instead, just indent them equally.
for i in range(0,numClass):
if breaks[i] == 0:
classStart = 0
else:
classStart = dataList.index(breaks[i])
classStart += 1
# end if
That is right. In Python, the indentation delimitates your condition block, differently from e.g., Matlab, where you would have to insert an "end" to mark the block's end. I like both ways though!
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