indentation errors in main function for connect four in python - python

A few minutes ago my program was fine until I tried adding in a way to make the user be asked to play again. When I put in the loop and indented everything, something got messed up really bad when I took out this part since it didn't work. Now I cant fix the indentation and nothing will work correctly. Can anyone see obvious problems?
def main():
lastRow = 0
won = 0
draw = False
player1turn = True
print("Welcome to Connect Four!")
rows = input("Please enter a number of rows: ")
check = True
while check == True:
try:
if int(rows) <= 4:
while int(rows) <= 4:
rows = input("Please enter a Valid choice: ")
else:
check = False
except ValueError:
rows = input("Please enter a Valid choice: ")
columns = input("Please enter a number of columns: ")
check2 = True
while check2 == True:
try:
if int(columns) <= 4:
while int(columns) <= 4:
columns = input("Please enter a Valid choice: ")
else:
check2 = False
except ValueError:
columns = input("Please enter a Valid choice: ")
myBoard = []
myBoardTemp = []
for i in range(int(columns)):
myBoardTemp.append(0)
for i in range(int(rows)):
myBoard.append([0] * int(columns))
printBoard(myBoard)
check3 = True
while won == 0 and draw == False:
move = input("Please enter a move: ")
while check3 == True:
try:
if int(move) < 0 or int(move) > len(myBoard[0]):
while int(move) < 0 or int(move) > len(myBoard[0]):
move = input("Please enter a valid choice: ")
else:
check3 = False
except ValueError:
move = input("Please enter a valid choice: ")
myBoard, player1turn, lastRow = move2(myBoard,int(move) - 1,player1turn)
printBoard(myBoard)
won = checkWin(myBoard,int(move) - 1, lastRow)
draw = isDraw(myBoard, won)
if won == 1:
print("Player 1 has won!")
elif won == -1:
print("Player 2 has won!")
elif draw == True:
print("It is a draw!")

The line after while check3 == True: is not indented correctly

The try after while check3 == True: isn't properly indented, although I can't tell if that is a transcription error or was in your original code.

Related

Find out how i can improve my Hangman coding on jupyter notebook

enter image description herei want to find out how
i can take in user’s inputs on the number of times user wishes to run/play, and execute accordingly. and also how can i provide user with an option on the game/run mode
allow the user to choose the complexity level of a game?
include a scoreboard that shows the top 5 players/scores.
[enter image description here](https://i.stack.enter image description hereimgur.com/CcJOM.png)
from IPython.display import clear_output
import random
NUMBER_OF_PICKS = 3
MINIMUM_SELECTION = 1
MAXIMUM_SELECTION = 36
#Input for the word by game master
user = input("Please enter your name:")
print("Hi " + user + " good luck ")
no_of_time = input("How many times do you want to play: ")
answer_word = list(str.lower(input("input enter your word: "))) #https://stackoverflow.com/questions/1228299/change-one-character-in-a-string
clear_output()
win = False
#defining function
def guesscheck(guess,answer,guess_no):
clear_output()
if len(guess)==1:
if guess in answer:
print("Correct, ",guess," is a right letter")
return True
else:
print("Incorrect, ",guess, " is a not a correct letter. That was your chance number ",guess_no)
return False
else:
print("Enter only one letter")
#Storing the number of characters in different variable
answer_display=[]
for each in answer_word:
answer_display += ["*"]
print(answer_display)
#initializing number of allowable guesses
guess_no = 1
while guess_no<5:
clear_output
#Player input for guess letter
guess_letter=str.lower(input('Enter your guess letter: '))
#Calling a sub function to check if correct letter was guessed
guess_check=guesscheck(guess_letter,answer_word,guess_no);
#Conditional: if incorrect letter
if guess_check == False:
guess_no +=1
print(answer_display)
#Conditional: if correct letter
elif guess_check == True:
num = [i for i, x in enumerate(answer_word) if x == guess_letter] #https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list
for all in num:
answer_display[all]=guess_letter
print(answer_display)
#Conditional: if no remaining unknown letter then win screen
if answer_display.count('*')==0:
win = True
break
if win:
print("You won!")
else:
print("The correct answer was: ", answer_word)
print("You lost!")
To install random_words package in jupyter notebook.
run this command in code shell.
!pip install random_word
import package. from random_word import RandomWords
generate.
r = RandomWords()
print(r.get_random_word())
Code snippet:
import random
from random_word import RandomWords
# Input for the word by game master
user = input("Please enter your name:")
print("Hi " + user + " good luck ")
while True:
try:
no_of_time = int(input("How many times do you want to play: "))
played_time = no_of_time
break
except ValueError:
print("Please enter a number. specify in number how many time you want to play.")
r=RandomWords()
scorecard = 0
# defining function
def guesscheck(guess, answer, guess_no):
if len(guess) == 1:
if guess in answer:
print("Correct, ", guess, " is a right letter")
return True
else:
print("Incorrect, ", guess, " is a not a correct letter. That was your chance number ", guess_no)
return False
else:
print("Enter only one letter")
while no_of_time:
while True:
try:
difficulty_level = int(input(
"Enter the difficulty you want to play: press [1] for easy, press [2] for medium, press [3] for hard, press [4] for manually word"))
if difficulty_level in [1, 2, 3, 4]:
break
else:
print("Enter number 1 or 2 or 3 or 4 not other than that!!")
continue
except ValueError:
print("Please enter difficulty level specific.")
answer_word = ""
if difficulty_level == 1:
while len(answer_word)!=5:
answer_word = r.get_random_word()
elif difficulty_level == 2:
while len(answer_word)!=6:
answer_word = r.get_random_word()
elif difficulty_level == 3:
while len(answer_word)!=10:
answer_word = r.get_random_word()
else:
answer_word=input("Enter manually what word you wanted to set..!")
win = False
# Storing the number of characters in different variable
answer_display = []
for each in answer_word:
answer_display += ["*"]
print(answer_display)
# initializing number of allowable guesses
guess_no = 1
while guess_no <= 5: # User chances given 5
# Player input for guess letter
guess_letter = str.lower(input('Enter your guess letter: '))
# Calling a sub function to check if correct letter was guessed
guess_check = guesscheck(guess_letter, answer_word, guess_no)
# Conditional: if incorrect letter
if guess_check == False:
guess_no += 1
print(answer_display)
# Conditional: if correct letter
elif guess_check == True:
num = [i for i, x in enumerate(answer_word) if
x == guess_letter] # https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list
for all in num:
answer_display[all] = guess_letter
print(answer_display)
# Conditional: if no remaining unknown letter then win screen
if answer_display.count('*') == 0:
win = True
break
if win:
print("You won!")
scorecard += 1
else:
print("The correct answer was: ", answer_word)
print("You lost!")
no_of_time -= 1
print("You played " + str(played_time) + ":")
print("Won: " + str(scorecard) + " Guessed correctly!!")
print("Lose: " + str(played_time - scorecard) + "not Guessed correctly!!")
don't know why specific length is not working in random_word hence included while statement.. this code snippet is working you can go through this..!

Stuck at WHILE LOOP when pressing N for escaping from the loop

# Feature to ask the user to type numbers and store them in lists
def asking_numbers_from_users():
active = True
while active:
user_list = []
message = input("\nPlease put number in the list: ")
try:
num = int(message)
user_list.append(message)
except ValueError:
print("Only number is accepted")
continue
# Asking the user if they wish to add more
message_1 = input("Do you want to add more? Y/N: ")
if message_1 == "Y" or "y":
continue
elif message_1 == "N" or "n":
# Length of list must be more or equal to 3
if len(user_list) < 3:
print("Insufficint numbers")
continue
# Escaping WHILE loop when the length of the list is more than 3
else:
active = False
else:
print("Unrecognised character")
print("Merging all the numbers into a list........./n")
print(user_list)
def swap_two_elements(user_list, loc1, loc2):
loc1 = input("Select the first element you want to move: ")
loc1 -= 1
loc2 = input("Select the location you want to fit in: ")
loc2 -= 1
loc1, loc2 = loc2, loc1
return user_list
# Releasing the features of the program
asking_numbers_from_users()
swap_two_elements
I would break this up into more manageable chunks. Each type of user input can be placed in its own method where retries on invalid text can be assessed.
Let's start with the yes-or-no input.
def ask_yes_no(prompt):
while True:
message = input(prompt)
if message in ("Y", "y"):
return True
if message in ("N", "n"):
return False
print("Invalid input, try again")
Note: In your original code you had if message_1 == "Y" or "y". This does not do what you think it does. See here.
Now lets do one for getting a number:
def ask_number(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Invalid input, try again")
Now we can use these method to create you logic in a much more simplified way
def asking_numbers_from_users():
user_list = []
while True:
number = ask_number("\nPlease put number in the list: ")
user_list.append(number)
if len(user_list) >= 3:
if not ask_yes_no("Do you want to add more? Y/N: ")
break
print("Merging all the numbers into a list........./n")
print(user_list)

am trying to make the while loop repeats again and again by the user after it finishes

I am new in python and I am trying to make a very basic and simple guessing game , I wanted the loop to be repeated again after it had finished.... when the user type yes in the command the loop should repeat again please help me .....in line (31):
import random
password =[1,2,3,4,5,6,7,8,9,10]
guess = ""
guess_limit = 3
guess_count=0
out_of_guess=False
you_lose = True
#body of the game
while guess != password and not(out_of_guess):
if guess_count < guess_limit:
guess = input(" enter a guess : ")
guess_count += 1
else:
out_of_guess=True
if out_of_guess:
you_lose=True
print("you LOSE :( ")
# PLAYING again
while True :
answer = input("do you want to play again ??\n yes or no ?? \n ")
yes_input= "yes"
no_input= "no"
if yes_input == answer:
random.shuffle(password)
#here i want to return from the beginning to start playing again
elif no_input == answer:
break
else:
print("********INVALID INPUT********")
You can wrap the whole program in one while True loop; then when you get to the play again section, you can just restart with continue:
import random
password = [1,2,3,4,5,6,7,8,9,10]
while True :
guess = ""
guess_limit = 3
guess_count=0
out_of_guess=False
you_lose = True
while guess != password and not(out_of_guess):
if guess_count < guess_limit:
guess = input(" enter a guess : ")
guess_count += 1
else:
out_of_guess=True
if out_of_guess:
you_lose=True
print("you LOSE :( ")
answer = input("do you want to play again ??\n yes or no ?? \n ")
yes_input= "yes"
no_input= "no"
if yes_input == answer:
random.shuffle(password)
continue
elif no_input == answer:
break
else:
print("********INVALID INPUT********")
But right now, it is impossible for the password to be guessed because the password is a list and input() is returning a str. You could make a str version of the password to check against, though:
import random
password = [1,2,3,4,5,6,7,8,9,10]
while True :
str_password = ''.join(str(i) for i in password)
#so correct input is "12345678910"
guess = ""
guess_limit = 3
guess_count=0
out_of_guess=False
you_lose = True
while guess != str_password and not(out_of_guess):
#and so on
Your code doesn't even work. You compare a string to a list. I think that you want to choose random element (number) from the list, and then check if the input is equal to that random.
I organized your code and make it look more clean.
import random
pass_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def game(guess: int) -> str:
guess_count = 0
while not guess_count <= 3:
if guess == random.choice(pass_list):
return 'You won!'
guess_count += 1
return 'You Lose'
while True:
guess = int(input('Enter a guess: '))
print(game(guess))
if input('Play again? ').lower() == 'yes':
game(guess)
else:
break
Instead of writing your code that way, you can use a function to organize your code and it will make it easier to understand.
import random
def password_guessing():
guess_count = 3
while True:
print("\nGuesses remaining: " + str(guess_count))
value = int(input("Enter a guess: "))
guess = random.choice(password)
if value == guess:
print("Correct guess!\n You won")
break
else:
guess_count -= 1
if guess_count >= 1:
pass
else:
print("You Lose :(\n")
ans = input("You want to play again?(y/n): ")
if ans == 'n':
break
# declaring it again since value in guess_count is 0 currently
guess_count = 3
password = [1,2,3,4,5,6,7,8,9,10]
print("Password Guessing game!")
answer = input("Enter 'yes' in order to play: ")
if answer == 'yes':
password_guessing()
print("*****GAME OVER*****")
else:
print("*****GAME OVER*****")

While loop not breaking?

I have written a main script that has a menu with 5 different options, the fifth option is if the user wants to quit the program. If the user types 5 in the main menu the program is supposed to quit, but it doesn't... It just keeps on looping through the menu. Can anyone help me resolve this issue??
menuItems = np.array(["Load new data", "Check for data errors", "Generate plots", "Display list of grades","Quit"])
userinput = input("Please enter name of the data file: ")
grades = dataLoad(userinput)
while True:
choice = displayMenu(menuItems)
while True:
if (choice == 1):
userinput = input("Please enter name of the data file: ")
grades = dataLoad(userinput)
break
elif (choice == 2):
checkErrors(grades)
break
elif choice == 3:
gradesPlot(grades)
elif choice == 4:
show = listOfgrades(grades)
showList(show)
elif (choice == 5):
break
else:
print("Invalid input, please try again")
break
You have nested loops, and break only breaks out of the inner loop.
To remedy this delete the nested loop and the break from the else block:
while True:
choice = displayMenu(menuItems)
if (choice == 1):
userinput = input("Please enter name of the data file: ")
grades = dataLoad(userinput)
break
elif (choice == 2):
checkErrors(grades)
break
elif choice == 3:
gradesPlot(grades)
elif choice == 4:
show = listOfgrades(grades)
showList(show)
elif (choice == 5):
break
else:
print("Invalid input, please try again")
In your code, when you call break, it breaks from the inner while loop and goes to the outer while loop which causes the whole thing to go on again. If for some cases you want both of the while loops to break then you can use some sort of a flag.
Example,
flag = False
while True:
while True:
if (1 == var):
flag = True
break
if flag:
break
//Your code
flag = False
while True:
choice = displayMenu(menuItems)
while True:
if (choice == 1):
userinput = input("Please enter name of the data file: ")
grades = dataLoad(userinput)
flag = True
break
elif (choice == 2):
checkErrors(grades)
flag = True
break
elif choice == 3:
gradesPlot(grades)
elif choice == 4:
show = listOfgrades(grades)
showList(show)
elif (choice == 5):
flag = True
break
else:
print("Invalid input, please try again")
flag = True
break
if True == flag:
break

How to sucsessfully ask the user to choose between two options

New programmer here
I'm trying to ask the user to choose between two options but I just can't get it right.
inp = int(input())
while inp != 1 or inp != 2:
print("You must type 1 or 2")
inp = int(input())
if inp == 1:
print("hi")
if inp == 2:
print("ok")
quit()
Even if I enter 1 or 2 when I ask initially it still spits back "You must must type 1 or 2"
My end goal is if they enter 1, to continue the program while if they choose 2 it will end the program. Thanks for any help.
inp = input("Choose 1 or 2 ")
if inp == "1":
print("You chose one")
# whatevercodeyouwant_1()
elif inp == "2":
print("You chose two")
# whatevercodeyouwant_2()
else:
print("You must choose between 1 or 2")
or if you want them to stay here until they choose 1 or 2:
def one_or_two():
inp = input("Choose 1 or 2")
if inp == "1":
print("You chose one")
# whatevercodeyouwant_1()
elif inp == "2":
print("You chose two")
# whatevercodeyouwant_2()
else:
print("You must choose between 1 or 2")
return one_or_two()
one_or_two()
This might not be the most elegant solution but it's a different approach than the "while" loop.
Just work with strings. If you need to turn the "inp" variable into an integer, don't wrap the int() function around input(), wrap the variable itself (i.e. int(inp) ). Also, change the ORs to ANDs:
inp = ""
while inp != "1" and inp != "2":
inp = input("Enter 1 or 2: ")
if inp != "1" and inp != "2":
print("You must type 1 or 2")
if inp == "1":
print("hi")
if inp == "2":
print("ok")
Try this
inp = ''
valid_inputs = [1,2,3,4]
output = {1: 'hi', 2:'hello', 3: 'Hey', 4: 'Bye'}
while inp not in valid_inputs:
inp = input("Enter 1 or 2 or 3 or 4: ")
if inp not in valid_inputs:
print("You must type 1 or 2 or 3 or 4")
print(output[inp])

Categories