How Does This Input Work with the Python 'Any' Function

How does this input work with the Python 'any' function?

If you use any(lst) you see that lst is the iterable, which is a list of some items. If it contained [0, False, '', 0.0, [], {}, None] (which all have boolean values of False) then any(lst) would be False. If lst also contained any of the following [-1, True, "X", 0.00001] (all of which evaluate to True) then any(lst) would be True.

In the code you posted, x > 0 for x in lst, this is a different kind of iterable, called a generator expression. Before generator expressions were added to Python, you would have created a list comprehension, which looks very similar, but with surrounding []'s: [x > 0 for x in lst]. From the lst containing [-1, -2, 10, -4, 20], you would get this comprehended list: [False, False, True, False, True]. This internal value would then get passed to the any function, which would return True, since there is at least one True value.

But with generator expressions, Python no longer has to create that internal list of True(s) and False(s), the values will be generated as the any function iterates through the values generated one at a time by the generator expression. And, since any short-circuits, it will stop iterating as soon as it sees the first True value. This would be especially handy if you created lst using something like lst = range(-1,int(1e9)) (or xrange if you are using Python2.x). Even though this expression will generate over a billion entries, any only has to go as far as the third entry when it gets to 1, which evaluates True for x>0, and so any can return True.

If you had created a list comprehension, Python would first have had to create the billion-element list in memory, and then pass that to any. But by using a generator expression, you can have Python's builtin functions like any and all break out early, as soon as a True or False value is seen.

How do you use input function along with def function?

You never actually defined x and y globally. You only defined it in the function when you did def smaller_num(x, y).

When you do smaller_num(x= input("Enter first number:-") ,y= input("Enter second number:-"))
, you aren't creating variables called x and y, you are just creating parameters for your function.

In order to fix your code, create the variable x and y before you call your function:

def smaller_num(x, y): ## Can be rephrased to  def smaller_num(x, y):
if x > y: ## if x > y:
number = y ## return y
else: ## else:
number = x ## return x
return number

x = input("Enter first number:-")
y = input("Enter second number:-")
result = smaller_num(x, y)
print("The smaller number between " + str(x) + " and " + str(y) + " is " + str(result))

The other reason your code is not working is because you're not assigning the returned value of the function back into a variable. When you return something from a function, and again when you call the function, you need to assign the value to a variable, like I have: result = smaller_num(x, y).

When you called your function, you never assigned the value to a variable, so it has been wasted.


Also, are you using Python 3 or 2.7? In python 3 using input() will return a string, and to convert this to an integer, you can call int() around the input() function.

using any() in return with for loop

In the following example you might see the difference:

from collections import namedtuple
Node = namedtuple('Node', ['state'])

state = 2
frontier = [Node(1), Node(1)]

print("Any frontier:", any(frontier))
print("Any state:", any(node.state == state for node in frontier))

The output is:

Any frontier: True
Any state: False

From the any documentation: Return True if any element of the iterable is true.

In the first case the iterable is the frontier and element in the iterable is the element in the frontier array.

In the second case the iterable is the list of comparisons between node.state and state and element is the result of this comparison.

How do Python's any and all functions work?

You can roughly think of any and all as series of logical or and and operators, respectively.

any

any will return True when at least one of the elements is Truthy. Read about Truth Value Testing.

all

all will return True only when all the elements are Truthy.

Truth table

+-----------------------------------------+---------+---------+
| | any | all |
+-----------------------------------------+---------+---------+
| All Truthy values | True | True |
+-----------------------------------------+---------+---------+
| All Falsy values | False | False |
+-----------------------------------------+---------+---------+
| One Truthy value (all others are Falsy) | True | False |
+-----------------------------------------+---------+---------+
| One Falsy value (all others are Truthy) | True | False |
+-----------------------------------------+---------+---------+
| Empty Iterable | False | True |
+-----------------------------------------+---------+---------+

Note 1: The empty iterable case is explained in the official documentation, like this

any

Return True if any element of the iterable is true. If the iterable is empty, return False

Since none of the elements are true, it returns False in this case.

all

Return True if all elements of the iterable are true (or if the iterable is empty).

Since none of the elements are false, it returns True in this case.


Note 2:

Another important thing to know about any and all is, it will short-circuit the execution, the moment they know the result. The advantage is, entire iterable need not be consumed. For example,

>>> multiples_of_6 = (not (i % 6) for i in range(1, 10))
>>> any(multiples_of_6)
True
>>> list(multiples_of_6)
[False, False, False]

Here, (not (i % 6) for i in range(1, 10)) is a generator expression which returns True if the current number within 1 and 9 is a multiple of 6. any iterates the multiples_of_6 and when it meets 6, it finds a Truthy value, so it immediately returns True, and rest of the multiples_of_6 is not iterated. That is what we see when we print list(multiples_of_6), the result of 7, 8 and 9.

This excellent thing is used very cleverly in this answer.


With this basic understanding, if we look at your code, you do

any(x) and not all(x)

which makes sure that, atleast one of the values is Truthy but not all of them. That is why it is returning [False, False, False]. If you really wanted to check if both the numbers are not the same,

print [x[0] != x[1] for x in zip(*d['Drd2'])]

Python call object function from user input

Try using getattr(object, name[, default]) like this:

class Player:
def status(self):
return "Active"

player1 = Player()
INPUT = 'player1.status'

input_list = INPUT.split('.')

method_to_call = locals()[input_list[0]]
for i in input_list[1:]:
method_to_call = getattr(method_to_call, i)

method_to_call()

Inputs vs print functions.. CONFUSED

Welcome to programming,
In the above statement print("Hello " + input("What is your name ") + "!")
whenever the print is called, print evaluates the parameter to print. In the print parameter the string also contains a function call. So the function in the print statement is called i.e. input("What is your name") this input function prints the string What is your name and reads the input from console, concatenates with the param of print statement.

How to input string to function?

This does it. There were a couple errors. First, in Python you start counting at 0, so you wanted to use astring[2] instead of astring[3]. Also you needed a value to be returned:

def scalc(p1):
astring = p1.split(",")
print(astring)
num1 = float(astring[0])
num2 = float(astring[1])
if astring[2] == "+":
add(num1,num2)
elif astring[2] == "-":
sub(num1,num2)
elif astring[2] == "*":
mult(num1,num2)
elif astring[2] == "/":
div(num1,num2)
return value

p1 = input("Enter two numbers and an operator, each separated by a comma: ")
scalc(p1)

Example:

input: "20,30,+"

Out[2]: 50.0

Creating an user input connected to my function

You would use input to request a string from the user; something like this :

def palindrome(phrase):
[...]

user_input = input("Enter some text:")

if palindrome(user_input):
print(f'{user_input} is a palindrome')
else:
print(f'{user_input} is not a palindrome')

How do I pass user input as a parameter in a function?

Use a dictionary to map state names to coordinates

states = {
"washington_dc": (38.9072, 77.0369),
"north_carolina": (35.7596, 79.0193),
"florida": (27.6648, 81.5158),
"hawaii": (19.8968, 155.5828),
"california": (36.7783, 119.4179),
"utah": (39.3210, 111.0937)
}

while True:
state1 = input("First state: ")
if state1 in states:
break;
else:
print("I don't know that state, try again")

while True:
state2 = input("Second state: ")
if state2 in states:
break;
else:
print("I don't know that state, try again")

distance_calc(states[state1], states[state2])


Related Topics



Leave a reply



Submit