Why would this line throw a syntax error in Python - python

I am getting a syntax error on this line of code in Python (tried in both 2.7.5 and 3.3)
Can someone tell me what is wrong?
if (ctx.bytes[0] = t + len) < t:
Appreciate any help!
Added 10/31/2013: My problem has stemmed from the fact that an online converter probably converted the code badly from C to Python. So I REALLY need help on how to convert this program to Python (will prefer 3, but 2 is fine). I need a lot of help with this because I don't 1) understand fully what the C code is doing and 2) I am still very new to Python! So help is appreciated!!! The full C source is posted at Pastebin here: http://pastebin.com/JTT1srSb.

Python won't let you use a single equals sign (assignment operator) within a conditional expression, unlike languages like C. Instead, try doing the following:
ctx.bytes[0] = t + len
if ctx.bytes[0] < t:

Unlike C, the assignment operator does not return any value and so can not be used in expressions. Python's if statement's condition has to be an expression. You can replace your code with:
ctx.bytes[0] = t + len
if len:
PS: You don't need to put brackets around the condition of an if statement in Python.

(ctx.bytes[0] = t + len) < t
You are using assignment operator (=) in the boolean expression, which is not allowed in python.

Related

Is it possible to pass a lambda expression as an argument of a print function in a f-String?

Wanted to know why I it shows an error when I try this:
print(f"equal to: {lambda h, c : sqrt(h**2 + c**2)}") # error
and it worked when I tried this:
print("equal to", lambda h, c : sqrt(h**2 + c**2)) # doesn't show error
Why is there an error on the first one? Is it a bug or not? Is it not possible to use lambda expressions within a f-string?
extra details: I was using Visual Studio Code and it showed: Expected ":" Pylance
From the documentation:
Expressions in formatted string literals are treated like regular Python expressions surrounded by parentheses, with a few exceptions. An empty expression is not allowed, and both lambda and assignment expressions := must be surrounded by explicit parentheses. [...]
>>> print(f"equal to: {(lambda h, c : sqrt(h**2 + c**2))}")
equal to: <function <lambda> at 0x10228af70>
As to why, I suspect the amount of proper parsing that can be done during lexical analysis is limited, and so the parentheses are needed to help the parser.
(The above link includes a snippet of the grammar used to define f-strings, which hints at the differences between replacement fields and arbitrary Python expressions, but I will beg off trying to provide an explanation for them.)

What is the difference between using eval(*code*) and just *code*?

What is the difference between:
cerebro.addsizer(bt.sizers.FixedSize, **eval('dict(' + args.sizer + ')'))
and:
cerebro.addsizer(bt.sizers.FixedSize, dict(args.sizer))?
I ran the first one and it worked but the second one causes an error.
Can someone please help me?
Python’s eval() allows you to evaluate arbitrary Python expressions from a string-based or compiled-code-based input. This function can be handy when you’re trying to dynamically evaluate Python expressions from any input that comes as a string or a compiled code object.

If the f-string like string formatting available in Julia?

So I am new to Julia and learned various ways of string formatting. Mainly from websites similar to this.
So I use f-strings a lot in Python, not a big fan of .format(). So I was wondering since someone created Formatting.jl Package to bring .format() like feature in Julia, is there any ongoing or useful package which does same for f-strings? Now I googled a bit about it too but didn't find anything.
What my main issue is that I want to replicate this behaviour:
a = 10
b = 20
print(f'The multiplication is = {a * b}')
In case anyone wondering what are f-strings, refer to this.
Yes, it is possible with standard Julia strings:
x = "World!"
y = 42
greeting = "Hello $x, $(y^2) !" # gives "Hello World!, 1764 !"
See also here:
https://docs.julialang.org/en/v1/manual/strings/#string-interpolation
Edit:
The example in the comment above is
j = 10; b = 20
println("The numbers and their square are $j, $b and $(j^2), $(b^2)")
There are multiple packages, of which the least well known but my favourite is PyFormattedStrings.jl.
Compare:
Package
Syntax
PyFormattedStrings.jl
f"Our yield is {harvest(crop):.3G} kg."
Fmt.jl
f"Our yield is {$(harvest(crop)):.3G} kg."
Formatting.jl
fmt("Our yield is {:.3f} kg.", harvest(crop))
(Note that Formatting has no g/G support).
PyFormattedStrings.jl uses the printf syntax, so eg aligning right is done with {var:20g}, and not {var:>20g} as in Python. Fmt.jl does use the Python syntax.
Neither package supports the f"{4+4=}" syntax of Python 3.8. (Though Julia has #show).
If you want more control over numeric formatting than the default string interpolation, you can use the Formatting.jl package in Julia, which provides Python f-string functionality.

Python operator precedence when concatenating adjacent string literals

The docs say that two string literals that are next to each other are concatenated. For example:
>>>print("py" "thon")
python
However, this feature is implemented at compile time instead of runtime like the + and * operators, so this interesting effect occurs:
>>>print(2 * "py" + "thon")
pypython
>>>print(2 * "py" "thon")
pythonpython
I understand why this happens in the language, but I can't think of a reason for it to be that way. Is there a reason, or was it just easier to leave it alone?
Quite frankly, If I were to design python today, I would make
print ("py" "thon")
A syntax error
Same as
print (5 3)
I would guess that the reason for concatenating adjacent strings, is for consistency with bash / perl
echo "py""thon"

code to reverse any given string in python using basic python operators [duplicate]

This question already has answers here:
How do I reverse a string in Python?
(19 answers)
Closed 9 years ago.
I am new to programming. I am trying to write a code to print the reverse of any given string.
I have written the following code:
import math
string= raw_input ("Enter string")
n= len(string)
ol= n-1
for ol>-1,ol--:
print string[ol]
but i am getting syntax error. Please help me to figure this out.
Python tries very hard to present code in a readable way. This means you don't get many of the ugly, hard to understand shortcuts that other languages like C offer. Instead, you get other, much easier to understand shortcuts.
The code to loop over a range in python is:
for ol in range(n):
To iterate backwards, use
for ol in range(n-1,-1,-1):
But of course, someone couldn't resist and add an unreadable shortcut to the language:
print string[::-1]
Related:
Loop backwards using indices in Python?
Reverse a string in Python
You can use these links for your further work, i know that this answer is out of the topic:
Code Academy
People all over the world are learning with Codecademy.
Python the hard way
Learn Python The Hard Way, 3rd Edition
Python Monk
Free, interactive tutorials to help you discover Python idioms, in
your browser!
If you want to code the string reverse yourself, try this as well. This will be useful when you reverse a very large string. You just have to traverse only half of it.
Data = list("ABCDEF")
Len = len(Data)
for i in range(Len//2):
Data[i], Data[Len - i - 1] = Data[Len - i - 1], Data[i]
Data = ''.join(Data)
print Data
NOTE: This solution is just for learning. For practical purposes, use #Aaron Digulla's third option. It will give far better performance than anything else. Its called slicing. Read about it here http://docs.python.org/2/tutorial/introduction.html#strings
print string[::-1]

Categories