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
Related
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()
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
I am creating a function which returns True when a number(here X) is Prime.
So I am checking whether the given number is evenly divisible by integers from 2 to X-1.
But the while loop breaks when the check returns True.
Help
def is_prime(x):
n = 2
if x < 2:
return False
elif x == 2:
return True
else:
while True and n < x:
if x % n == 0:
return False
else:
n += 1
return True #--The loop is breaking here--
You code should look like this:
def is_prime(x):
n = 2
if x < 2:
return False
elif x == 2:
return True
else:
while n < x:
if x % n == 0:
return False
else:
n += 1
# Put the return True after the loop
return True
print('{}: {}'.format(10, is_prime(10)))
print('{}: {}'.format(11, is_prime(11)))
print('{}: {}'.format(0, is_prime(0)))
print('{}: {}'.format(1, is_prime(1)))
print('{}: {}'.format(2, is_prime(2)))
print('{}: {}'.format(113, is_prime(113)))
Output:
10: False
11: True
0: False
1: False
2: True
113: True
Well You used return statment in loop, so it exited from method. You need to change the logic of this loop. Check here:
Python Prime number checker
I'm currently learning python for fun. I'm used to coding in C++ and so far it's fairly easy to pickup. I wrote my first program on my own, but for some reason, it doesn't do anything and the functions I wrote won't execute. If I write print statements outside the functions, the statements execute, but it never goes inside the function. Here is my code. Any tips would be much appreciated.
racks = 1000000
sum = 0
def ConsecutivePrime():
primeNum = 0
stack = []
while(StackAdder == False):
primeNum = isPrime(primeNum)
stack.append(primeNum)
StackAdder(stack)
if(StackAdder == True):
print ("Largets Prime: ", sum)
def StackAdder(stack):
for n in stack:
sum += n
if(count < racks):
return False
else:
stack.pop()
return True
def isPrime(primeNum):
isPrime = False
while(isPrime == False):
primeNum += 1
if(primeNum % 2 == 1): #First Checks If Odd
if(primeNum % 3 == 0):
isPrime == False
elif(primeNum % 5 == 0):
isPrime == False
elif(primeNum % 7 == 0):
isPrime == False
elif(primeNum % 9 == 0):
isPrime == False
else:
isPrime == True
if(isPrime == True):
return primeNum
def main():
ConsecutivePrime()
if __name__ == "__main__":
main()
StackAdder is a function; it is neither True nor False, so ConsecutivePrime is called, it just doesn't do anything.
Add these lines at the beginning of your ConsecutivePrime() function, and observe the output:
print(StackAdder == True)
print(StackAdder == False)
You can see False printed twice, right? Surprised? Read the comments on the answer by Scott Hunter. May be that will help a little.
So, your conditionals for both while and if are False.
If what you wanted was to check what value StackAdder() returned, you need to do it like this:
def ConsecutivePrime():
primeNum = 0
stack = []
while(StackAdder(myStack) == False): # define myStack to your needs
primeNum = isPrime(primeNum)
stack.append(primeNum)
StackAdder(stack)
if(StackAdder(myStack) == True):
print ("Largets Prime: ", sum)
There are major problems in the way you structured your code, and I will try to point out the most obvious mistakes in your functions:
1) Regarding the function isPrime(primeNum), this is the correct way of writing it:
def isPrime(primeNum):
isPrime = False
while not isPrime:
primeNum += 1
if(primeNum % 2 == 1): #First Checks If Odd
if(primeNum % 3 == 0):
isPrime == False
elif(primeNum % 5 == 0):
isPrime == False
elif(primeNum % 7 == 0):
isPrime == False
elif(primeNum % 9 == 0):
isPrime == False
else:
isPrime == True
return primeNum
I rewrote while(isPrime == False) as while not isPrime. Also, you don't need the if(isPrime == True) statement, because the while loop will be exited when isPrime == True.
2) In the function StackAdder(stack), you are introducing count, which was not defined before. Maybe you wanted sum instead? Or maybe you were trying to use the count() method (which returns the count of how many times an obj occurs in a list?)
3) In the function ConsecutivePrime(), Stackadder is a function, so your code should be: while(StackAdder(stack) == False)
Ok, so here is my code:
def is_prime(n):
n = abs(int(n))
if n < 2:
return False
elif n == 2:
return True
elif n%2 == 0:
return False
else:
prime(n)
def prime(n):
for x in range(3, int(n**0.5)+1,2):
if n%x == 0:
return False
else:
return True
print is_prime(6577)
But whenever I run this in my shell it returns 'None', I don't understand why. Any help would be appreciated.
Your final else in is_prime returns nothing. You can even remove the else altogether, but that's just personal preference
def is_prime(n):
# You don't really need to take abs value cause you already do a check for < 2 which includes negative numbers
n = abs(int(n))
if n < 2:
return False
elif n==2:
return True
elif n%2 == 0:
return False
return prime(n)