if-else statement to increment or decrement inside for loop in python - python-3.x

I will take an input n and then print n number of lines.Every line i will input a string if this string is "++X" or "X++" then i will add 1 with 0(The initial value of X is 0). If my string is "--X" or "X--" then i will subtract 1 from 0.(If i already take another string then subtract from this string value).
Here is My code:
n = int(input())
c = 0
for x in range(n):
a = input()
if a == "X++" or "++X":
c = c + 1
elif a == "--X" or "X--":
c = c - 1
print(c)
My input:
2
X++
--X
My output:
2
Expected output:
0
Because,value will 1 for "X++" and 0 again for "--X". So,what is wrong in my code and how can i fix this?

Reference: https://docs.python.org/3/reference/expressions.html#operator-precedence
The order of precedence in the logic expression makes your expression equivalent to if (a == "X++") or "++X": which will always be True because bool("++X") == True. Any non-empty string will be True. So, as other answers suggest, you can use if a == "X++" or a == "++X": since or is evaluated last in the expression, the interp will evaluate the equality operations first, then apply or.
Another more shorthand way to test if a variable has a value that could be a few alternatives is to use the in operator.
n = int(input())
c = 0
for x in range(n):
a = input()
if a in ("X++", "++X"):
c = c + 1
elif a in ("--X", "X--"):
c = c - 1
print(c)
So you had a case where a non-empty string evaluated to True, there are other interesting cases that evaluate to either True or False in expressions. For instance, lists:
li1 = []
li2 = [1, 2]
if li1:
print("li1")
if li2:
print("li2")
Will output li2.
Bonus round - associating values with string input using a dict:
>>> def foo(n):
... d = {'X++': 1, '++X': 1, '--X': -1, 'X--': -1}
... c = 0
... for _ in range(n):
... a = input()
... c += d.get(a, 0)
... return c
...
>>> foo(3)
<-- X++
<-- ++X
<-- ++X
3

n = int(input())
c = 0
for x in range(n):
a = input()
if a == "X++" or a == "++X":
c = c + 1
elif a == "--X" or a == "X--":
c = c - 1
print(c)
:)

Change your condition from
if a == "X++" or "++X":
to
if a == "X++" or a == "++X":
or
if a in ("X++", "++X"):

You forgot to compare with a in every second operand of the ors. A non-empty string will evaluate to True.
n = int(input())
c = 0
for x in range(n):
a = input()
if a == "X++" or a == "++X":
c = c + 1
elif a == "--X" or a == "X--":
c = c - 1
print(c)

Related

Counting weighted average doesn't work properly sometimes

I've made a program that counts weighted average and required weighted value to average being equal to our preference. If I want the average be equal to 85 from (the first value in the list is the weight of next values) [[4,72,78],[3,56],[6,93]] and x value of 6 weight it does not output the right value.
def choice(x):
c = 0
Choice = True
choices = []
while Choice:
if choices == []:
if x != 0:
fill = "weight of required value"
else:
fill = "weight of next values"
else:
if x != 0:
fill = "value of wanted weighted average"
else:
fill = "value"
try:
c = input("Give {}\n" .format(fill))
except:
continue
if isinstance(c, str):
if c == "":
Choice = False
if choices == []:
choices = False
break
else:
try:
choices.append(float(c))
except:
continue
if x != 0 and len(choices) == x:
break
c = 0
return choices
def av(x):
c = 0
alist = x[:]
alist.pop(0)
for a in alist:
c += a*x[0]
return c
def average(k,args):
c = 0
n = 0
for y in range(len(args)):
for a in range(len(args)):
c += (av(args[a]))/2
for b in range(len(args)):
n += (args[b][0]*(len(args[b])-1))/2
if k == 1:
return ([float("{0:.2f}".format(c/n)),c,n])
else:
j = float("{0:.2f}".format(c/n))
print("Weighted average {} from {}" .format(j,args))
def rmark(q,args):
alist = average(1,args)
a = float("{:.2f}" .format((((q[1]*(alist[2]+q[0]))-alist[1])/q[0])))
print("To get weighted average {}, u have to add the value equal to {} of weight {}" .format(q[1],a,q[0]))
# return a
Continue = True
list_choices = []
while Continue:
x = 0
x = choice(0)
if isinstance(x, list):
list_choices.append(x)
elif x == False:
break
print(list_choices)
rmark(choice(2),list_choices)
average(0,list_choices)
Let me break it down for you.
av function is reducing the size of your lists (x1, x2 and x3) to 1 by popping (alist.pop(0)) one element.
Hence, value of len(x1)-1 is 0, which means value of all multipliers in the denominator of (av(x1) + av(x2) + av(x3))/((x1[0]*(len(x1)-1)) + (x2[0]*(len(x2)-1)) + (x3[0]*(len(x3)-1))) is 0. Thus, the error divide by zero.

If else method giving unexpected result

m = 5
if m == 1 or 4:
print("x")
else:
print("y")
I want this code to print y, not x.
4 evaluates to true, hence the result
m = 5
if m == 1 or m == 4:
print("x")
else:
print("y")
Fiddle
A number except for zero is an implicit True.
Read up on Operator precedence
What you've written actually translates to:
m = 5
if (m == 1) or True:
print("x")
else:
print("y")
Your if will always be True.
Try with:
if m == 1 or m == 4:
instead.

solve n which is an integer above 0 in python

This code works but it is not very efficient is there any help on a faster code in python to find n knowing that n is an integer above 0 and that n has no upper bound, how(x) will return you 1 if x>n, 0 if x = n, and -1 if x
def how(x):
if x > n:
return 1
elif x < n:
return -1
else:
return 0
def find(how):
if how(1) == 1:
return 1
x = 2
while how(x) != 1:
x = x**x
v = x
while how(x) != 0:
if how(x) == 1:
v = x
x = (x+1)//2
else:
x += (v-x+1)//2
return x
Rebecca, I've added some print statements so you can see where goes what wrong. As Patrick Artner said... its a bit confusing which way to go so I've tried to clean-up some things that enable you to continue exploring comparison of two variables against each other (and fake error catching (0).
Lets start and remove the confusing lingo and produce something workable code. With current below script it runs and with value = 1, reference = 1 you get the below print result in a continues loop until YOU stop the script manually:
v1 = n: error
loop1 1
def selector(v1, n):
if v1 > n:
print 'v1 > n', v1, n
return 1
elif v1 < n:
print 'v1 < n', v1, n
return -1
else:
print 'v1 == n: error'
return 0
def find(value, reference):
if selector(value, reference) == 1:
return 1
while selector(value, reference) != 1:
x = value**value
print 'loop1', x
v = x
while selector(value, reference) != 0:
print 'loop2'
if selector(value, reference) == 1:
v = value
x = (value+1)/2
print 'loop2-if', v, x
else:
x += (v-(value+1))/2
print 'loop2-else', x
print ' Almost done...'
return x
if __name__ == '__main__':
n = 1
print find(1, 1)
Happy exploring,....

How to command Python not to count True as 1?

count([5,2,1,'5',9,5,True],1) will show 2 as it treat Trueas 1.How do i change my main code so that when I want to check how many 1 is in the sequence,it will only return 1.
this is my main code
def count(L,x):
k = 0
for i in L:
if x == i :
k+= 1
return k
You can change x == i to x is i.
>>> x = True
>>> y = 1
>>> x == y
True
>>> x is y
False
Just add an isinstance to your check:
def count(L,x):
k = 0
for i in L:
if not isinstance(i, bool) and i == x:
k+= 1
return k
or, explicitly filter with i is not True. I.e if i is not True and i == x:

Invalid Syntax; nth prime number

def primetest(x):
if x < 2:
return False
if x == 2:
return True
if x % 2 == 0:
return False
for i in range(3,(x**0.5)+1):
if x % i == 0:
return False
return True
def nthprime(n):
primes = []
x = 2
while len(primes) < n:
if primetest(x) == True:
primes.append(x)
x = x + 1
return list(-1)
print nthprime(10001)
Whenever I try to run this it says that "print nthprime(10001)" is invalid syntax.
-prime test is to test wether a number is prime and nthprime creates a list of prime numbers a certain lengths and then return the last element of the list.
print is a function in Python 3, not a statement. You should change your last line of code to:
print(nthprime(10001))
In your code:
def nthprime(n):
primes = []
x = 2
while len(primes) < n:
if primetest(x) == True:
primes.append(x)
x = x + 1
return list(-1) // this is the error
I think you meant primes[-1], like this:
def nthprime(n):
primes = []
x = 2
while len(primes) < n:
if primetest(x) == True:
primes.append(x)
x = x + 1
return primes[-1] // this is now correct
You're also going to need to specify a range in integers, not float. So this:
for i in range(3,(x**0.5)+1):
Becomes this:
for i in range(3,int((x**0.5)+1)): // note the "int"

Resources