This question already has an answer here:
Check if a number is a palindrome - fails for 11,22 etc
(1 answer)
Closed 10 months ago.
x = int(input())
if x<0 and (x%10 == 0 and x !=0):
print("false")
rev = 0
while x>0:
rev = rev*10 + x%10
x = x // 10
if rev == x:
print("true")
else:
print("false")
Since the reversed number is the same as entered one, the condition rev == x should return true but it's giving the opposite. What am I doing wrong?
Edit 1: converting to string is not allowed
Edit 2: 🤦 I see now.
Suggestion:
x = int(input())
You are reading x by input(), so a better idea to check if it's palindrome would be reversing it:
x = input()
if (x == x[::-1]):
...
To better understand [::-1] I would suggest you to read this.
Answer:
Your while loops modifies x, so it no longer has the original input value. It exits as 0
Somebody in the comments said this, which is your real problem.
while x>0:
rev = rev*10 + x%10
x = x // 10
To be clearer I would suggest you to read this part of your code, and to wonder what will be the value of x at the end of the while loop.
You are updating the 'x' value inside the while loop, irrespective of the input x equals 0 after the while loop.
Copy x value to some temp variable after the input() and compare that in the if condition.
x = 121
x1=x
if x<0 and (x%10 == 0 and x !=0):
print("false")
rev = 0
while x>0:
rev = rev*10 + x%10
x = x // 10
#print(x1,rev)
if rev == x1:
print("true")
else:
print("false")
Related
So I am learning python and there is something that bothers me. For the chunk of sample code below:
print("Test")
while True:
print("statement0")
x = input()
print(x)
if x == 1:
print("statement1")
y += input()
print(y)
elif x == 2:
print("statement2")
y += input()
print(y)
elif x == 3:
print("statement3")
y += input()
print(y)
elif x == 4:
print("statement4")
break
The if statements don't seem to be able to execute. After the value of x is printed it will loop back to statement0.
You have to first specify what will be the data type of the variable x.
Now as you are equating x to integers, you need to add int before the input() function.
Also, you have not initialized the variable y before, so python will throw an error. Define y beforehand with any integer value.
And try to keep the expressions inside parenthesis as it helps in easier understanding.
So, your final code becomes:
print("Test")
while True:
print("statement0")
x = int(input())
print(x)
y = 0 # initialize y with any value
if (x == 1): # edit
print("statement1")
y += int(input())
print(y)
elif (x == 2): # edit
print("statement2")
y += int(input())
print(y)
elif (x == 3): # edit
print("statement3")
y += int(input())
print(y)
elif (x == 4): # edit
print("statement4")
break
While taking the input, use x = int(input())
And, also y is not defined in this case, before doing something like y+=int(input()), you have to declare y above like y = 0
Thank you!
I'm trying to make a program that simply adds or subtracts 2 numbers. I have the code below:
x = int(input("Enter a number: "))
y = int(input("Enter a number: "))
print("Would you like to add or subtract?")
txt = input("Type 'a' for add or 's' for subtract")
if txt == "a" or "A":
x + y == z
if txt == "s" or "S":
x - y == z
else:
return
else:
return
print (z)
I know the return isn't right but not sure how I should work this out.
first of all when you write:
x + y == z
you are not defining a new z variable, but just making the logical operation "is x + y equal to z?" where z is not even defined. If you want to define z as the sum or difference of x and y you should use:
z = x + y or z = x - y
Also, when you want to make a structure of the kind "if condition is equal to something, else if condition is equal to something else" you can use if, else and elif (which is both else and if togheter), but you have to be sure that they have the same indentation.
The following code should do the job: (Edited)
x = int(input("Enter a number: "))
y = int(input("Enter a number: "))
print("Would you like to add or subtract?")
txt = input("Type 'a' for add or 's' for subtract")
if txt == "a" or txt=="A":
z = x + y
elif txt == "s" or txt=="S":
z = x - y
print (z)
Edit: you did not define a function, therefore you don't need to use "return". Return is used to give the result of a function, for example:
def sum(x, y):
z = x + y
return(z)
Edit #2: Thank you for making me note that txt == 'a' or 'A' would always be true, i've now repaired the code.
First: x + y == z is a test for equality. It checks if x + y and z are equal. To assign the result of x + y to z, you need to do z = x + y.
For such problems, it really helps to draw a flowchart or at least write out the steps you are going to implement in your code, especially when you're beginning programming. Here's an example. Pay attention to the indentation of my numbered list. This is similar to the indentation that you will expect to see in your Python code.
Take two numbers
input() returns a string, so convert to integers
Ask for the operator
input() to take a string.
If the operator is "a" or "A" (See note 1)
do addition
Instead, if the operator is "s" or "S"
do subtraction
If the operator is none of the above
do nothing? Show an error?
In the end, print the output
The code for the algorithm we discussed above would be:
x = int(input("Enter a number: ")) # 1.
y = int(input("Enter a number: ")) # 1.
print("Would you like to add or subtract?") # 2.
txt = input("Type 'a' for add or 's' for subtract")
if txt == "a" or txt == "A": # 3.
z = x + y
elif txt == "s" or txt == "S": # 4.
z = x - y
else: # 5.
z = 0
print("Invalid choice!")
print (z) # 6.
Your code goes wrong here:
If the operator is "a" or "A"
do addition
Now, if the operator is "s" or "S" (Can it be "s" or "S"? No, because we already established that it's "a" or "A" in 3. above )
do subtraction
Note 1: In human languages, we say
Check if txt is "a" or "A"
But Python works with booleans for the if condition. If we did if txt == "a" or "A", this would evaluate to if [[(txt == "a") is true] or ["A" is true]]. Because non-empty strings are truthy in Python, ["A" is true] would always be correct and so [[(txt == "a") is true] or ["A" is true]] would always be true, so we'd always go into the if statement. Not what we wanted to happen!
We have to compare each one separately like so:
if txt == "a" or txt == "A":
Alternatively, we can convert txt to lower or upper case and have a single check
if txt.lower() == "a":
Or,
if txt.upper() == "A":
Alternatively, we could check whether txt is one of the elements in a list.
if txt in ["a", "A"]:
You need to do z = x + y and z = x - y instead of x + y == z and x - y == z. Double equals to is a comparison operator.
The below code should work:
x = int(input("Enter a number: "))
y = int(input("Enter a number: "))
z = 0
print("Would you like to add or subtract?")
txt = input("Type 'a' for add or 's' for subtract")
if txt == "a" or "A":
z = x + y
elif txt == "s" or "S":
z = x - y
//you can use return if it's a function
return z;
print (z)
I'm a beginner programmer and chose python[3.8] as my choice to learn. I don't even know what to ask or how to search this site. My program counts 30 to 40 and prints 'Go' for multiples of 3 and strings of 3 and remainders of 3. It counts Go's. Output should be 10 but it's 3. It's not counting the strings. There is no error msgs.
`enter code here`
s = '3'
x = 40
y = 30
num = 0
while y < x :
y=y+1
if y % 3 == 0 or y % 10 == 3 or s in 'y' :
print('Go',y)
num = num + 1
print(num, 'Go\'s')
I think the problem here is to understand how python works.
When you write s in 'y' it will always return false because y here is a character that composes the string which value is ythe character.
So what you'll need to do is use the function str(param) to convert your integer to a string with the same value.
This is a code that works the way you want to.
s = '3'
x = 40
y = 30
num = 0
while y < x :
if y % 3 == 0 or y % 10 == 3 or s in str(y) :
print('Go',y)
num = num + 1
y=y+1
print(num, 'Go\'s')
https://www.urionlinejudge.com.br/judge/en/problems/view/1145
Write an program that reads two numbers X and Y (X < Y). After this, show a sequence of 1 to y, passing to the next line to each X numbers.
Input
The input contains two integer numbers X (1 < X < 20) and Y (X < Y < 100000).
Output
Each sequence must be printed in one line, with a blank space between each number.
My code is here:
x,y = raw_input().split(" ")
x = int(x)
xr = x
y = int(y)
lis = []
for i in range(1, y+1):
lis.append(i)
j = 0
for i in range(1, y+1):
while j <= x:
try:
if j < x:
print str(lis[j]),
j=j+1
else:
if x == y:
break
else:
print ""
x = xr + x
except IndexError:
break
Code's output is accurate. But the website is not accepting my code for some reason. Please help me find the bug?
Maybe the problem in on the line print str(lis[j]),, which add a space after the third digit and the site don't consider this valid, the problem say "with a blank space between each number." and maybe this is considered invalid.
Another possible solution is to split the list with the X numbers in lists of Y elements and print them with something like print " ".join(lis[Xs:Xf])
If you need just print you probably don't need list.
I don't know how to format code from phone.
sx,sy = raw_input().split(" ")
x = int(sx)
y = int(sy)
lines = int(y/x)+1
for line in range(lines):
offset = x*line
for i in range(x):
print i+offset,
if i+offset>=y:
print
break
print
Is there an equivalent of += for a string?
ie:
x = 1
while x <= 100:
y = x
if x % 3 == 0:
y = 'Fizz'
if x % 5 == 0:
y += 'Buzz'
if x % 7 == 0:
y += 'Foo'
if x % 11 == 0:
y += 'Bar'
print y
x += 1
raw_input('Press enter to exit...')
This should return a string and a second string if the same rules as with numbers applied. Is it possible to do this? Because just doing that returns TypeError: unsupported operand type(s) for +=: 'int' and 'str', even though y is a string to begin with, not an int.
If you do this:
You are concatenating a string to string:
x = 'a string'
x += '6'
print x
If you do this:
You concatenate int to string so you get error:
x = 'a string'
x += 6
print x
error:
TypeError: cannot concatenate 'str' and 'int' objects
You have to make sure variable type before doing '+' operation; based on variable type, python can add or concatenate
The following code works for me for Python 2.7.4 and Python 3.0:
a='aaa'
a+='bbb'
print(a)
aaabbb
That would be s1 += s2:
>>> s1 = "a string"
>>> s1 += " and a second string"
>>> s1
'a string and a second string'
>>>
Unlike Perl, Python mostly refuses to perform implicit conversions (the numeric types being the principal exception). To concatenate the string representation of an integer i to a string s, you would have to write
s += str(i)
I don't know, but maybe you are looking for operator
operator.iadd(a, b)¶
operator.__iadd__(a, b)
a = iadd(a, b) is equivalent to a += b.
http://docs.python.org/2/library/operator.html
x = 'a string'
x += ' and a second string'
print x
operator.iadd(x, ' and a third string')
print x
How can I concatenate a string and a number in Python?
I managed to fix it using isinstance()
x = 1
while x <= 100:
y = x
if x % 3 == 0:
y = 'Fizz'
if x % 5 == 0:
if isinstance(y, str):
y += 'Buzz'
else:
y = 'Buzz'
if x % 7 == 0:
if isinstance(y, str):
y += 'Foo'
else:
y = 'Foo'
if x % 11 == 0:
if isinstance(y, str):
y += 'Bar'
else:
y = 'Bar'
print y
x += 1
raw_input('Press enter to exit...')
Please tell me if this particularly bad code (which I have a habit of writing).
x = 1
while x <= 100:
y = str(x)
if x % 3 == 0:
y = 'Fizz'
if x % 5 == 0:
y += 'Buzz'
if x % 7 == 0:
y += 'Foo'
if x % 11 == 0:
y += 'Bar'
print y
x += 1
raw_input('Press enter to exit...')
It's quite simple.
You start off by defining X as an integer, then you increese it in a while loop.
At the very beginning of each iteration you define y = x which essentially tells python to set y into an integer.
Then depending on what x modulus <nr> you got, you add a string to the integer called y (yes, it is an integer as well).. This leads to an error because it's an illegal operation because of the way a INT and a WORD works, they're just different so you need to treat one of them prior to merging them into the same variable.
How to debug your own code: Try doing print(type(x), type(y)) and you get the differences of the two variables.. Might help you wrap your head around this.
The solution is y = str(x).
So, no.. Y is NOT a string to begin with
Because you redefine y each iteration of your while loop.
y = x <-- Makes Y a int, because that's what x is :)
Also, try using .format()
x = 1
while x <= 100:
y = x
if x % 3 == 0:
y = '{0}Fizz'.format(x)
if x % 5 == 0:
y += '{0}Buzz'.format(x)
if x % 7 == 0:
y += '{0}Foo'.format(x)
if x % 11 == 0:
y += '{0}Bar'.format(x)
print y
x += 1
raw_input('Press enter to exit...')
Another personal observation is that if x % 3 == 0 you replace y = ..., but in all other if-cases you append to y, why is this? I left it just the way you gave us the code but either do elif on the rest or why not concade on allif's