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 9 years ago.
Improve this question
Now I'm talking about MATH brackets, not python brackets, I know that parentheses () work like in maths, ex:
i = 5*(2+2)
print (i)
#output = 20
But square brackets [] and curly brackets {} don't work... (I know why they don't work)
Thank you,
Using Python 3.2.2
You don't need "math" brackets -- just use nested parentheses. Humans use [] in writing out complex math expressions to make them more readable to other humans, but this isn't necessary. They don't mean anything different than regular parentheses. So, when writing code, just stick to the parentheses.
They don't work as grouping constructs - only parentheses will do that.
Square brackets define a list.
Curly brackets define either a set or a dictionary (if the elements appear as key: value).
Further to this, the extra level of clarity when dealing with multiple nestings is unnecessary, as most good IDEs will let you know when the parentheses count is imbalanced (and, you will also notice when the count is imbalanced from repetition).
Related
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 1 year ago.
Improve this question
for pl in pokemon_list:
if pl["pokemon"] == showtype:
result = f"stamina: {'{:.2f}'.format((pl['stamina']/statmax)*100)}% ("
for i in range(pl["stamina"]):
result += "*"
How do I convert the code above to a more pythonic way?
First, using str.format() inside of an f-string is not sensible. Pick one
technique or the other, depending on the situation. For readability and
maintainability, do the computations outside of the f-string. An f-string is an
awkward context for computation; but it's perfect for simple variable
interpolation. In your case, you'd probably be better off sticking to
format().
Second, list comprehension is just a tool. It's not the holy grail of Python.
Select the tool only when it makes sense. One key test is whether you want
to create a list. You do not, as far as I can tell.
Your comment implies that you want to return the first matching item during the
iteration. If so, just do it. While you're at it, help your reader by using
convenience variables to reduce the visual weight of the code.
fmt = "stamina: '{:.2f}'% ({}"
for pl in pokemon_list:
if pl["pokemon"] == showtype:
s = pl['stamina']
return fmt.format(100 * s / statmax, '*' * s)
Could this be rewritten in the style of a comprehension? Yes, but it would be
less readable, even after breaking it apart into three lines of code. Avoid the
temptation to write overly fancy code like this, which will just leave your
readers scratching their heads.
fmt = "stamina: '{:.2f}'% ({}"
gen = (
fmt.format(100 * pl['stamina'] / statmax, '*' * pl["stamina"])
for pl in pokemon_list:
if pl["pokemon"] == showtype
)
return next(gen, None)
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
for x in s[:].split():
s = s.replace(x, x.capitalize())
I want to know how the for loop will progress and what exactly s[:] means and will do?
Assuming s is a string, s[:] makes a copy of the string, and split() splits the string at spaces and returns an array of substrings, the for loop will then iterate over the substrings.
It's actually unnecessary because split returns an array, so even the though the for loop modifies the original string, the loop iterable isn't reevaluated multiple times, so you don't need to copy it.
s is very likely to be a string because the split is a method in str (of course, you can also say that s is an instance, which comes from a class that is defined by the user in which also has a split method ...)
Normally s[:] is like a slice. The following can help you to understand.
s ='abc AB C dd'
print(s)
print(s[:]) # same as s
print(s[:3]) # abc
print(s[4:6]) # AB
print(s[-1]) # d
for x in s[:].split():
s = s.replace(x, x.capitalize())
print(s) # Abc Ab C Dd # Now you know the capitalize is what, right?
digression
The following is a digression.
I think your question is very bad,
First, this question is very basic.
second, its subject is not good.
Note that an ideal Stack Overflow question is specific and narrow -- the idea is to be a huge FAQ.
And now, you tell me searching how the loop will work? I mean, if you are a programmer who must know how the loop it is.
so when you ask a question, you have to think twice about what the title name can benefit everyone. (not just you only)
I suggest that you can delete this question after you understand it.
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 3 years ago.
Improve this question
Why is the position of a loop header relative to the body is different from its usual one? How come a loop variable appears before the loop?
The code is taken from various programs
n=reduce(operator.mul,[int(x) for x in str(n)],1)
return value == sum(int(x) ** len(str(value)) for x in str(value))
It is, technically, not a loop. This is so-called comprehension syntax, borrowed into Python from Haskell (see comments for the full lineage). To follow traditions of math notation for sets, and distinguish a comprehension from a usual loop, loop-like enumerator comes in the end of the notation.
Find more of history of various comprehensions and generator expression in Python here http://python-history.blogspot.com/2010/06/from-list-comprehensions-to-generator.html
NOTE. The first of your expression contains a list comprehension, the list comprehension is the first and the most popular pythonic comprehension. The second one contains a generator expression, which, though, originally were called generator comprehension, according to PEP 289.
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 2 years ago.
Improve this question
I'm writing a program that will create a binary tree of the Morse Code alphabet (as well as a period and an apostrophe), and which will then read a line of Morse Code and translate it into English. (Yes, I know that a look-up table would be easier, but I need to sort out my binary trees). I think a good bit of my problem is that I want to put the values into the tree in alphabetical order, rather than by symbol order. But surely there must be a way to do that? Because if I had a million such values that weren't numeric, I wouldn't need to sort them into the simplest order for insertion...right?
It's reading from a text file where each line has one sentence in Morse Code.
- .... .. ... .. ... ..-. ..- -. .-.-.- for example, which is "This is fun."
1 space between symbols means it's a new letter, 2 spaces means it's a new word.
As it stands, I'm getting the output ".$$$" for that line given above, which means it's reading a period and then getting an error which is symbolized by ('$$$'), which is obviously wrong...
Like I said before, I know I'm being complicated, but surely there's a way to do this without sorting the values in my tree first, and I'd like to figure this out now, rather than when I'm in a time crunch.
Does anyone have any insight? Is this something so horribly obvious that I should be embarrassed for asking about it?
Welcome to SO and thanks for an interesting question. Yes, it looks to me like you're overcomplicating things a bit. For example, there's absolutely no need to use classes here. You can reuse existing python data structures to represent a tree:
def add(node, value, code):
if code:
add(node.setdefault(code[0], {}), value, code[1:])
else:
node['value'] = value
tree = {}
for value, code in alphabet:
add(tree, value, code)
import pprint; pprint.pprint(tree)
This gives you a nested dict with keys ., -, and value which will be easier to work with.
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 2 years ago.
Improve this question
Is it considered bad style to assign values to variables like this?
x = "foobar" or None
y = some_variable or None
In the above example, x gets the value 'foobar'.
No, it's a common practice. It's only considered bad style for expressions that are considerably longer than yours.
The primary danger of doing something like this is the possibility that (in the second case) some_variable is False but not None (the integer 0, for instance) and you don't want to end up with y equal to None in that case.
I also feel a bit unconfortable using that kind of expressions. In Learning Python 4ed it is called a "somewhat unusual behavior".
Later Mark Lutz says:
...it turns out to be a fairly common coding paradigm in Python: to
select a nonempty object from among a fixed-size set, simply string
them together in an or expression. In simpler form, this is also
commonly used to designate a default...
In fact, they produce concise one-line expressions that help to eliminate line noise from the code.
This behavior is the basis for a form of the if/else ternary operator:
A = Y if X else Z
OP's syntax is perfectly fine.
The official name for "assignment with or" is null coalescing and there's actually a Wikipedia page about it now! https://en.wikipedia.org/wiki/Null_coalescing_operator
This question may be useful as well:
Is there a Python equivalent of the C# null-coalescing operator?