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)
Related
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
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
String concatenation happens to be on the right side, example:
foo = 'Sorting1234'
foo += 'er'
print(foo)
Sorting1234er
But in a loop this happens:
string = 'Sorting1234'
x = ''
for c in string:
if c.islower():
x+=c
if c.isupper():
x+=c
print(x)
Sorting
I would expect the output to be:
ortingS
Since I am 'appending' the lowercase first in the loop and 'appending' the uppercase later.
At the moment, you are processing the letters in the order of the original string, rather than by case. This means that your current for loop has little effect but to prevent the printing of numeric values.
One way to achieve the behaviour you're looking for, with the lower case characters appended first, would be to use two loops: the first looking for lower case characters and the second looking for upper case characters, i.e.:
string = 'Sorting1234'
x = ''
for c in string:
if c.islower():
x += c
for c in string:
if c.isupper():
x += c
print(x)
Output:
ortingS
An alternative way, requiring one pass over the string, could be to store lists of the lower and upper case characters, then join them at the end:
lower, upper = [], []
for c in string:
if c.islower():
lower.append(c)
elif c.isupper():
upper.append(c)
print(''.join(lower + upper))
Output:
ortingS
string = 'Sorting1234'
x = ''
for c in string:
if c.islower():
x+=c
if c.isupper():
x+=c
print(x)
print(x)
x=''
#x += c -> x = x + x -> appends c to the right of x, which it's doing it correctly
When printing the output you can see:
S
So
Sor
Sort
Sorti
Sortin
Sorting
You can see you are simply looping through the string and appending each letter, the if statements are practically useless in your case.
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.
I was trying to create a reverse rail-fence cipher, when I stumbled upon an error!
Here is my code:
n=len(cipher)
strings=[]
for r in range(3,4):
lis=[[0 for i in range(n)] for i in range(r)]
x,y=0,0
for c in cipher:
try:
lis[x][y]=c
except:
for i in lis:
print(i)
print(x,y)
break
y+=2*r-3
print(y)
if y>=n:
y-=n
x+=1
print(x,y)
x,y,z=0,0,1
s=""
for i in range(n):
try:
if(lis[x][y]==0):
print(r,n)
s+=lis[x][y]
except:
for i in lis:
print(i)
print(x,y,c)
break
y+=1
if x==0:
z=1
elif x==r-1:
z=0
if z==1:
x+=1
else:
x-=1
strings.append(s)
return strings
I added in several try/except statements to determine the error. Later though, I found that if I changed a single line, line 4, to read as
lis=[['.' for i in range(n)] for i in range(r)]
The code worked flawlessly (as in didn't create any errors - it still didn't produce the right result)!
The only differences between the codes is this single line. I am using Python 37 on Windows 10.
Why does the one code work where the other doesn't?
EDIT: My input cipher is "Js s!ae saeoemiwm", which was encoded using three "rails" in a rail-fence cipher.
EDIT 2: I have a working version to reverse this cipher, but the point of this question is why does changing the 0's to '.' make a difference in any way?
The reason is this line:
s+=lis[x][y]
s is a string, so you can only concatenate other strings to it. If lis[x][y] contains 0, that's a number, not a string, so you can't concatenate it.
If you change it to:
s += str(lis[x][y])
then it will work with either initial value.
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