Can you put multiple conditions in a if statement? [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
For example:
The if statement would take input from the user and would run the correct function for it.
if x == 1 or 2 or 3:
do this or that

Your current statement will always be true. It checks if x == 1 which may be true or false, then it checks the value 2 which is true, because all nonzero integers are "truthy". (And similarly for 3)
The correct way to check a single variable against multiple values is to use:
if x == 1 or x == 2 or x == 3:
Or, you could check if x is in a collection of values. This is usually the preferred way if there are lots of possible values to check.
if x in {1, 2, 3}:
This uses a set literal, but you could use any collection type such as a list or a tuple instead.
If you need to take a different action depending on the value of x, you can use if, elif, else
if x == 1:
# do something
elif x == 2:
# do something different
else:
# x did not match any of your values so raise an error or something

yes, you would want to do
if x == 1 or x == 2 or x == 3:
...
or you could do
if x in [1 ,2]:
...
in python

Related

Please help me solve this algorithm im in problem this code python (TypeError: 'NoneType' object is not iterable)? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 months ago.
Improve this question
it is my first post in StackOverflow I'm having trouble understanding and applying this exercise on my own with python please could help me!
getting this TypeError: 'NoneType' object is not iterable
This is the exercise Algorithm:
Definition: An integer is said to be perfect if it is equal to the sum of all its divisors. Examples: 6 and 28 are perfect since
6 = 1+2+3 (knowing that 1, 2 and 3 are the divisors of 6 less than 6)
28= 1+2+4+7+14 (knowing that 1, 2, 4, 7 and 14 are the divisors of 28 less than 28)
1) Create a function liste_divisors(), which accepts an integer N as a parameter and returns the list of its divisors less than N (1 included).
2) Make a function is perfect(), which accepts a (positive) integer N as a parameter and returns “True” if it is perfect and “False” otherwise (use the function from the 1st question)
3) Create a Perfect List() function, which accepts a Limit parameter, then returns a list containing the perfect numbers less than Limit
This is my attempt so far,
but there are errors, please help me to correct these errors and make it better
def liste_diviseur(N):
for i in range(1,N):
if(N%i == 0):
print(i)
def est_parfait(M):
s = 0
for i in liste_diviseur(M):
s += i
if(s == M):
return True
else:
return False
def liste_parfait(Limite):
if(Limite<est_parfait(Limite)):
return Limite
m = int(input('Giving an number :'))
print(liste_parfait(m))
As you iterate over the result of liste_diviseur() this latter function must return an iterable (something we can iterate).
It can be a sequence : a list or a tuple.
def liste_diviseur(N):
diviseurs: list[int] = []
for i in range(1,N):
if(N%i == 0):
print(i)
diviseurs.append(i)
return diviseurs
Or simpler you can use a Generator.
def liste_diviseur(N):
for i in range(1,N):
if(N%i == 0):
print(i)
yield i
Consider adding N itself to the divisors list.
N divided by N equals 1.
You can add N at the end of the loop.
Or you can have a higher range with range(1, N+1) as the upper bound is not comprised.
"1) Create a function liste_divisors()....and returns the list of its divisors.."
Your function just prints the divisors, You need to collect them in a list and return it.
Then you can iterate over the list in est_parfait(M).

Python - function that creates boolean term if modulo operator = 0 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 months ago.
Improve this question
I have to create a function that returns true if b is a divisor of a.
I haven't done anything with functions yet.
I made this:
def is_divisor(a,b):
a % b = i
if i > 0:
return False
if i = 0:
return True
is_divisor(10,5)
It should show true, but it doesn't.
The error in your code is on the line if i = 0: it should be if i == 0. To check for equality, use ==.
You can also simplify this function to simply:
def is_divisor(a, b):
return a % b == 0
Try this:
def is_divisor(a, b):
try:
remainder = a % b
except ZeroDivisionError:
return False
return remainder == 0
You should always check if you're dividing by 0! Otherwise your function is going to raise an exception.

Return just the item of a list if len(list) == 1 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
I have a list with possibly several items (tuples) that I need to return. But what about, in the case that I only get one item in my list, I would like to return the item itself and not a list with only one item. How could this be done?
This is my code:
def strength(self):
values = []
max_v = 0
my_list = []
for i in inspect.getmembers(self):
if not i[0].startswith('_'):
if not inspect.ismethod(i[1]):
if "name" in i:
continue
values.append(i[1])
my_list.append(i)
max_v = max(values)
result = [tup_item for tup_item in my_list if tup_item[1] == max_v]
result.sort(reverse=True)
if len(result) > 1:
return tuple(result)
else: # in case len(result) == 1
return result # this is where i get a list with only one item but
# i would like to get just the tuple itself
If your list only has one item, it's usually at the 0th index. Just return result[0]. I would not recommend it though, since you will have to differentiate between lists and tuples from wherever you're calling that function.

How to fix the recursive function? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
It's a simple question of recursive function, which extracting every digits from a positive number. As the comment mentioned, I have known the mistake is because of global variable, but I still have no idea to fix it to get expected result. Thanks.
def getdigits(n):
if n == 0:
return list_1[::-1]
list_1.append(n % 10)
return getdigits(int(n / 10))
list_1 = []
print(getdigits(120)) # output = [1,2,0]
print(getdigits(5)) # output = [5,1,2,0]
But the expected output should be
print(getdigits(120)) # expected output = [1,2,0]
print(getdigits(5)) # expected output = [5]
You are using the existing LIST that already have values from the previous function call.
First clear the list and then try to call for another value.\
Try it
def getdigits(n):
if n == 0:
return list_1[::-1]
list_1.append(n % 10)
return getdigits(int(n / 10))
list_1 = []
print(getdigits(120))
list_1.clear() #clear list values
print(getdigits(5))
def getdigits(n):
global list_1
if n == 0:
listTemp = list_1
list_1 = []
return listTemp
list_1.append(n % 10)
return getdigits(int(n / 10))
list_1 = []
print(getdigits(120)) # output = [1,2,0]
print(getdigits(5)) # output = [5]
you need to declare list 1 as a global varible inside your function so you can clear list one within th function
i have tested it and got that output

Counting even numbers in a given list [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm trying to count the numbers in a given list and only count the even numbers. I keep getting a syntax error and don't know what the issue is.
x = [1,5,4,7,2,10,8,19,27,26,54,80]
def count_evens(g_list):
y = 0
for i in g_list:
if g_list[i] % 2 = 0:
y = y + 1
else:
y = y + 0
print(str(y))
count_evens(x)
The syntax error is coming from if g_list[i] % 2 = 0: What's wrong about my syntax?
Thanks!
syntax error
You want to compare so use == not = (single equal is for assignment)
if g_list[i] % 2 == 0:
index is out of range
To loop through all elements of the list, you can use this form:
for i in g_list:
if i % 2 == 0: # No need for g_list[i]
# in your for loop,
# i is an element from the list, not an index
g_list[i] % 2 = 0 is an assignment statement (and an illegal one at that since you "Can't assign to an operator"). Assignment statements are not allowed in if statements (only expressions).
You want g_list[i] % 2 == 0 which is a logical expression.

Categories