Related
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).
When I run the following code, I get an error: "IndentationError: unident does not match any outer indentation level".
What am I doing wrong? I've included my code below for reference:
file=open('csquetionseasy.txt','r')
print(file.read(432))
answersinputeasy=input('enter the letter responding to the correct answer for all 3 questions e.g. BBB')
if answersinputeasy==('BAA'):
print('you got 3/3!')
else:
if answersinputeasy==('BAB'):
print('2/3!')
else:
if answersinputeasy==('BBB'):
print('1/3!')
else:
if answersinputeasy==('ABB'):
print('0/3!')
else:
if answersinputeasy==('AAB'):
print('1/3!')
else:
if answersinputeasy==('AAA'):
print('2/3!')
else:
if answersinputeasy==('ABA'):
print('1/3!')
Use elif rather than else. You need else statement to do something when if and elif statements evaluate to false.
if answersinputeasy==('BAA'):
print('you got 3/3!')
elif answersinputeasy==('BAB'):
print('2/3!')
elif answersinputeasy==('BBB'):
print('1/3!')
elif answersinputeasy==('ABB'):
print('1/3!')
elif answersinputeasy==('AAA'):
print('2/3!')
elif answersinputeasy==('ABA'):
print('1/3!')
else:
print('Invalid Input')
Also, if you want to indicate a block of code, you must indent each line of the block by the same amount, which is typically four spaces.
The reason that you are getting the error "IndentationError: unident does not match any other indentation level" is because you are chaining tabs together to create a nested logic statement (in pseudo-code):
if <condition>:
#then do something
else if <condition>:
#then do something else
else if <condition>
#then do something further else
This is not how Python likes to see syntax in a logical block. Additionally, the next error you're going to run into will surround the use of nested if statements inside of else clauses.
To run an else if statement in Python, you will want to use the syntax elif: followed by an indented line with the code that you want to execute if that condition is met (in pseudo-code):
if <condition>:
#then do something
elif <condition>:
#then do something else
elif <condition>:
#then do something further else
One other call out as a best practice, is that you should include an explicit else clause in a conditional block with a bunch of elif statements if you're not going to do any further validation on the string you're getting from the user. Imagine that the user passed in XYZ. They wouldn't meet any of the conditions you've defined, and because of that the code would just continue out of the bottom of this logic block (which may or may not be a good thing). In the following code, I've added an example of what an explicit else clause might look like, but it's up to you to ultimately decide what might make sense for your application:
file=open('csquetionseasy.txt','r')
print(file.read(432))
answersinputeasy=input('enter the letter responding to the correct answer for all 3 questions e.g. BBB')
if answersinputeasy==('BAA'):
# Code to be executed following an if-statement must be indented by 4 spaces:
print('you got 3/3!')
elif answersinputeasy==('BAB'):
# Code to be executed following an elif-statment (else-if) must be indented by 4 spaces:
print('2/3!')
elif answersinputeasy==('BBB'):
print('1/3!')
elif answersinputeasy==('ABB'):
print('0/3!')
elif answersinputeasy==('AAB'):
print('1/3!')
elif answersinputeasy==('AAA'):
print('2/3!')
elif answersinputeasy==('ABA'):
print('1/3!')
# Else clause would provide a default condition that executes if none of the prior cases are met.
else:
# Code following an else statment must be indented by 4 spaces:
#Example of a default Else-block entry:
print('Wasn\'t able to parase your entry into a valid answer!')
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!
For a given code:
pattern = r'(?:some_pattern)'
def find(seq):
ret = []
while True :
m= pattern_re.match(seq)
if not m :
break
myseq= m.group(2)
assert len(myseq)%3 == 0
assert len(myseq) > 6
ret.append(myseq)
pos = m.end()
return ret
sequence = 'some sequence'
my_seq = find(sequence)
this returns ret in which only first assert function is taken and not the second . Any solution for it ?
the question simply is how to make code consider both the assert function
For starters, why are you using assert?
As soon as the first assert fails an AssertionError is raised and execution of the program stops.
You should be using normal conditionals. Besides that, there is so much wrong with or unusualy with this code I seriously suggest you to read the Python tutorial at http://docs.python.org/tutorial/
Pointers:
print statement after return
usage of assert instead of conditionals
the unnecessary while loop
no proper indenting
Furthermore you pasted an example that plainly does not execute since the indenting is wrong and the function called on the last line does not exist in your code. Please be more precise if you want help :-)
What sorts of methods exist for prematurely exiting an if clause?
There are times when I'm writing code and want to put a break statement inside of an if clause, only to remember that those can only be used for loops.
Lets take the following code as an example:
if some_condition:
...
if condition_a:
# do something
# and then exit the outer if block
...
if condition_b:
# do something
# and then exit the outer if block
# more code here
I can think of one way to do this: assuming the exit cases happen within nested if statements, wrap the remaining code in a big else block. Example:
if some_condition:
...
if condition_a:
# do something
# and then exit the outer if block
else:
...
if condition_b:
# do something
# and then exit the outer if block
else:
# more code here
The problem with this is that more exit locations mean more nesting/indented code.
Alternatively, I could write my code to have the if clauses be as small as possible and not require any exits.
Does anyone know of a good/better way to exit an if clause?
If there are any associated else-if and else clauses, I figure that exiting would skip over them.
(This method works for ifs, multiple nested loops and other constructs that you can't break from easily.)
Wrap the code in its own function. Instead of break, use return.
Example:
def some_function():
if condition_a:
# do something and return early
...
return
...
if condition_b:
# do something else and return early
...
return
...
return
if outer_condition:
...
some_function()
...
from goto import goto, label
if some_condition:
...
if condition_a:
# do something
# and then exit the outer if block
goto .end
...
if condition_b:
# do something
# and then exit the outer if block
goto .end
# more code here
label .end
(Don't actually use this, please.)
while some_condition:
...
if condition_a:
# do something
break
...
if condition_b:
# do something
break
# more code here
break
You can emulate goto's functionality with exceptions:
try:
# blah, blah ...
# raise MyFunkyException as soon as you want out
except MyFunkyException:
pass
Disclaimer: I only mean to bring to your attention the possibility of doing things this way, while in no way do I endorse it as reasonable under normal circumstances. As I mentioned in a comment on the question, structuring code so as to avoid Byzantine conditionals in the first place is preferable by far. :-)
may be this?
if some_condition and condition_a:
# do something
elif some_condition and condition_b:
# do something
# and then exit the outer if block
elif some_condition and not condition_b:
# more code here
else:
#blah
if
For what was actually asked, my approach is to put those ifs inside a one-looped loop
while (True):
if (some_condition):
...
if (condition_a):
# do something
# and then exit the outer if block
break
...
if (condition_b):
# do something
# and then exit the outer if block
break
# more code here
# make sure it is looped once
break
Test it:
conditions = [True,False]
some_condition = True
for condition_a in conditions:
for condition_b in conditions:
print("\n")
print("with condition_a", condition_a)
print("with condition_b", condition_b)
while (True):
if (some_condition):
print("checkpoint 1")
if (condition_a):
# do something
# and then exit the outer if block
print("checkpoint 2")
break
print ("checkpoint 3")
if (condition_b):
# do something
# and then exit the outer if block
print("checkpoint 4")
break
print ("checkpoint 5")
# more code here
# make sure it is looped once
break
Generally speaking, don't. If you are nesting "ifs" and breaking from them, you are doing it wrong.
However, if you must:
if condition_a:
def condition_a_fun():
do_stuff()
if we_wanna_escape:
return
condition_a_fun()
if condition_b:
def condition_b_fun():
do_more_stuff()
if we_wanna_get_out_again:
return
condition_b_fun()
Note, the functions don't HAVE to be declared in the if statement, they can be declared in advance ;) This would be a better choice, since it will avoid needing to refactor out an ugly if/then later on.
There is another way which doesn't rely on defining functions (because sometimes that's less readable for small code snippets), doesn't use an extra outer while loop (which might need special appreciation in the comments to even be understandable on first sight), doesn't use goto (...) and most importantly let's you keep your indentation level for the outer if so you don't have to start nesting stuff.
if some_condition:
...
if condition_a:
# do something
exit_if=True # and then exit the outer if block
if some condition and not exit_if: # if and only if exit_if wasn't set we want to execute the following code
# keep doing something
if condition_b:
# do something
exit_if=True # and then exit the outer if block
if some condition and not exit_if:
# keep doing something
Yes, that also needs a second look for readability, however, if the snippets of code are small this doesn't require to track any while loops that will never repeat and after understanding what the intermediate ifs are for, it's easily readable, all in one place and with the same indentation.
And it should be pretty efficient.
Here's another way to handle this. It uses a single item for loop that enables you to just use continue. It prevents the unnecessary need to have extra functions for no reason. And additionally eliminates potential infinite while loops.
if something:
for _ in [0]:
# Get x
if not x:
continue
# Get y
if not y:
continue
# Get z
if not z:
continue
# Stuff that depends on x, y, and z
Effectively what you're describing are goto statements, which are generally panned pretty heavily. Your second example is far easier to understand.
However, cleaner still would be:
if some_condition:
...
if condition_a:
your_function1()
else:
your_function2()
...
def your_function2():
if condition_b:
# do something
# and then exit the outer if block
else:
# more code here
So here i understand you're trying to break out of the outer if code block
if some_condition:
...
if condition_a:
# do something
# and then exit the outer if block
...
if condition_b:
# do something
# and then exit the outer if block
# more code here
One way out of this is that you can test for for a false condition in the outer if block, which will then implicitly exit out of the code block, you then use an else block to nest the other ifs to do something
if test_for_false:
# Exit the code(which is the outer if code)
else:
if condition_a:
# Do something
if condition_b:
# Do something
The only thing that would apply this without additional methods is elif as the following example
a = ['yearly', 'monthly', 'quartly', 'semiannual', 'monthly', 'quartly', 'semiannual', 'yearly']
# start the condition
if 'monthly' in b:
print('monthly')
elif 'quartly' in b:
print('quartly')
elif 'semiannual' in b:
print('semiannual')
elif 'yearly' in b:
print('yearly')
else:
print('final')
There are several ways to do it. It depends on how the code is implemented.
If you exit from a function, then use return; no code will be executed after the return keyword line. Then the example code is:
def func1(a):
if a > 100:
# some code, what you want to do
return a*a
if a < 100:
# some code, what you want to do
return a-50
if a == 100:
# some code, what you want to do
return a+a
If you exit from a loop, use break. No code will be executed after break keyword. Then the example code is, for while and for loops:
a = 1
while (True):
if (a == 10):
# some code, what you want to do
break
else:
a=a+1
print("I am number", a)
for i in range(5):
if i == 3:
break
print(i)
If you exit from the basic conditional, then you can use the exit() command directly. Then code after the exit() command will not be executed.
NB: This type of code is not preferable. You can use a function instead of this. But I just share the code for example.
The example code is:
if '3K' in FILE_NAME:
print("This is MODIS 3KM file")
SDS_NAME = "Optical_Depth_Land_And_Ocean"
elif 'L2' in FILE_NAME:
print("This is MODIS 10KM file")
SDS_NAME = "AOD_550_Dark_Target_Deep_Blue_Combined"
exit()
else:
print("It is not valid MODIS file")
I scrolled through, and nobody mentioned this technique. It's straightforward compared to other solutions and if you do not want to use a try-except statement, this may be your best option.
#!/usr/bin/python3
import sys
foo = 56
if (foo != 67):
print("ERROR: Invalid value for foo")
sys.exit(1)
use return in the if condition will returns you out from the function,
so that you can use return to break the the if condition.