Pythonic way to check logics [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
What I have found so far in many cases python code for checking business logic or any other logic is some thing like below(simplified):
user_input = 100
if user_input == 100:
do_something()
elif user_input > 100:
do_sth_different()
else:
do_correct()
When a new logic need to be checked what new python programmer(like me) do just add a new bock in elif...
What is pythonic way to check a bunch of logic without using a long chunk of if else checking?
Thanks.

The most common way is just a line of elifs, and there's nothing really wrong with that, in fact, the documentation says to use elifs as a replacement for switches. However, another really popular way is to create a dictionary of functions:
functions = {100:do_something,101:do_sth_different}
user_input = 100
try:
functions[user_input]()
except KeyError:
do_correct()
This doesn't allow for your given if user_input > 100 line, but if you just have to check equality relationships and a generic case, it works out nicely, especially if you need to do it more than once.
The try except case could be replaced by explicitly calling get on the dictionary, using your generic function as the default parameter:
functions.get(user_input,do_correct)()
If that floats your boat.

Aside from the fact that the way you're doing it is probably the best way, you could also write it as:
user_input = 100
do_something() if user_input == 100 else
do_sth_different() if user_input > 100 else
do_correct()

Related

Difference among Yield vs. Print vs. Return [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Two questions/clarifications:
Most people may ask the difference between yield and return.
def square(n):
for i in range(n):
yield i**2
for i in square(10000000000):
print(i)
I understand this is a way to run the 'function' in a generator way. If we directly run print([i**2 for i in range(10000000000)]) or this way
def square():
return [i**2 for i in range(10000000000)]
Python will run almost infinite time. However, if we run in the generator way, we will save a lot of memories, and Python can keep printing the squared numbers. In the generator, we directly print out the result we got and do not save it anywhere. However, in a function-return way, we will save the results into a list so it will waste a lot of memories and time. Am I correct about this?
My another question is yield vs. print: if we want to save memories and hope to directly print out the results, then why don't we just use print to directly print out the result, like:
def square(n):
for i in range(n):
print(i**2)
square(10000000000)
Python will do the same thing as the yield-generator way, right? So what is the difference between yield and print? Thanks!
Depends on the purpose and the caller.
When you are print-ing, you are calling a console writer in the loop. Thus print sends to a fixed and forced destination.
When you are yielding, you are not calling anything, but simply return-ing your output in gradual way to "any" caller which can take it and do whatever it like.

Should you declare variable before hand in python when using list append and For loop? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
After receiving an error in the code below i ended up adding
new_list = []
summation = 0
after the second line. But i fail to understand why i had to do that. I thought variables did not have to be declared early on in python
a = int(input())
b = int(input())
while a <= b:
if a % 3 == 0:
new_list.append(a)
a += 1
for number in new_list:
summation += int(number)
print(summation / len(new_list))
In general, Python does not require variables to be declared (except for a couple of cases). In this case, you are not declaring a variable but rather initializing it. Let's imagine that variables are boxes. In python, you don't have to say, please make a box and call it x. The issue is when you come across summation += int(number). This tells python, please take out whatever is in the box called summation, add int(number) to it, and put it back in the box. But you haven't yet put anything in the box. So python says sorry, there's nothing in the box at the moment so I can't take anything out. Same for new_list.append(a), that asks python to please append a to whatever is in the box. So python looks in the box to figure out how to append something to it but it can't find anything so it shows an error.
You may ask, why doesn’t python just put 0 in the box? Well, python doesn't know that what you want in the box is an int. Maybe you wanted a fraction, a complex number, or something you make up yourself that happens to be able to be added to a number. The same goes for the list, python does not know that you wanted a list and not a set, dictionary, tuple, counter, queue, or some other collection. So rather than guess, and possibly get it wrong (which would cause all kinds of weird bugs due to the slight differences in how these work with addition), it just gives you an error.
It depends on what you're doing with the variable. If you're assigning a value to the variable, it will initialize the variable in the loop itself. But if you want to modify a variable like you did with .append(), you have to declare it first as it has to be declared to be modified.

Why isn't one of my variables defined? -Python 2.7 [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 years ago.
Improve this question
So I'm fairly new still to python, and I'm trying to create a "word guessing" program, and part of that is creating a function that takes the inputted letter and then compares it to a list of letters, however it does not seem to recognize my definition of the variable "guess" in while (guess != ans):, any thoughts on why that is?
(Also here's my code as a reference):
def main():
ans = str("a")
guess = str("null")
letterList = [A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z]
while (guess != ans):
if(letterList[0] == ans):
guess = letterList[0]
main()
Error:
NameError: Name 'guess' is not defined on line 5
Python is an interpreted language and the interpreter relies on indentation to distinguish the different blocks of code.
If you don't know what that is, here's something you could read:
https://www.geeksforgeeks.org/indentation-in-python/
The problem in your code lies within the while loop.
Because your variable "guess" is within the scope of the function main, so only other variables and functions inside "main" can see it.
Also, your letterList has a problem, because each character should be within quotes(" " or ' ') otherwise python interprets them as variables which are not even defined.
Your while loop is in a different scope, the "global" scope and that is why your program doesn't recognize the "guess" variable.
And your loop is infinite because "guess" will always be different than "ans" is not changing.
If you could express what you want to accomplish in a better way, I could help you out.
def main():
ans = str("a")
guess = str("null")
letterList=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
while (guess != ans):
if(letterList[0] == ans):
guess = letterList[0]

What's the correct way to pass by reference [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have seen other people ask a question but the only answers I have seen simply explain that python doesn't have the same concept of pass by reference vs pass by value as languages like C do.
for example
x=[0]
def foo(x):
x[0] += 1
In the past, I have been using this work around but it seems very un-pythonic so I'm wondering if there is a better way to do this.
let's assume for what ever reason returning values won't work, like in the case where this code runs on a separate thread.
Some python objects are immutable (tuple, int, float, str, etc). As you have noted, you cannot modify these in-place.
The best workaround is to not try to fake passing by reference, instead you should assign the result. This is both easier to read and less error prone.
In your case, you could call:
x = 0
def f(x):
return x + 1
x = f(x)
If you truly need to fake passing by reference (and I don't see why you would need that), your solution works just fine, but keep in mind that you do not actually modify the object.
x = 0
x_list = [x]
print(id(x_list[0])) # 1844716176
def f(x_list):
x_list[0] += 1
f(x_list)
print(x) # 0, not modified
print(id(x_list[0])) # 1844716208

Which of these two functions more "pythonic"? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I just want to know which way is more preferable in python.
Imagine two functions:
1 function:
def foo(key):
if bar.has_key(key):
return bar.get(key)
# do something with bar
# this will be executed if bar_key(key) is False
...
return something
2 function:
def foo(key):
if bar.has_key(key):
return bar.get(key)
else:
# do something with bar
# this will be executed if bar_key(key) is False
...
return something
As you can see the only difference is else statement. So the question is will it affect performance somehow. Or are there any reasons to include else in this type of functions?
If the choice is between those two approaches, I would pick the first one. return is pretty explicit that execution terminates at that point. I find if x { return y } else { ... } an anti-pattern for this reason (not just in Python -- I see this in C/C++ code and it irks me there, too).
If you are returning, an else block is entirely unnecessary and causes pointless indentation of a block of code that might be quite large. The more nested structures you have, the more difficult it is to maintain proper context in your head while reading code. For this reason I tend to prefer less nesting when it does not obfuscate logic, and in this case I don't think it would.
The pythonic way:
def foo(key):
return bar.get(key, something)
While this question is a little opinion based, I'd say the second is more Pythonic for the reason of "explicit is better than implicit". The second function is clearly saying "if this condition, do this. Otherwise, do this". On the other hand, the first function implies the "Otherwise" part.

Categories

Resources