codecademy 6 practice makes perfect - python

Can anyone explain this please?
def cube(number):
number = (number**3)
return number
def by_three(number):
if number % 3 == 0:
cube(number)
return number
else:
return False
by_three(3)
Oops, try again. by_three(3) returned 3 instead of 27
Why does this not return 27?

So the problem is that in your by_three function you are returning the parameter "number" passed into the by_three function and not returning the result of the cube function.
Your code:
def by_three(number):
if number % 3 == 0:
cube(number)
## problem is right here you should return cube(number) not number
return number
else:
return False
Fixed code.
def by_three(number):
if number % 3 == 0:
return cube(number) ## note the change here
else:
return False

Check you are not referring the returned value to variable number.The code will be like this.
def cube(number):
number = (number**3)
return number
def by_three(number):
if number % 3 == 0:
number=cube(number)
return number
else:
return False
print by_three(3)
Hope your problem is solved

For example, we have two functions:
def function1(num):
return num * 3
and second function
def function2(num):
if num%2 == 0:
print(num)
function1(num)
return num
If you call function(1), as expected it will return 1
If you call function(2), it will return 2 not 6. WHY?
Lets analyze this function2(2)
def function2(num): # num = 2
if num%2 == 0: # yes, it meets the condition
print(num)
function1(num) # it steps into function 1, this return num*3 == 6 however we do not know where it is saved (its address is unknown).
return num # this 'num' it is just the argument == 2

Related

The insert function is returning None

in python, I am trying to insert into a list recursively for a decimal to binary converter but the insert it is returning none
def dectob(num):
print(num)
if num==0:
return []
hnum = int(num/2)
if num - hnum == hnum:
asn="0"
else:
asn="1"
return dectob(hnum).insert(0,asn)
print(int(''.join(dectob(6666)))==1101000001010)
asn: answer
num: base ten number
hnum: integer of half of num
I tried everything I made this longer version so it prints all the data
def dectob(num):
print(num)
if num==0:
print("got")
blanklist=[]
print(blanklist)
return blanklist
hnum = int(num/2)
if num - hnum == hnum:
asn="0"
else:
asn="1"
ret= dectob(hnum)
print(ret)
print(asn)
return ret.insert(0,asn)
print(int(''.join(dectob(6666)))==1101000001010)
insert() modifies the list in place but does not return a value. Typically with functional programming you avoid side effects and treat most data structures as immutable, so insert() is probably the wrong choice here. Instead of mututaing the returned list, you can simply return the result of recursion along with the new value:
def dectob(num):
if num==0:
return []
hnum = int(num/2)
if num - hnum == hnum:
asn="0"
else:
asn="1"
return dectob(hnum) + [asn]
int(''.join(dectob(6666))) == 1101000001010
# True

Why does one part of conditional statements in Python returns None while others are ok?

I need to write a code that prints out valid or invalid for an input of letters and numbers for a license plate. The conditions are: first two characters must be letters, characters have to be between 2 and 6, and if numbers are used, 0 should not be the first, nor should a number appear before a letter.
I put the code below on Thonny and cannot understand why len(l) == 4 part of the conditional statement for def valid_order() returns None and does not execute the next line of the code whereas others work fine. My code should return "Valid" for CSAA50, but it returns invalid. Why?
Also, is there an elegant way to write def valid_order()?
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
if s[0:2].isalpha() and 6 >= len(s) >= 2 and s.isalnum() and valid_order(s):
return True
else:
return False
def valid_order(c):
n = []
l = list(c[2:len(c)])
for i in c:
if i.isdigit():
n += i
if n and n[0] == "0":
return False
if len(l) == 2:
if l[0].isdigit() and l[1].isalpha():
return False
if len(l) == 3:
if l[0].isdigit():
if l[1].isalpha() or l[2].isalpha():
return False
else:
if l[1].isdigit() and l[2].isalpha():
return False
if len(l) == 4:
if l[0].isdigit():
if l[1].isalpha() or l[2].isalpha() or l[3].isalpha():
return False
else:
if l[1].isdigit():
if l[2].isalpha() or l[3].isalpha():
return False
else:
if l[2].isdigit() and l[3].isalpha():
return False
else:
return True
main()

Blank List, Return False

I'm looking to write a function definition named has_evens that takes in sequence of numbers and returns True if there are any even numbers in the sequence and returns False otherwise.
My code is correct, except when it receives something empty, like "([])". I need to account for that. Here's my code:
def has_evens(s):
for num in s:
if num % 2 == 0:
return True
elif num % 2 != 0:
return False
if ([]):
return False
The final part is a desperate attempt to account for blank lists. More formally, it needs to pass this assertion:
assert has_evens([]) == False
You should only return True when an even is found:
def has_evens(s):
for num in s:
if num % 2 == 0:
return True
return False
Python has an any function to make this simpler:
def has_evens(s):
return any(num % 2 == 0 for num in s)
I answered my own question. I just needed to un-indent my lines
def has_evens(s):
for num in s:
if num % 2 == 0:
return True
else:
return False

Keep getting type error with decorative function

I keep getting a type error for this. I am experimenting with decorative functions. Any help is appreciated
def primer(func):
def primes(n):
print (n)
return None
#primer
def find_prime(n):
while True:
count = 2
if (count == n):
z = ("PRIME")
return z
elif (n % count == 0):
z = n / count
return z
else:
count += 1
continue
prime = find_prime()
prime(10)
def primer(func):
def primes(n):
print(n)
#return None: dont know why this is here, you could do without it
return primes
#The nontype error is occuring because your code is returning none
#so to fix that all you have to do is return the inner function
#primer
def find_prime(n):
while True:
count = 2
if (count == n):
z = ("PRIME")
return z
elif (n % count == 0):
z = n / count
return z
else:
count += 1
continue
prime = find_prime
# if you want to turn a function into a variable you have to make sure it's
# callable, which means no parantheses around it
prime(15) # then you can call it

'For' iterator in python doesn't return the right answer

I wrote this in python to calculate the number of primes under a given value. It prints "0" when I execute the code. Could anyone tell me why my code is going wrong?
def is_prime(x):
if x<2:
return False
else:
for value in range(2, x):
if x%value == 0:
return False
else:
return True
def primes_in(x):
primes = [ ]
for value in range(2, x+1):
if is_prime(value):
primes.append(1)
elif not is_prime(value):
primes.append(0)
else:
primes.append(0)
return sum(primes)
print primes_in(25)
See range function.
range(start, stop[, step])
for value in range(2, x+1):
if x%value == 0:
return False
This means value goes from 2 to x included. Which means that there will necessarily be x%value == 0. So your function always return False and then primes is a list of 0.
You should use for value in range(2, x).
The issue is in your is_prime function , you are looping from 2 to x inclusive of both , so x%x is always 0 ,and hence it will always return False.
You just need to loop till the sqrt of the number.
Example code -
def is_prime(x):
if x<2:
return False
else:
for value in range(2, int(x**(1/2))+1):
if x%value == 0:
return False
else:
return True
Also, in the other function you should start
def is_prime(x):
if x<2:
return False
else:
if x == 2:
return True
for value in range(2, int(x**(0.5)) + 1):
if x%value == 0:
return False
return True
def primes_in(x):
primes = []
for value in range(2, x+1):
if is_prime(value) == True:
primes.append(1)
elif is_prime(value) == False:
primes.append(0)
else:
primes.append(0)
return sum(primes)
print primes_in(25)

Categories