(Edit: Using python 2.7) I’m trying to get the user to input 10 numbers and the program needs to count and determine how many are negative, positive, or zeros.
However, everytime I run the program, it doesn’t give me the right number of negative or positive (or zero) numbers
i =[]
for i in range(10)
i = input('Enter Next Number: ')
n = 0
p = 0
z = 0
if (i > 0):
p = p+1
elif (i < 0):
n = n+1
elif (i == 0):
z = z+1
print "The number of negative numbers is",n
print "The number of positive numbers is",p
print "The number of zeros is",z
As Johnny Mopp suggested in his comment, you need to declare your counters outside of the loop. If you declare them inside, they are reset at every iteration and you are only counting the last number input by the user
n = 0
p = 0
z = 0
for i in range(10):
i = input('Enter Next Number:')
if (i > 0):
p = p+1
elif (i < 0):
n = n+1
else:
z = z+1
print "The number of negative numbers is",n
print "The number of positive numbers is",p
print "The number of zeros is",z
You will also want to convert the inputs to integers. If you really wish to add them to the list you will then need to iterate through the list after gathering all of the inputs. If retaining the values in a list is not needed #Bentaye answer will work just fine.
i =[]
n = 0
p = 0
z = 0
for num in range(10):
x = int(input('Enter Next Number: '))
i.append(x)
for y in range(len(i)):
if (i[y] > 0):
p = p+1
elif (i[y] < 0):
n = n+1
elif (i[y] == 0):
z = z+1
print ("The number of negative numbers is",n)
print ("The number of positive numbers is",p)
print ("The number of zeros is",z)
So I've got this code, it guesses a number between 0 and 100.
It prompts a number and the user answers with 'h' 'l' or 'c'
now everything works fine except that I want this line to only show when the user input is not equal to 'h', 'l' or 'c' instead now it shows up even if I enter 'c' which would break the loop, right?
print "Sorry, I did not understand your input."
full code
start = 0
end = 100
guess = int((start+end)/2.0)
print "Please think of a number between 0 and 100!"
print
x= 'n'
while x != 'c':
print 'Is your secret number ' + str(guess) + '?'
x = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.").lower()
if x == 'h':
end = guess
elif x == 'l':
start = guess
else:
print "Sorry, I did not understand your input."
guess = int((start + end)/2)
print 'your answer is: ' + str(guess)
So to clarify this is the output even when I enter 'c'
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.c
Sorry, I did not understand your input.
your answer is: 50
You do not have an elif for the 'c' case, so it falls to the final else.
Add, the following to handle that case and break the while loop:
elif x == 'c':
break
In addition, you can just do while True: and loop until c breaks.
Your higher/lower logic is backward as well. for h, start = guess, for example.
The update to guess should be indented inside the while loop.
I feel like I am constantly having this problem when I am writing a program, what I want to do is iterate over every value in my nested list and say that if it's not a zero, make it one.
Here is the error I am getting:
Traceback (most recent call last):
File "C:\Users\ryry3\Desktop\Python Projects\Games\Pygame Experiment\Sprint2.py", line 65, in <module>
resetBoard()
File "C:\Users\ryry3\Desktop\Python Projects\Games\Pygame Experiment\Sprint2.py", line 49, in resetBoard
if board[i][j] != 0:
IndexError: list index out of range
Here is my full code:
import random
grid = [100,100]
board = [[0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,1,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
[0,0,0,5,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0,0,0]]
playerX = None
playerY = None
randX = 0
randY = 0
def getRandomGridPos():
global randX, randY
randX = int(random.uniform(0, grid[0]))
randY = int(random.uniform(0, grid[1]))
def main():
pass
def printBoard():
print str(board[0]).replace(',', '')
print str(board[1]).replace(',', '')
print str(board[2]).replace(',', '')
print str(board[3]).replace(',', '')
print str(board[4]).replace(',', '')
print str(board[5]).replace(',', '')
print str(board[6]).replace(',', '')
print str(board[7]).replace(',', '')
print str(board[8]).replace(',', '')
print str(board[9]).replace(',', '')
def resetBoard():
i = 0
j = 0
while i < 10:
if board[i][j] != 0:
board[i][j] = 0
j += 1
print "Looping"
if j == 10:
j = 0
i += 1
print "J == 10"
if i == 10:
j = 0
i = 0
print "I == 10"
else:
j += 1
resetBoard()
Can someone help me find a solution and also help me not get this error anymore (explain why it happens)?
You've already gotten several pointers to the cause of your error, but I just wanted to point out a clearer pattern to iterate multi-dimensional arrays:
for x in range(0, 10):
for y in range(0, 10):
# you will now have all values for a 10x10 array in x & y
if board[x][y] != 0:
board[x][y] = 0
If you really just want to make sure all board fields (10 x 10) are zeros, the following is even more consice:
# zero out a 10 x 10 multi-dimensional array
board = [[0] * 10] * 10
Your for reset board doesn't work for the following reasons:
"if i == 10" ,i never actually reaches 10, since it is in a while loop which states "while i < 10". The loop would exit before i actually reaches 10
no nested while loop. You need two while loops to reset the board.
When j reaches 10 this line raises an index error: if board[i][j] != 0: , because j equals 10, and the maximum index you can take of a 10 element list is 9(since index starts at 0)
I recommend reading the following
http://introtopython.org/lists_tuples.html
I would add that one of the best ways to achieve what you want in python with loops is:
for row in board: # runs the following once for every item in board
for item in row: # runs the following for every item in row.
# A second for statement is required because
# multidimensional lists are lists of lists.
if(item != 0)
item = 0 #sets items to 0 if the item isn't equal to 0
UPDATE:
Sorry but I also encoutered another problem, my bad for not checking the code:
The final code should be:
while i < 10:
if j == 10:
j = 0
i += 1
print ("J == 10")
elif board[i][j] != 0:
board[i][j] = 0
j += 1
print ("Looping")
else:
j += 1
The problem I missed was that you should have checked the j boundary before trying to access the array, only then you should start the loop again.
The problem is in this part:
if j == 10:
j = 0
i += 1
print "J == 10"
if i == 10:
j = 0
i = 0
if i = 9, j= 10 then we enter into the first if which changes i,j to be 10,10
Then the code continues and we enter the second if, thus reseting i and j making the loop go again and again...
Solve it by deleting the second if part, since the while condition will make sure we will never go to that case in the first place.
I am fairly new to Python and am trying to create my own small program. Im having trouble with the replace function. I want to replace every even position in a string with its position number, and a problem occurs when the position becomes greater than 10; it just keeps replacing every character after 10 with an even number. Here is my code
def replaceEvenUntil(st,n):
for i in range(len(st)):
if i % 2 == float(0):
st = st.replace(st[i], str(i), n)
return st
>>> replaceEvenUntil("abcdefghijklmnop", 100)
'0b2d4f6h8j101214161820'
Where in my code have I made my error?
A few things:
float and str are functions in Python. You don't need to write int(0) or str('foo').
str.replace('a', 'b') replaces all occurrences of a with b. You don't really want that.
You're re-assigning st in the loop, but the size of st may change (10 is two characters), so you'll get off-by-one errors as the strings grow larger than 10 characters long.
I would construct a temporary string instead:
def replaceEvenUntil(s, n):
result = ''
for i in range(min(n, len(s))):
if i % 2 == 0:
result += str(i)
else:
result += s[i]
return result
Or with enumerate():
def replaceEvenUntil(s, n):
result = ''
for i, c in enumerate(s):
if i <= n and i % 2 == 0:
result += str(i)
else:
result += s[i]
return result
for (int i = 0; i < s.length(); i++)
{
if (isdigit(s[i]))
counts[s[i] - '0'] ++;
}
what does this code means, any one can able to explain this code " counts[s[i] - '0'] ++;" exact opertion
counts is a ten-element array, which is being used to count how many times each digit appears in s.
Specifically:
s[i] - '0' turns '0' into 0, '1' into 1 etc.
counts[...]++ increments the corresponding element of the array.
Hope this helps.
1) Ascii value of '0' is 48
2) Whenever s[i] is a digit (between 0-9 inclusive)
3) s[i] - '0' evaluates to an index (between 0..9 inclusive);
Example:
Ascii value of '1' is 49
Say s[i] is '1'
then s[i] - '0' is 49-48 = 1
4) counts[s[i]-'0']++ would count the number of times a particular digit has been found in s[i].
The code is counting how many times a digit (1-9) is appearing in string s.
Note. 'i' - '0' is the same as i - 0 if i is a digit.
The reason is that characters '0' -'9' have consecutive ASCII values. So the difference in ASCII value between 'i' and '0' is i;
Now let's say
string s = "1b21cc55";
and
int count[10] is all zeros
in the loop
we check s[i],
s[0] = 1 ---> isdigit(1) = yes ----> count[1-0] += 1 ---> count[1] is 1;
s[1] = b ---> isdigit(b) = no ;
s[2] = 2 ---> isdigit(2) = yes ----> count[2-0] += 1; ---> count[2] is 1;
s[3] = 1 ---> isdigit(1) = yes ----> count[1-0] += 1; ---> count[1] is 2;
and so on ...
At the end count[i] will tell you how many is are in the string.
counts is an array.
s[i] is a character which contains numbers in ASCII. '0', '1',
'2', ...
s[i] - '0' converts them into integer numbers. 1, 2, 3, ...
Above number indicates the index of n'th item in the array --> X
counts[X] ++ increments one the X'th item of the array.