Some questions about the following code - python

I have the following questions about the following code:
What value does 0 hold in the second line? Is it something like 'true' or 'false'? Or a numerical value?
Are the return statements necessary in the user_even function? The code works without them but it seems that all user-defined functions have a return statement in them or am I wrong?
def divisible(num1, num2):
return num1 % num2 == 0
def user_even():
num1 = int(input ("Choose a number: "))
num2 = int(2)
if divisible(num1, num2):
print ("It's even")
return
else:
print ("it's odd")
return
user_even()

For question 1, it evaluates the statement and returns a Boolean (True or False) value. The 0 is 0.
return 5 % 5 == 0 # Remainder of 5/5 is 0 so that returns True
return 5 % 4 == 0 # Remainder of 5/4 is 1 so that returns False
For question 2, the return statements are not needed. A return statement should be used for variables or pieces of data that need to be returned from the function. In the code you provided, there is no data being returned so there is no need for the return statement.

1.) Return will be boolean because you used Comparator Operators (==)
2.) return statement is not necessary. Refer to this thread.
Is it ok to skip "return None"?

Related

When I attempt to execute my recursive function with odd numbers ,i have a kern problem

There is a problem with odd numbers.
When I run the function on even numbers, the code works.
#recursive demo function1
#Even nums
def evenNum(num):
if num % 2 != 0:
print("enter a even number")
if num == 2:
return num
else:
return evenNum(num-2)
evenNum(5)
output : Canceled future for execute_request message before replies were done
The second if should be changed to elif. When number is odd it prints "Enter a even number" and then compares it to 2. As it is different, it calls the function again.
Here is fixed code
def evenNum(num):
if num % 2 != 0:
print("enter a even number")
elif num == 2:
return num
else:
return evenNum(num-2)
evenNum(5)
Btw. make sure the number is greater than 0.
#recursive function1
#positive Even nums
def evenNum(num):
print(num)
if num % 2 != 0:
return print("enter an even number")
elif num == 2:
pass
else:
return evenNum(abs(num)-2)
evenNum(5)
Thank you for your valuable advice.
I learned some things about return and kern error.

No output after calling function (Python) [duplicate]

This question already has answers here:
What is the purpose of the return statement? How is it different from printing?
(15 answers)
Closed 6 months ago.
just a total newbie here. I am learning Python and was trying to call the function as below, yet I cannot see any output.
nums = [0,1,2,7,14]
def has_lucky_num(nums):
#return numbers that can be divisible by 7
for num in nums:
if num % 7 == 0:
return True
return False
has_lucky_num(nums)
Can someone tell me why it did not work? Thanks in advance.
Your program isn't printing anything because it doesn't have a print() command anywhere. Try the following line : print(has_lucky_nums(nums)), and it should print your True or False result! So you would have the following code :
nums = [0,1,2,7,14]
def has_lucky_num(nums):
#return numbers that can be divisible by 7
for num in nums:
if num % 7 == 0:
return True
return False
print(has_lucky_num(nums))
Your function has a problem:
You must put the return False after loop because if you don't it return immediately after checking first item
So function code must be this:
nums = [0,1,2,7,14]
def has_lucky_num(nums):
#return numbers that can be divisible by 7
for num in nums:
if num % 7 == 0:
return True
return False
If you want to see result you must print the result returns by the function has_lucky_num()
So all you have to do is to add a print like this:
Instead Of:
has_lucky_num(nums)
Replace With:
print(has_lucky_num(nums))
Output:
True
Return True and Return False won't actually display anything. You need to do something with those values, for instance:
if has_lucky_num(nums) == True:
print(f'{nums} has a lucky number!')
else:
print(f'{nums} has a lucky number!')
```

Explain how python execute this function? [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 2 years ago.
def check_even_list(num_list):
# Go through each number
for number in num_list:
# Once we get a "hit" on an even number, we return True
if number % 2 == 0:
return True
else:
return False
now when execute function
[1]-check_even_list([1,2,3])
False
[2]-check_even_list([2,1,3])
True
why this True when #3 is return False ???
[3]-check_even_list([1,4,2])
False
Why this False when #2 is return True ???
Your code will only ever check the first element, once a return statement is hit, no further code in your function will execute. Instead you could modify your code to
def check_even_list(num_list):
# Go through each number
for number in num_list:
# Once we get a "hit" on an even number, we return True
if number % 2 == 0:
return True
# After loop, must not have hit an even number
return False
For conciseness, you could also write the equivalent
def check_even_list(num_list):
return all(i % 2 == 0 for i in num_list)
You are using "early return statements". What your function does is actually only evaluating the first element of your list.
Here's I would write the function:
def check_even_list(num_list):
return all(map(lambda x: x % 2 == 0, num_list))
This is because once return statement is executed, function is not executed any more.
Use this code:
def check_even_list(num_list):
# Go through each number
for number in num_list:
# Once we get a "hit" on an even number, we return True
if number % 2 == 0:
return True
# After loop is completed and no even values encountered
return False
and if you want to do just the opposite i.e. return false once an odd number is hit:
def check_odd_list(num_list):
# Go through each number
for number in num_list:
# Once we get a "hit" on an odd number, we return True
if number % 2 != 0:
return False
# After loop is completed and no odd values encountered
return True

Default function in Python using min

For my problem I have to write a min function that can take up to 4 numeric arguments but must have at least 2. The third and fourth arguments have to be set to None if they aren't passed a value. The function should return the smallest value of those passed and must work with either 2, 3, or 4 values.
This is what I have:
def min(num1, num2, num3=None, num4=None):
if num1<num2:
result=num1
elif num2<num1:
result=num2
elif num3>None:
if num3<num1 and num3<num2:
result=num3
else:
min_num=num4
return result
When I run it in python and enter 4 values, it doesn't return the minimum number. It just returns a random number from the four arguments I entered. Can anyone help me out?
You are using elif which only executes if if condition is false. So, you can fix by using all if conditions. Also, you have default value to None which you can compare using != None. You can try something like:
def minimum(num1, num2, num3=None, num4=None):
# this first if else will check with num1 and num2 only
if num1 < num2:
result = num1
else:
result = num2
# after checking between num1 and num2
# the result will be checked with num3
# if num3 is provided
if num3 is not None and num3 < result:
result = num3
# if num4 also provided then the result will be compared with it
if num4 is not None and num4 < result:
result = num4
return result
Your logic is flawed in several ways. Draw the logic tree your want, the way you would do it with a list of numbers, and implement that, rather than what you've posted here.
if num1<num2:
result=num1
elif num2<num1:
result=num2
elif ...
Look at the logic here: the only way you get to the last two arguments is if num1 == num2. If you feed your function (5, 7, 1, 0), it will return 5.
elif num3>None:
What are you trying to do here? None is not a valid numerical value; this is an illegal comparison. Try
if num3 is not None and ...
Suggested logic: keep track of the smallest number so far in a separate variable; compare each value against that.
This can be a solution in order to avoid the ifs and using an in-built function.
def my_min(num1, num2, num3=None, num4=None):
my_numbers = [num1, num2, num3, num4]
return min(my_numbers)
print(my_min(4, 3, 2, 1))
First of all, you shouldn't use the min() as your function name, because it is a keyword of python.
Secondly, the number of "if-else" conditions should be minimal, it is too much, you might need to think about other options.
def custom_min(num1, num2, num3=None, num4=None):
min_value = num1
for num in [num2, num3, num4]:
if !(num is None) and min_value>num:
min_value = num
return min_value
print(custom_min(1, 2))
print(custom_min(2, 1, 4))
print(custom_min(2, 1, 4, 0))
The output is:
1
1
0

Making a GCF calculator in python

I'm making a calculator in python that takes in two numbers and returns the greatest common factor of it. When I create a function that returns the same numbers of the two lists of factors, I keep getting a 'index' error even if I stated
if len(one) == 0 and len(two) == 0:
here's my code:
def work(one, two):
for i in range(len(one)):
for j in range(len(two)):
if len(one) != 0 and len(two) != 0:
if one[i] == two[j]:
one.pop(i)
two.pop(j)
if len(one) == 0 or len(two) == 0:
break
else:
work(primeF, primeF2)
break
work(primeF, primeF2)
What could I do to fix this?
You can greatly simplify your code by using what is already available in Python's standard library:
>>> import fractions
>>> work = fractions.gcd
>>> work(12345, 67890)
15
The fractions.gcd function should do exactly what you want without the need for more code. Here is a copy of the function from the module's source:
def gcd(a, b):
"""Calculate the Greatest Common Divisor of a and b.
Unless b==0, the result will have the same sign as b (so that when
b is divided by it, the result comes out positive).
"""
while b:
a, b = b, a%b
return a
I think that instead of checking whether the list length is 0, you need to be checking that the list is long enough to include your index.
There is an even easier way to do it without modules (I just used time for supplements)
import time
def gcf (num1, num2): #The Actual Calculator
if num1 > num2:
num1, num2 = num2, num1
for x in range (num1, 0, -1):
if num1 % x == 0 and num2 % x == 0:
return x
def run(): #This section is defined so that it can be run multiple times
num1 = int(input("First Number: ")) #First number
num2 = int(input("Second Number: ")) #Second number
print (str (gcf (num1, num2)))
run_again = input("Run again? y or yes for yes: ")
if run_again == "yes" or run_again == "Y" or run_again == "Yes" or
run_again == "y":
run()
elif run_again == "hello":
print("hi")
run()
else:
print("Goodbye!")
time.sleep(1.5)
quit()
#Runs the code
run()

Categories

Resources