I have a seemingly trivial problem. I write a definition and I don't know how to introduce conditional functions.
I have a definition that works:
def function_1 (kot):
if kot == True:
print ("Yes:")
else:
print ("NO:")
It wokrs good
function_1 (False)
No:
or
function_1 (True)
Yes:
But I would like to have such a thing in my definition
def function_1 (kot = True):
if kot == True:
print ("Yes:")
else:
print ("NO:")
and it doesn't work any more.
Because you need to call the function as you did in the above example
def function_1 (kot=True):
if kot == True:
print ("Yes:")
else:
print ("NO:")
function_1()
output:
Yes:
Related
In the code below, 'else' is same for all 'if' statements? Is there a way to have just one 'else' statement, rather than repeating the same code in all 'if' statement blocks for 'else' statement?
Here's example:
if condition A == "Yes":
print("A")
if condition B == "Yes":
print("B")
else:
print("D")
if condition C =="Yes":
print("C")
else:
print("D")
else:
print("D")
Flowchart
In the case of nested if else, you can use a guard type statement. guard is popular in case of nested if-else and provides a clean code.
Guard statement tries to element the else cases first. You know we write else cases to perform deviated paths. So what if we remove the
deviated paths first.
For example, if you have
if condition A == "Yes":
print("A")
if condition B == "Yes":
print("B")
else:
print("D")
if condition C =="Yes":
print("C")
else:
print("D")
else:
print("D")
Now I can formatting the following
// 1
if condiation A == "No" {
print("D")
return
}
// 2
if condition B == "Yes" {
print("B")
return
}
if condition C == "No" {
print("D")
return
}
print("C")
For more follow the link: - Youtube
You look like in a nested testing sequence
You test A
if A ok, you test B
if B ok you test C
if any test fail you print D
so ...
you eitheir leave the testing sequence test everything print all Yes result
or print D if any test fail (wich look like a big ERROR message)
or
you keep the ugly if else sequence
If you go for testing everything
you can create a function
def TestThis(Value, id):
if value == "Yes":
print(id)
return 1
else:
return 0
and call it like this:
if TestThis(A, "A") == 0:
integrity = 1
elif TestThis(B, "B") == 0:
integrity = 1
elif TestThis(C, "C") == 0:
integrity = 1
if integrity == 1:
print("D")
And I'm pretty sure you can find a way to finally get your sequence testing.
Edited to create that sequential testing that was the aim from the start
def earlier_semester(w1,w2):
if w1[1]<w2[1] or w1[0]=="Fall":
print "True"
else:
print "False"
A = ('spring',2015)
B = ('spring',2014)
C = ('Fall',2015)
D = ('Fall',2014)
print earlier_semester(A,B)
print earlier_semester(D,A)
print earlier_semester(A,C)
Getting answer and then None on the next line like:
False
None
True
None
The command print earlier_semester(A,B) calls the function earlier_semester with the arguments A,B and prints what that function returns. It returns, by default, None. Therefore None prints.
Let's demonstrate this. First, let's define a very simple function:
>>> def somefn():
... print "Hi"
...
Let's run the function:
>>> somefn2()
'Hi'
Now, let's print the function:
>>> print somefn()
Hi
None
The problem is that somefn has no explicit return statement. That means, by default, it returns None.
Let's try this again with a return statment:
>>> def somefn2():
... return "Hi"
...
>>> somefn2()
'Hi'
>>> print somefn2()
Hi
It no longer prints None.
You should use return inside the function instead of print. something like the below:
def earlier_semester(w1,w2):
if w1[1]<w2[1] or w1[0]=="Fall":
return "True"
else:
return "False"
If you no return at the end of function, you got None default value!
You don't need to type print("True") or print("False") for python to print out True/False.
Just type:
return True
return False
Python will automatically print out 'True' and 'False' values.
If you use your method, you're not defining what the function returns when the condition evaluates. The reason for this is because Python Functions work in a way so that it has to return "something".
So it does what you tell it to it:
Print "True" or Print "False"
Then prints out "None" after each function call.
Refer to amended code below:
def earlier_semester(w1,w2):
if w1[1]<w2[1] or w1[0]=="Fall":
return True
else:
return False
A = ('spring',2015)
B = ('spring',2014)
C = ('Fall',2015)
D = ('Fall',2014)
print(earlier_semester(A,B))
print(earlier_semester(D,A))
print(earlier_semester(A,C))
Why?
It returns:
if word[0] != word[-1]:
IndexError: list index out of range
If I change "print "Palindrome"" to "return True" and "return False" it returns nothing at all.
import sys
exstring = "f"
data = list(exstring)
def palindrome(word):
if len(word) < 2:
print "Palindrome"
if word[0] != word[-1]:
print "Not Palindrome"
return palindrome(word[1:-1])
palindrome(data)
First, you need an elif in there like Hypnic Jerk mentioned. Second you need to return after your prints.
Working code:
import sys
exstring = "radar"
data = list(exstring)
def palindrome(word):
if len(word) < 2:
print "Palindrome"
return True
elif word[0] != word[-1]:
print "Not Palindrome"
return False
return palindrome(word[1:-1])
palindrome(data)
What you want to do is this:
def palindrome(word):
if len(word) < 2:
return True
if word[0] != word[-1]:
return False
return palindrome(word[1:-1])
You do not need elif in this case. It's just good practice. The second if statement will not be reached unless the first is false anyway. More "correct" (but still completely equivalent) is:
def palindrome(word):
if len(word) < 2:
return True
elif word[0] != word[-1]:
return False
else
return palindrome(word[1:-1])
Furthermore, it's good practice to only let the function decide if it's a palindrome or not, and not print it. Instead, you should use it like this:
if palindrome(word):
print "Palindrome"
else
print "Not palindrome"
Don't mix functionality unless you have a good reason.
I am doing a palindrome-check assignment in Python. I have to use a for-loop to check if it is a palindrome or not.
I think that I am on to the right track, but I am having trouble returning the result of the loop. When running the program it always returns True, even when it is not a palindrome. I would really need help to see if I have done the for-loop correctly and how to return the correct result.
My program as it is now looks like this:
def main ():
showResult(testPalindrome(newText()))
def newText():
word = raw_input ('Hi, insert a word:')
clean = (',','!','.')
for i in clean:
cleanedText = word.replace(i, "").lower()
return cleanedText
def testPalindrome(cleanedText):
testword = cleanedText
list = [testword]
for i in range(len(list)/2):
if list[i] != list [-i-1]:
continue
else:
break
def showResult(palindrome):
if True:
print 'Yes, it is a palindrome '
else:
print 'No, it is not palindrome'
main ()
You never return anything from test_palindrome. Remember that it is not a palindrome if any letters fail to match, but all must match to pass, so:
for i in range(len(list)/2):
if list[i] != list [-i-1]:
continue
else:
break
Should become
for i in range(len(list)/2):
if list[i] != list [-i-1]:
return False
return True
Also, to make your code more robust, you could replace clean with string.punctuation (remembering to import string).
For testing is a string is a palindrome, compare it with its reverse.
In [1]: p = 'this is a test'
In [2]: p[::-1]
Out[2]: 'tset a si siht'
In [3]: p == p[::-1]
Out[3]: False
In [4]: q = 'racecar'
In [5]: q == q[::-1]
Out[5]: True
I would like
to check if a string can be a float before I attempt to convert it to a float. This way, if the
string is not float, we can print an error message and exit instead of crashing the
program.
so when the user inputs something, I wanna see if its a float so it will print "true" if its not then it will print"false" rather than crashing. I don't want to use built in functions for this. I need to make my own function for this.
I tried :
import types
def isFloat():
x = raw_input("Enter: ")
if(x) == float:
print("true")
if(x) == str:
print("false")
isFloat()
I don't know if its true or not but it wont work it wont print anything either
The recommended thing to do here is to try it:
try:
f = float(x)
print("true")
except ValueError:
# handle error here
print("false")
This underscores the Python philosophy "It's better to ask for forgiveness than for permission".
The only reliable way to figure out whether a string represents a float is to try to convert it. You could check first and convert then, but why should you? You'd do it twice, without need.
Consider this code:
def read_float():
"""
return a floating-point number, or None
"""
while True:
s = raw_input('Enter a float: ').strip()
if not s:
return None
try:
return float(s)
except ValueError:
print 'Not a valid number: %r' % s
num = read_float()
while num is not None:
... do something ...
print 'Try again?'
num = read_float()