The Question:
5.Now write the function is_odd(n) that returns True when n is odd and False otherwise.
Finally, modify it so that it uses a call to is_even to determine if its argument is an odd integer.
I had to write a function for is_even(n) that returns True when n even and False otherwise. Here is my code:
def is_even(n):
return n % 2 == 0
def is_odd(n):
if is_even(n):
print "This is an even integer."
else:
print "This is an odd integer."
return n % 2 != 0
My Question:
I am a total beginner and find programming very hard but I love it for some reason, but why does this not work? I defined the function is_even(n) and is_odd(n), put is_even(n) into the is_odd(n) function, wrote and if/else else statement making if the function is_even is equal to true it should print out it is an even integer... When I put in is_odd(3); it prints out "This is an even integer" and returns True even though it should print out "This is an odd integer."
Update:
I changed my code to this and works fine.
def is_even(n):
return n % 2 == 0
def is_odd(n):
if is_even(n) == False:
print "This is an odd integer."
return n % 2 != 0
You're encountering IndentationError because you're being inconsistent with your indentation. As soon as you indent in Python, you have created a new block. You do this after block-introducing keywords, like if, while, for, etc. Python doesn't care how many spaces or tabs or whatever you use before your first block, but once you make the choice the first time, you must keep using the same number. I've added a line to your posted code to show you:
See how the r in return aligns with the f in if? It needs to align with the i. In this example your if is not at the proper indentation level relative to the first block, producing the error in question.
Related
Wrote this code in comp sci class and I cant get it to work, it always returns as false every time I run it. Its supposed to be a recursive binary search method... Any idea why it only returns false?
arr = [1,10,12,15,16,122,132,143,155]
def binarysearch(arr,num):
arr2 = []
if (len(arr) == 1):
if (arr[0] == num):
return 1
else:
return 0
for i in range (len(arr)/2):
arr2.append(0)
if (arr[len(arr)/2]>num):
for x in range (len(arr)/2,len(arr)):
arr2[x-(len(arr)/2)]=arr[x]
return binarysearch(arr2,num)
if(arr[len(arr)/2]<num):
for x in range(0, len(arr) / 2 ):
arr2[x] = arr[x]
return binarysearch(arr2, num)
num = raw_input("put number to check here please: ")
if(binarysearch(arr,num)==1):
print "true"
else:
print "false"
You're doing vastly more work than you need to on things that Python can handle for you, and the complexity is masking your problems.
After your base case, you have two if statements, that don't cover the full range—you've overlooked the possibility of equality. Use if/else and adjust the ranges being copied accordingly.
Don't create a new array and copy stuff, use Python's subranges.
Don't keep repeating the same division operation throughout your program, do it once and store the result.
If you want to print True/False, why not just return that rather than encoding the outcome as 0/1 and then decoding it to do the print?
Recall that raw_input returns a string, you'll need to convert it to int.
The end result of all those revisions would be:
def binary_search(arr,num):
if (len(arr) == 1):
return (arr[0] == num)
mid = len(arr) / 2
if (arr[mid] > num):
return binary_search(arr[:mid], num)
else:
return binary_search(arr[mid:], num)
num = int(raw_input("put number to check here please: "))
print binary_search(arr,num)
Suppose I want to solve the equation x + 3 = 40 using GNU bc. One way I could do this would be to start by checking to see if 0 is a solution, then checking 1, and so on, until I get to the right answer. (Obviously not the best way to do algebra, but oh well.) So I enter the following code into GNU bc:
int solver(int x);
define solver(x){
if(x + 3 == 40) return x;
x = x + 1;
solver(x)
}
solver(0)
It produces 37 - the right answer, of course - but the 37 is then followed by 37 zeros. Based on some experimentation, it seems like each zero comes from an instance of the if statement being false, but how do I prevent the zeros from showing up? I'm using GNU bc to solve more complicated functions and create more complex lists of numbers, so it really isn't practical for me to sort through all the zeros. Any help would be appreciated, since I haven't yet figured anything out.
For each operation that isn't an assignment, bc prints an exit status. One way to suppress that is to assign to the dummy value . (which is just the value of the last result anyway), another way is to make sure you explicitly print exactly what you need.
I would have written your function like this:
#!/usr/bin/bc -q
define solver(x) {
if (x + 3 == 40) return x
return solver(x+1)
}
print solver(0), "\n"
quit
A few remarks for your attempt:
I don't understand what your first line is supposed to do, I just dropped it
I've indented the code, added some whitespace and removed the semicolons – mostly a matter of taste and readability
I've simplified the recursive call to avoid the solver(x) line stand on its own, as this produces the spurious 0
As for your suspicion that the if statement produces the zeroes: try, in an interactive session, the following:
1 == 2 # Equality test on its own produces output
0
1 == 1 # ... for both true and false statements
1
if (1 == 2) print "yes\n" # No output from false if condition
if (1 == 1) print "yes\n" # If statement is true, print string
yes
I am just starting out programming and reading thru C++ Programming Principles and Practice. I am currently doing the Chapter 3 exercises and do not understand why this code I wrote works. Please help explain.
#include "std_lib_facilities.h"
int main() {
cout<<"Hello, User\n""Please enter a number (Followed by the 'Enter' key):";
int number=0;
cin>> number;
if (number%2) {
cout<<"Your number is an odd number!";
} else {
cout<<"Your number is an even number\n";
}
return 0;
}
When number is odd, number%2 is 1.
if (number%2) {
is equivalent to
if (1) {
Hence, you get the output from the line
cout<<"Your number is an odd number!";
When number is even, number%2 is 0.
if (number%2) {
is equivalent to
if (0) {
Hence, you get the output from the line
cout<<"Your number is an even number\n";
The modulus operator simply determines the remainder of the corresponding division problem. For instance, 2 % 2 returns 0 as 2 / 2 is 1 with a remainder of 0.
In your code, any even number entered will return a 0 as all even numbers are, by definition, divisible by 2 (meaning <any even number> % 2 == 0)
Likewise, any odd number entered will return 1 (for instance, 7 % 2 == 1 as 7 / 2 has a remainder of 1).
In c++, like in many programming languages, numeral values can be treated as booleans such that 0 relates to false while other numbers (depending on the language) relate to true (1 is, as far as I know, universally true no matter the programming language).
In other words, an odd number input would evaluate number % 2 to 1, meaning true. So if (number % 2), we know that the input number is odd. Otherwise, number % 2 must be false, meaning 0, which means that the input number is even.
"if" statements works on boolean values. Let's remember that boolean values are represented by "false" and "true", but in reality, it's all about the binary set of Z2 containing {0, 1}. "false" represents "0" and "true" represents "1" (or some people in electronics interpret them as "off/on")
So, yeah, behind the curtains, "if" statements are looking for 0 or 1. The modulus operator returns the rest of a / b. When you input any number and divide it by 2, you are gonna get a rest of 0 or 1 being it pair or an odd number.
So that's why it works, you will always get a result of 0 or 1 which are false and true by doing that operation that way.
think of modulus in terms of this:
while (integer A is bigger than integer B,)
A = A - B;
return A
for example, 9%2 -> 9-2=7-2=5-2=3-2=1
9%2=1;
the statement if (number%2) is what is called a boolean comparison (true false). Another way to write this statement identically is if(number%2 != 0) or if(number%2 != false) since false and zero are equivocal. You're taking the return value of the modulus operator function (a template object we will assume is an integer) and inserting it into an if statement that executes if the input does not equal zero. If statements execute if the input is -5,9999999,1-- anything but zero. So, if (2) would be true. if(-5) would also be true. if(0) would be false. if(5%2) would be 1 = true. if(4%2) would be if(0) = false. If it is true, the code in the body of the if statement is executed.
I've made this function for a HW but every time I run it python returns no result,
What am I doing wrong?.
mult
def mult( n, m ):
""" input two strings
output the product of those numbers
"""
if n==0 or m==0:
return
elif m<0:
m=abs(m)
m+m
mult(n-1,m)
return
else:
m+m
mult(n-1,m)
return
In Python return is a transtive verb. It is sort of like the verbs "say" or "go"
say what? go where? return what?
You seem to think of return as something which simply returns execution flow to the caller (perhaps returning the value of the last calculated expression) but it doesn't work that way.
def add(x,y):
return x+y
returns the sum of x and y
def add(x,y):
x+y
return
returns nothing (which is called None in Python). It computes the sum of x and y but then discards the result.
Think about return as "give to the guy who called me".
def four():
return 4
print("four is ", four()) # four is 4
So, if I need a four, I can call my handy new function: print("four is ", four()). print() calls four() to get a result. If I define four() with an empty return statement, it won't give me anything.
def four():
4
return
print("four is ", four()) # four is None
return with recursion is the same "giving to the caller" principle, only more complicated.
def add(n,m):
"""add two integers together. The second integer
cannot be negative"""
if m == 0:
return n
else:
return 1 + add(n, m-1)
For simplicity's sake, the second number cannot be less than 0. Now, think about the algorithm, and how the return <something> affects it. If m is zero, then n + 0 == n, so we only need to return n. Otherwise, we're adding one to our eventual answer and subtracting one from m.
add(2, 3) becomes
1 + add(2, 2)(the return means "give to the guy who called me" which is add(2, )), which becomes 1 + 1 + add(2, 1), which becomes 1 + 1 + 1 + add(2, 0), and when we see zero in that second spot, we just replace it with the first number, so it becomes 1 + 1 + 1 + 2 which is 5.
I have just started learning python 2.7.1, and I have written a code for a Cows and Bulls game, in which you need to guess a four digit number by continuously re-entering 4 digits till you get the right number.
But for some reason by code just lasts for 3 loops max. Here is the code:-
number=raw_input("Enter the 4 digit number to be guessed:")
a=map(int,str(number))
def Guess():
yournumber=raw_input("Enter your number now:")
b=map(int,str(yournumber))
i=j=k=0
while i<=3:
if a[i]==b[i]:
j+=1
elif b[i] in a:
k+=1
i+=1
print str(j),"Bulls and "+str(k),"Cows"
return yournumber
Guess()
c=Guess()
if c==number:
print "BINGO! You have guessed the number!"
else:
Guess()
There is actually no loop to keep asking for user input.
In your implementation, there are exactly three calls for the function Guess().
Your implementation:
Guess() # first call
c=Guess() # second call
if c==number:
print "BINGO! You have guessed the number!"
else:
Guess() # third call
#end
Instead, you should loop while the user gets it wrong. Try this block instead:
c=""
while c != number:
c = Guess()
print "BINGO! You have guessed the number!"