My code won't work, because of operators:PYTHON [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am making a text to binary translator and needed to make my x go up by increments of one. But when I do this it wont let me. Here is the part python does not like,
if beep == 1:
if x < length:
x + 1 = x

x + 1 = x is an invalid expression in python (invalid in almost all other programming languages).
x = x + 1 will be a valid increment.
You need to see first how Assignment Operator works.
Assigns values from right side operands to left side operand.

When updating variables, the variable by itself needs to be on the left of the assignment operator. So instead of x + 1 = x, use x = x + 1 or simply x += 1

you cant do operations in left hand side. so x + 1 = x is invalid in python.
You can do this by: x = x + 1 or x += 1

Related

Putting ':' after print does not return an error in python 3? [duplicate]

This question already has answers here:
What is this odd colon behavior doing?
(2 answers)
Closed 6 months ago.
The following loop does not return a syntax error, instead it runs forever. Why?
x = 1
while x <= 10:
print :x=x+1
If we properly format that code, we get:
x = 1
while x <= 10:
print: x = x + 1
So this is syntactically correct Python, but x is used as a type annotation (like x: int = 1).
Type annotations don't do anything on runtime but can be used by tools like mypy to help find bugs in your code.
So this code really boils down to:
while True:
print = 2

finding expression in python [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
I am beginner to python.I want to have a program which can go upto 20 and can show the expression only like +,- that can make number 10.
My expected output is:
20-10=10
8+2=10
6+4=10
I want to show them in list.
abc=[]
for x in range(1,20):
for y in range(1,20):
if x+y=10:
strValue=x+'+'+y
abc.append(strValue)
elif(x-y=10):
strValue=x+'-'+y
abc.append(strValue)
print(abc)
But,I get error
at line 10
abc.append(strValue)
^
IndentationError: unindent does not match any outer indentation level
abc=[]
for x in range(1,20):
for y in range(1,20):
if x+y==10:
strValue=str(x)+'+'+str(y)
abc.append(strValue)
elif(x-y==10):
strValue=str(x)+'-'+str(y)
abc.append(strValue)
print(abc)
This edited code is working for me. The Indentation Error you are getting is because abc.append(strValue) is not indented correctly. Your indentation must be consistent throughout the scope (within the if statement), usually 4 spaces.
There were two other errors in your code stemming from the same problem.
You cannot concatenate an integer to a string like you did in (x + '+' + y). You need to do (str(x) + '+' + str(y))
Also, in the if statements, you were using the wrong operator (= instead of the correct ==). = is the assignment operator used to set a value to a variable, whereas == compares two things.
Python is an Off-side rule language. It means that indentation is what will actually determine which part of the code belongs to the condition.
IndentationError means that you have problem with the indentation, and the interpreter should shows you the faulty line (or the line right after the faulty line, in this case).
Be sure to re-indent the line that starts with strValue.
Also:
Your conditions should use double-equal sign (==) to make a comparison, instead of one equal sign (=) which is usually used for assignment.
Cast integers to strings before concatenating them with other strings. You can use str to cast the integers explicitly, or fstrings to cast them implicitly (see code example below).
Code example (with some suggested improvements and stylefixes):
UPPER_CHECK_BOUND = 20
SOLUTION_TO_SEARCH_FOR = 10
valid_solutions = []
for x in range(1, UPPER_CHECK_BOUND):
for y in range(1, UPPER_CHECK_BOUND):
if x + y == SOLUTION_TO_SEARCH_FOR:
exercise = f'{x} + {y}'
valid_solutions.append(exercise)
elif x - y == SOLUTION_TO_SEARCH_FOR:
exercise = f'{x} - {y}'
valid_solutions.append(exercise)
print(valid_solutions)
The line after elif(x-y=10): is indented too far, which is why there is an Indentation Error on the next line; the indentation isn't consistent. Match the indentation of strValue=x+'-'+y to the line after it:
abc=[]
for x in range(1,20):
for y in range(1,20):
if x+y=10:
strValue=x+'+'+y
abc.append(strValue)
elif(x-y=10):
strValue=x+'-'+y
abc.append(strValue)
print(abc)
Couple of issues in your code.
Python cares about spaces before the code on each line. Your indentation needs
adjusting.
Your if statements are using the wrong operator. You're using the assignment operator = instead of the comparison operator ==
#!/usr/bin/python
# -*- coding: utf-8 -*-
abc = []
for x in range(1, 20):
for y in range(1, 20):
if x + y == 10:
strValue = x + '+' + y
abc.append(strValue)
elif x - y == 10:
strValue = x + '-' + y
abc.append(strValue)
print abc
For indentation, you can use an online tool like this one to get an idea of the correct format.
abc=[]
for x in range(1,20):
for y in range(1,20):
if x+y=10:
strValue=x+'+'+y
abc.append(strValue)
elif(x-y=10):
strValue=x+'-'+y # <= indent here is what cause error
abc.append(strValue)
print(abc)
Change it to
abc=[]
for x in range(1,20):
for y in range(1,20):
if x+y==10: #use == instead of =
strValue=x+'+'+y
abc.append(strValue)
elif x-y == 10: # error with using = (use for assignment)
strValue=x+'-'+y #two backspace solve problem
abc.append(strValue)
print(abc)

Addition binary numbers [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
I need a help of my code, i have make addition of passing two variable of two binary numbers and the answer is incorrect!
in my code
import data as s
s.num
s.demo
def add_binary_nums(x,y):
max_len = max(len(x), len(y))
x = x.zfill(max_len)
y = y.zfill(max_len)
result = ''
carry = 0
for i in range(max_len-1, -1, -1):
r = carry
r += 1 if x[i] == '1' else 0
r += 1 if y[i] == '1' else 0
result = ('1' if r % 2 == 1 else '0') + result
carry = 0 if r < 2 else 1
if carry !=0 : result = '1' + result
return result.zfill(max_len)
print("start here")
demoo = (add_binary_nums(s.num,s.demo))
print(demoo)
assume the values as num="011000100110111101100010" and demo="001" and the answer of above code is 011000100110111101100110 , and it's wrong answer! when i pass the value like
num="011000100110111101100010"
demo="001"
i got the the answer 01111011000010110011101010 .
and fpr passing the value like
print(add_binary_nums('001', '001'))
the result will be 01100010011011110110010 i'm getting 3 different results!!
Any suggestion!
space not effect, i remove the space and the answer is same wrong
I tried your script and found out you have an extra space on the right side of your value variable. If you remove it, it should work (returns 010). I would recommend to trim your input values before proceeding with the algorithm.
value = value.strip()
If you just interested in the result but not in implementation (May be you are trying to learn something new or it is an assignment), you can first convert the binary numbers to int and add them and again convert back to binary string.
See this code:
value = '001 '
demo = '001'
def add_binary_nums(x,y):
x_int = int(x, 2)
y_int = int(y, 2)
result = x_int + y_int
return '{0:08b}'.format(result)
print(add_binary_nums(value, demo))
Output:
00000010
To understand '{0:08b}'.format(result), visit this link.
EDIT:
thx, for sure i care about the implementation, its not assignemt or homework to convert numbers into binary, and the code above its peace of my program, im passing many variables have binary number i give u one example , when i pass variable from other python code, assume , n="011000100110111101100010" and m="0001", when i run the code , its shows wrong answer!, remember i'm pass variable and i got result 011000100110111101100110 !
Try the code below. I am getting the right results with python3.
value = '011000100110111101100010'
demo = '0001'
def add_binary_nums(x,y):
x=x.strip()
y=y.strip()
max_len = max(len(x), len(y))
print("Max: %d X: %s Y %s" %(max_len, x, y))
x = x.zfill(max_len)
y = y.zfill(max_len)
result = ''
carry = 0
print("X: %s Y: %s" % (x, y))
for i in range(max_len-1, -1, -1):
print(i)
r = carry
r += 1 if x[i] == '1' else 0
r += 1 if y[i] == '1' else 0
result = ('1' if r % 2 == 1 else '0') + result
carry = 0 if r < 2 else 1
if carry !=0 : result = '1' + result
return result.zfill(max_len)
demoo = (add_binary_nums(demo, value))
print(demoo)
The problem only exists with the trailing space. When running the code with trailing space it produces the output 0011, when running the code without the trailing space produces the output 010
The reason this occurs is due to the space and how you use zfill. If we look at the data when there is a trailing space on one of them.
if we assume x="001" and y='001 ' then max_len will be set as 4 since y has 4 chars in it. you then do zfill on x and zfill on y. this will pad x with an extra leading 0 to make it 4 chars. It will have no effect on y since its already 4 chars. So you will end up with
x="0001"
y="001 "
As you can see these are now not in the same representation. So when you start to do your calculations your first iteration on index 3 will be comparing the "1" from x and the space char from y. You code says if its not a 1 then its a 0. since space isnt a 1 then you default it to a 0.
So your essentially treating it like
x="0001"
y="0010"
and the result of that would indeed correctly be "0011"
So the issue is 100% with your space in the string. I would suggest either validate your input to the function to be sure it contains only 1s or 0s if it doesnt raise a ValueError. Or at a minimum call strip method of string to remove any leading or trailing spaces from the string.
Look at how you initialized your variables (empty space, quotes). Seems off to me for a binary representation...
value = '001 '
demo = "001"
Just use python binary literals: How do you express binary literals in Python?
Rewrite print(add_binary_nums(value, demo)) as print(bin(int(value, 2), int(demo, 2)))
running your code leaves me with the result 0011 not as you mentioned 001001. Leaving out the space in the first "value" variable leaves me with the result 010.
Hope this helps!
Edit: I also would suggest to just add the numbers in int-mode and then convert the int back to binary if you insist in having the space and the input as you have.

Is it valid to write some code that a bit tricky as long as I get same result (fibonacci in python) [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 6 years ago.
Improve this question
In Pycharm Edu I've encountered with this code:
def fib(n):
"""This is documentation string for function. It'll be available by fib.__doc__()
Return a list containing the Fibonacci series up to n."""
result = []
a = 1
b = 1
while a < n:
result.append(a)
tmp_var = b
b = a+b
a = tmp_var
return result
Since I am still learning I tried to do something similar with lists but the problem is to get a proper fibonacci series I used [-1,1] to start calculation, but results are same. Here is my code:
x = [-1,1]
y = []
for i in range(10):
c = x[0] + x[1]
y.append(c)
x[0] = x[1]
x[1] = c
print(y)
The question is, can I get away with this ?
This question might be too opinion-based for this site, but take into consideration that your code doesn't just need to run, it also needs to be readable. Otherwise, what you have written is entirely valid.
Consider this:
addends = [-1,1]
fibonacci_sequence = []
for value in range(10):
next_fibonacci = addends[0] + addends[1]
fibonacci_sequence.append(next_fibonacci)
addends[0] = addends[1]
addends[1] = next_fibonacci
print(fibonacci_sequence)
As I said, this may seem like opinion, but make sure you keep the beginning PEP 20 in mind:
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts...
As a final note, your code is not a function, but the original code snippet is a function. Here is your code as a function:
def fibonacci():
addends = [-1,1]
fibonacci_sequence = []
for value in range(10):
next_fibonacci = addends[0] + addends[1]
fibonacci_sequence.append(next_fibonacci)
addends[0] = addends[1]
addends[1] = next_fibonacci
return fibonacci_sequence
print(fibonacci())

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