check for variable in 2d list in python - python

I'm trying to get the user to input a number from 1 to 9. The code is supposed to check if the number is in the list "board" or already taken. If it's not taken the number is turned into "O". If the number is not in the list or already taken the loop is supposed to re-ask the user for input. However, even if the number is in the list and not taken, the function asks the user for input twice. If I move the else statement on line with the if statement, I get an infinite loop asking for input.
Here's the code:
# ask the unser to make a move
def userMove():
move = int(input("Please make your move: "))
check = True
# check if move is already taken
while check:
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == move:
board[i][j] = "O"
check = False
else:
print("This field is either already taken or not on the board")
move = int(input("Please choose another move: "))

You can use any() to check if value is in 2D list:
if any(move in sublist for sublist in board):

Your problem is caused by the else clause being executed always. The posted code can be fixed as follows.
With for/else statements, the else clause executes after the loop completes normally.
A break statement can be used to prevent normal completion.
Revised Code
# ask the unser to make a move
def userMove():
move = int(input("Please make your move: "))
check = True
# check if move is already taken
while check:
for i in range(len(board)):
for j in range(len(board[i])):
if board[i][j] == move:
board[i][j] = "O"
check = False
break
if not check:
break
else:
# only executes if break not encountered in for i loop
print("This field is either already taken or not on the board")
move = int(input("Please choose another move: "))

Related

How do you keep a list looping, whilst removing a number the user inputs each time? (Python + Jupyter Notebook)

Made a list where I want the user to insert x followed by a number. once they have inputted, say x1, I would like x1 to be removed from the list as they are asked to input another number starting with x.
I want the list to be on loop as well, only stopping until one of the groups (of three number) has been chosen.
Disclaimer - I am a beginner at Python + Jupyter Notebook
allwins = (('x1','x2','x3'),
('x4','x5','x6'),
('x7','x8','x9'),
('x1','x4','x7'),
('x2','x5','x8'),
('x3','x6','x9'),
('x1','x5','x9'),
('x7','x5','x3'))
in_item = input("Please enter x followed by a number 1-9: ")
if in_item in allsolutions:
input("Good choice. Now pick another number starting with x: ")
else in_item not in allsolutions:
input("That did not work. Try again: ")
Idk how to keep loop for atleast a few times until the user inputs 3 diff numbers that makes a group.
You can't remove something from a tuple, so you need to make the inner tuples lists.
Then you need to loop over the main tuple, removing the input from each of them if it exists. After you do this you can check if the list is empty.
allwins = (
['x1','x2','x3'],
['x4','x5','x6'],
['x7','x8','x9'],
['x1','x4','x7'],
['x2','x5','x8'],
['x3','x6','x9'],
['x1','x5','x9'],
['x7','x5','x3'])
while True:
in_item = input("Please enter x followed by a number 1-9: ")
item_found = False
solution_found = False
for sublist in allwins:
if in_item in sublist:
sublist.remove(in_item)
item_found = True
if sublist == []:
solution_found = True
if solution_found:
print("You found all of them, congratulations!")
break
elif item_found:
print("Good choice, now pick another")
else:
print("That did not work, now try again")

Never Ending Validation Check in Python

Working on a battleship game in python. My function to check the user's 'guess' input in resulting in an endless validation loop. I want a guess in the format of 'a10' on a 10x10 grid. The validation function i have built to help validate is as follows:
def validate_guess(self,guess):
while True:
if (len(guess)) in range(2, 4):
if guess[0] not in 'abcdefghij' or guess[1:] not in '1,2,3,4,5,6,7,8,9,10':
print("Sorry the Grid is a 10x10 square you must enter a valid position. Try again...")
continue
else:
return guess
else:
if len(guess) < 2 or len(guess) > 3:
print("Oops! That's too not the right amount of characters. Please try again...")
continue
If the user guesses an incorrect value--it does spot it--but the error is returning a never ending loop with the printed error statement.
This is the portion of my game where the validation function is being used:
while True:
print("\n")
# get guess from player one in coordinate form (example: a10)
guess = input("{}'s turn to guess: ".format(player1.player))
# strip characters from the guess input
guess = guess.strip()
# validate the guess
guess = self.validate_guess(guess)
# append the guess to a list for player 1
player1.guesses.append(guess)
# break down the coordinates into x and y variables
x, y = ship1.split_guess(guess)
# increment guesses
guesses += 1
# loop to assess whether, hit, miss or a won game
if any(guess in ship for ship in grid2.play_two_board):
print("HIT")
grid2.print_guess_board(x, y, "h")
for ship in grid2.play_two_board:
try:
ship.remove(guess)
print(len(Board.play_two_board))
self.check_if_sunk(ship)
win = self.play_one_win_check(player1.player)
if win == 1:
print ("GAVE OVER!")
break
except ValueError:
pass
else:
print("Miss!")
grid2.print_guess_board(x, y, "m")
Not sure if it might be because i have two While statements? Just really stuck here would appreciate any guidance. Thanks.
*****************************8
edit --changed function to include the guess without actually passing it that value from the input statement but still getting same problem.
def validate_guess(self):
guess = input("Please enter a location:")
while True:
if len(guess) in range(2, 4):
if guess[0] not in 'abcdefghij' or guess[1:] not in '1,2,3,4,5,6,7,8,9,10':
print("Sorry the Grid is a 10x10 square you must enter a valid position. Try again...")
continue
else:
return guess
else:
if len(guess) < 2 or len(guess) > 3:
print("Oops! That's too not the right amount of characters. Please try again...")
continue
and just calling it like this:
while True:
print("\n")
# get guess from player one in coordinate form (example: a10)
# guess = input("{}'s turn to guess: ".format(player1.player))
# strip characters from the guess input
# guess = guess.strip()
# validate the guess
guess = self.validate_guess()
Within validate_guess, when the user enters a bad value, you have to get new input before you check again. See here.
Either return an error code (True/False ?) from your function, or have the function loop until the input is valid. Just add a command for new input at the bottom of the function's while loop.

Write a simple looping program

I want to write a program with this logic.
A value is presented of the user.
Commence a loop
Wait for user input
If the user enters the displayed value less 13 then
Display the value entered by the user and go to top of loop.
Otherwise exit the loop
You just need two while loops. One that keeps the main program going forever, and another that breaks and resets the value of a once an answer is wrong.
while True:
a = 2363
not_wrong = True
while not_wrong:
their_response = int(raw_input("What is the value of {} - 13?".format(a)))
if their_response == (a - 13):
a = a -13
else:
not_wrong = False
Although you're supposed to show your attempt at coding towards a solution and posting when you encounter a problem, you could do something like the following:
a = 2363
b = 13
while True:
try:
c = int(input('Subtract {0} from {1}: '.format(b, a))
except ValueError:
print('Please enter an integer.')
continue
if a-b == c:
a = a-b
else:
print('Incorrect. Restarting...')
a = 2363
# break
(use raw_input instead of input if you're using Python2)
This creates an infinite loop that will try to convert the input into an integer (or print a statement pleading for the correct input type), and then use logic to check if a-b == c. If so, we set the value of a to this new value a-b. Otherwise, we restart the loop. You can uncomment the break command if you don't want an infinite loop.
Your logic is correct, might want to look into while loop, and input. While loops keeps going until a condition is met:
while (condition):
# will keep doing something here until condition is met
Example of while loop:
x = 10
while x >= 0:
x -= 1
print(x)
This will print x until it hits 0 so the output would be 9 8 7 6 5 4 3 2 1 0 in new lines on console.
input allows the user to enter stuff from console:
x = input("Enter your answer: ")
This will prompt the user to "Enter your answer: " and store what ever value user enter into the variable x. (Variable meaning like a container or a box)
Put it all together and you get something like:
a = 2363 #change to what you want to start with
b = 13 #change to minus from a
while a-b > 0: #keeps going until if a-b is a negative number
print("%d - %d = ?" %(a, b)) #asks the question
user_input = int(input("Enter your answer: ")) #gets a user input and change it from string type to int type so we can compare it
if (a-b) == user_input: #compares the answer to our answer
print("Correct answer!")
a -= b #changes a to be new value
else:
print("Wrong answer")
print("All done!")
Now this program stops at a = 7 because I don't know if you wanted to keep going with negative number. If you do just edited the condition of the while loop. I'm sure you can manage that.

I need to figure out how to make my program repeat. (Python coding class)

I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.
import random
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
maximum = 10 ** x;
maximum += 1
firstnum = random.randrange(1,maximum) # return an int from 1 to 100
secondnum = random.randrange(1, maximum)
compsum = firstnum + secondnum # adds the 2 random numbers together
# print (compsum) # print for troubleshooting
print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user
added = int(input("Your answer is: ")) # gets user input
if added == compsum: # compares user input to real answer
print("You are correct!!!")
else:
print ("Sorry, you are incorrect")
You'll want to do something like this:
def foo():
print("Doing good work...")
while True:
foo()
if input("Want to do more good work? [y/n] ").strip().lower() == 'n':
break
I've seen this construct (i.e., using a break) used more often than using a sentinel in Python, but either will work. The sentinel version looks like this:
do_good_work = True
while do_good_work:
foo()
do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n'
You'll want to do more error checking than me in your code, too.
Asking users for input is straightforward, you just need to use the python built-in input() function. You then compare the stored answer to some possible outcomes. In your case this would work fine:
print('Would you like to test your adding or subtracting skills?')
user_choice = input('Answer A for adding or S for subtracting: ')
if user_choice.upper() == 'A':
# ask adding question
elif user_choice.upper() == 'S':
# ask substracting question
else:
print('Sorry I did not understand your choice')
For repeating the code While loops are your choice, they will repeatedly execute a statement in them while the starting condition is true.
while True: # Condition is always satisfied code will run forever
# put your program logic here
if input('Would you like another test? [Y/N]').upper() == 'N':
break # Break statement exits the loop
The result of using input() function is always a string. We use a .upper() method on it which converts it to UPPERCASE. If you write it like this, it doesn't matter whether someone will answer N or n the loop will still terminate.
If you want the possibility to have another question asked use a while loop and ask the user for an input. If you want the user to input whether (s)he want an addition or substraction you already used the tools to ask for such an input. Just ask the user for a string.

Python: How do I get my function to repeat until asked to cancel?

I just started learning Python. Basically I just want to repeat the loop once if answer is yes, or break out of the loop if answer is no. The return True/False doesn't go back to the while loop?
def userinfo():
while true:
first_name=input("Enter your name here:")
last_name=input("Enter your last name:")
phonenum=input("Enter your phone number here")
inputagain=rawinput("Wanna go again")
if inputagain == 'no':
return False
userinfo()
Instead of while true: use a variable instead.
Such as
while inputagain != 'no':
Instead of looping forever and terminating explicitly, you could have an actual condition in the loop. First assume that the user wants to go again by starting again as 'yes'
again = 'yes'
while again != 'no':
# ... request info ...
again = input("Wanna go again?: ")
though this while condition is a bit weak, if the user enters N, n, no or ever no with space around it, it will fail. Instead you could check if the first letter is an n after lowercasing the string
while not again.lower().startswith('n'):
You could stick to your original style and make sure the user always enters a yes-like or no-like answer with some extra logic at the end of your loop
while True:
# ... request info ...
while True:
again = input("Wanna go again?: ").lower()
if again.startswith('n'):
return # exit the whole function
elif again.startswith('y'):
break # exit just this inner loop

Categories