I am trying to prevent the user from inputting a square that is already marked, but the for loop moves on to the next player's input without decrementing the value of i by one, so the player 1 can repeat his input. How do I fix this?
arr = [[0,0,0],[0,0,0],[0,0,0]]
grid = grid(arr)
grid.print_grid()
for i in range(9):
row = int(input("Enter the row name: "))
col = int(input("Enter the column name: "))
if(arr[row][col] == 0):
if(i%2):
arr[row][col] = 1
else:
arr[row][col] = 2
else:
print("\nThat square has already been marked! Please select another square")
i = i-1
continue
grid.print_grid()
res = grid.grid_checker()
if (res == 1):
print("\nPlayer 1 wins the game!")
break
elif(res == 2):
print("\nPlayer 2 wins the game!")
break
elif(i == 8):
print("\nThe game has ended in a draw!")
You need to store another variable to keep track of whose turn it is. You cannot modify the variable you are looping on while you are in the loop body. This means that i cannot be manipulated while you are running in the loop. Here's how I would change it.
turn = 0
while True:
row = int(input("Enter the row name: "))
col = int(input("Enter the column name: "))
if(arr[row][col] == 0):
if(i%2):
arr[row][col] = 1
turn = turn + 1
else:
arr[row][col] = 2
turn = turn + 1
else:
print("\nThat square has already been marked! Please select another square")
continue
grid.print_grid()
res = grid.grid_checker()
if (res == 1):
print("\nPlayer 1 wins the game!")
break
elif(res == 2):
print("\nPlayer 2 wins the game!")
break
elif(turn == 8):
print("\nThe game has ended in a draw!")
Here we're saving the turn number in the variable turn and only incrementing the variable when we can confirm a player has successfully completed their turn.
Why you cannot modify i: For optimisations, loops are often expanded by python before they are converted to assembly instructions. For example a simple loop like this:
for i in range(9):
print(i)
May be expanded to something like this:
i = 0
print(i)
i = 1
print(i)
# and so on, upto
i = 9
print(i)
This is done to avoid having to jump around in memory. So as you can see here, i is reassigned for every iteration of the loop. Therefore, even if you change the value of i in the body of the loop, it will simply be reassigned before the next iteration.
Related
It has been a week since I started to self-study python and I tried making a program that adds or multiplies all natural numbers and the problem is I want to only show the final result of all the sum or product of all natural numbers. How do I do it?
repeat = 'y'
a=0
while repeat.lower() == 'y':
result = 0
choice = 0
i=0
product = 1
num = int(input("Enter the value of n: "))
if num < 1 or num > 100 :
print('must be from 1-100 only')
repeat = input("\nDo you want to try again?Y/N\n>>> ")
continue
print('1. Sum of all natural numbers')
print('2. Product of all numbers')
choice = int(input("Enter choice: "))
if choice == 1:
while(num > 0):
result += num
num -= 1
print(' ',result)
if choice ==2:
while i<num:
i=i+1
product=product*i
print(' ', product)
repeat = input("\nDo you want to try again Y/N? \n>>> ")
while repeat.lower() == 'n':
print('\nthank you')
break
The program prints you all the numbers because the print statement is in a while loop, so it gets executed with each run of the loop. Just move the print function out of the while.
if choice == 1:
while(num > 0):
result += num
num -= 1
print(' ',result)
if choice ==2:
while i<num:
i=i+1
product=product*i
print(' ', product)
You have two problems. First, your print statements that print the results need to be un-indented by one step, so they are not PART of loop, but execute AFTER the loop. Second, you need to initialize product = 1 after the if choice == 2:. As a side note, you don't need that final while loop. After you have exited the loop, just print('Thanks') and leave it at that.
So the end of the code is:
if choice == 1:
while num > 0 :
result += num
num -= 1
print(' ',result)
if choice == 2:
product = 1
while i<num:
i=i+1
product=product*i
print(' ', product)
repeat = input("\nDo you want to try again Y/N? \n>>> ")
print('thank you\n')
I presume you'll learn pretty quickly how to do those with a for loop instead of a while loop.
Basically, I'm trying to build a code to get the largest number from the user's inputs. This is my 1st time using a for loop and I'm pretty new to python. This is my code:
session_live = True
numbers = []
a = 0
def largest_num(arr, n):
#Create a variable to hold the max number
max = arr[0]
#Using for loop for 1st time to check for largest number
for i in range(1, n):
if arr[i] > max:
max = arr[i]
#Returning max's value using return
return max
while session_live:
print("Tell us a number")
num = int(input())
numbers.insert(a, num)
a += 1
print("Continue? (Y/N)")
confirm = input()
if confirm == "Y":
pass
elif confirm == "N":
session_live = False
#Now I'm running the function
arr = numbers
n = len(arr)
ans = largest_num(arr, n)
print("Largest number is", ans)
else:
print(":/")
session_live = False
When I try running my code this is what happens:
Tell us a number
9
Continue? (Y/N)
Y
Tell us a number
8
Continue? (Y/N)
Y
Tell us a number
10
Continue? (Y/N)
N
Largest number is 9
Any fixes?
The error in your largest_num function is that it returns in the first iteration -- hence it will only return the larger of the first two numbers.
Using the builtin max() function makes life quite a bit easier; any time you reimplement a function that already exists, you're creating work for yourself and (as you've just discovered) it's another place for bugs to creep into your program.
Here's the same program using max() instead of largest_num(), and removing a few unnecessary variables:
numbers = []
while True:
print("Tell us a number")
numbers.append(int(input()))
print("Continue? (Y/N)")
confirm = input()
if confirm == "Y":
continue
if confirm == "N":
print(f"Largest number is {max(numbers)}")
else:
print(":/")
break
So, first things first,
the use of max can be avoided, as it is a reserved keyword in python
And coming to your fix, you are comparing it with the value only once in the loop, and you are returning the number, the indentation is the key here. You will have to wait for the loop to complete its job then return the value.
There are many inbuilt methods to do the job, Here is your implementation (a bit modified)
session_live = True
numbers = []
a = 0
def largest_num(arr, n):
#Create a variable to hold the max number
max_number = arr[0]
#Using for loop for 1st time to check for largest number
for i in range(1, n):
if arr[i] > max_number:
max_number = arr[i]
# --- The indentation matters
#Returning max's value using return
return max_number
while session_live:
print("Tell us a number")
num = int(input())
numbers.insert(a, num)
a += 1
print("Continue? (Y/N)")
confirm = input()
if confirm == "Y":
pass
elif confirm == "N":
session_live = False
#Now I'm running the function
arr = numbers
n = len(arr)
ans = largest_num(arr, n)
print("Largest number is", ans)
else:
print(":/")
session_live = False
I made it without using the built-in function 'max'.
It is a way to update the 'maxNum' variable with the largest number by comparing through the for statement.
numbers = []
while True:
print("Tell us a number")
numbers.append(int(input()))
print("Continue? (Y/N)")
confirm = input()
if confirm == "Y":
continue
if confirm == "N":
maxNum = numbers[0]
for i in numbers:
if i > maxNum:
maxNum = i
print("Largest number is", maxNum)
else:
print(":/")
break
*Q.Randomly generate a 4-digit number. Ask the user to guess a 4-digit number. For every digit that the user guessed correctly in the correct place, they have a “cow”. For every digit the user guessed the number in the wrong place is a “bull.”
Every time the user makes a guess, tell them how many “cows” and “bulls” they have. Once the user guesses the correct number, the game is over. Keep track of the number of guesses the user makes throughout the game and tell the user at the end.*
**Now, the problem is that I've made the program but it could generate any 4 - digit number, and that's when the problem arises. For example:
The generated number is 3568.
The user types: 3266
Then user gets 2 Cows And 2 Bulls.
But the user has no way of knowing which are the correct numbers in the number that he typed.
I want a function that can tell the user the numbers that he guessed right.
In the example, the program should tell the user that 3 and 6 are correct in the following places.**
import random
def compare_number(number, user_guess):
cowbull = [0, 0]
for i in range(len(number)):
if number[i] == user_guess[I]:
cowbull[1] += 1
else:
cowbull[0] += 1
return cowbull
if __name__ == "__main__":
playing = True
number = str(random.randint(1000, 10000))
guesses = 0
print("Let's Play A Game Of Cows And Bulls!")
print("I Will Generate A 4 Digit Number, And You Have To Guess The Numbers One Digit At A Time.")
print("For Every Number I The Wrong Place, You Get A Bull. For Every Number In The Right Place,
You Get A Cow.")
print("The Game Will End When You Get 4 Bulls.")
print("Type Exit At Any Prompt To Exit!")
while playing:
user_guess = input("Give Me The Best You Got!: ")
if user_guess.lower() == "exit":
break
cowbull_count = compare_number(number, user_guess)
guesses += 1
print(f"You Have {cowbull_count[1]} Cows, And {cowbull_count[0]} Bulls.")
if cowbull_count[1] == 4:
playing = False
print(f"You Win The Game After {guesses} Guess(es)!. The Number Was {number}.")
break
else:
print(f"Your Guess Isn't Quite Right, Tyr Again!.")
You can do something like this:
import random
def compare_number(number, user_guess):
cowbull = [0, 0, 0, 0]
for i in range(len(number)):
if number[i] == user_guess[i]:
cowbull[i] += 1
return cowbull
if __name__ == "__main__":
playing = True
number = str(random.randint(1000, 10000))
guesses = 0
print("Let's Play A Game Of Cows And Bulls!")
print("I Will Generate A 4 Digit Number, And You Have To Guess The Numbers One Digit At A Time.")
print("For Every Number I The Wrong Place, You Get A Bull. For Every Number In The Right Place, You Get A Cow.")
print("The Game Will End When You Get 4 Bulls.")
print("Type Exit At Any Prompt To Exit!")
while playing:
user_guess = input("Give Me The Best You Got!: ")
if user_guess.lower() == "exit":
break
cowbull_count = compare_number(number, user_guess)
guesses += 1
correct = sum(cowbull_count)
wrong = len(number) - correct
print(f"You Have {correct} Cows, And {wrong} Bulls.")
if correct == 4:
playing = False
print(f"You Win The Game After {guesses} Guess(es)!. The Number Was {number}.")
break
else:
print(f"Your Guess Isn't Quite Right, Try Again!.")
if correct >= 1:
print(str([user_guess[i] for i, x in enumerate(cowbull_count) if x == 1]) + " was correct!")
Changes made to your original code:
Instead of returning [numOfCorrect,numOfWrong], i returned [is 1 correct?, is 2 correct?, is 3 correct? is 4 correct?] // you need this to know which was right and which was wrong
the number of cows is = the number of correct which is equal to sum of 1's in cowbull_count //changed because of different return of compare_number
the number of bulls is = the number of wrong which is equal to number of digits - number of wrongs = len(numbers) - correct //changed because of different return of compare_number
if not all 4 digits were correct, show them which number they got correct // this is what you wanted
Sample run
You can replace your compare number function to print the index and value of the correct number.
def compare_number(number, user_guess):
cowbull = [0, 0]
for i in range(len(number)):
if number[i] == user_guess[I]:
cowbull[1] += 1
print("The number " + number[i] + " at index " + i " is correct")
else:
cowbull[0] += 1
print("The number " + number[i] + " at index " + i " is incorrect")
return cowbull
Add another method that return a list of positions: 4 element list, 0 if the user didn't guess a digit, 1 if he did. You can use it as you want in your function.
def digit_position(number, user_guess):
right_guesses = [0, 0, 0, 0]
for i in range(len(number)):
if number[i] == user_guess[i]:
right_guesses[i] = 1
return right_guesses
# Cow and Bull Game is a game in which User
# tries to guess the Secret code chosen by computer.
# We have 2 use cases i.e
# If Value in index of both User's and Computer's number are same than it is Cow.
# If Value Exists but not on same index as computer's than ita a Bull.
import random
# Following function generate a unique 4-digit number
def checkDuplication():
r = str(random.randint(1000, 9999))
for i in r:
if r.count(i) > 1:
return checkDuplication()
return r
# Following function check both number and returns Cow and Bull COUNTS.
def cowBullGame(human):
cow_count = bull_count = 0
for i in human:
if i in computer:
if human.count(i) > 1:
print('No Repeatative Numbers Allowed!')
return 0
if human.index(i) == computer.index(i): # Checking if both the value in index i are same or not
cow_count += 1
else:
bull_count += 1
print(str(cow_count)+' Cows, '+str(bull_count)+' Bulls')
return cow_count # Returning Cow_Count to check All Numbers are on right place.
computer = checkDuplication()
print(computer)
guesses = 1
# Infinite Loop till user gets 4 Cow_Counts
while True:
human = str(int(input('Guess a Number :')))
if cowBullGame(human) == 4:
print('Game Over. You made '+str(guesses)+' guesses')
break
guesses += 1
This is my code for a game in which the computer must guess a user defined number within a given range. This is a challenge from a beginners course/ book.
I'd like to draw your attention to the 'computerGuess()' function. I think there must be a more eloquent way to achieve the same result? What I have looks to me like a botch job!
The purpose of the function is to return the middle item in the list (hence middle number in the range of numbers which the computer chooses from). The 0.5 in the 'index' variable equation I added because otherwise the conversion from float-int occurs, the number would round down.
Thanks.
Code:
# Computer Number Guesser
# By Dave
# The user must pick a number (1-100) and the computer attempts to guess
# it in as few attempts as possible
print("Welcome to the guessing game, where I, the computer, must guess your\
number!\n")
print("You must select a number between 1 and 100.")
number = 0
while number not in range(1, 101):
number = int(input("\nChoose your number: "))
computerNumber = 0
computerGuesses = 0
higherOrLower = ""
lowerNumber = 1
higherNumber = 101
def computerGuess(lowerNumber, higherNumber):
numberList = []
for i in range(lowerNumber, higherNumber):
numberList.append(i)
index = int((len(numberList)/2 + 0.5) -1)
middleValue = numberList[index]
return middleValue
while higherOrLower != "c":
if computerGuesses == 0:
computerNumber = computerGuess(lowerNumber, higherNumber)
elif higherOrLower == "l":
higherNumber = computerNumber
computerNumber = computerGuess(lowerNumber, higherNumber)
elif higherOrLower == "h":
lowerNumber = computerNumber + 1
computerNumber = computerGuess(lowerNumber, higherNumber)
print("\nThankyou. My guess is {}.".format(computerNumber))
computerGuesses += 1
higherOrLower = input("\nHow did I do? If this is correct, enter\
'c'. If your number is higher, enter 'h'. If it is lower, enter 'l': ")
print("\nHaha! I got it in {} attempt(s)! How great am I?".format\
(computerGuesses))
input("\n\nPress the enter key to exit.")
Like this ?
import math
def computerGuess(lowerNumber, higherNumber):
return int((lowerNumber+higherNumber)/2)
I am trying to create a number guessing game with multiple numbers. The computer generates 4 random numbers between 1 and 9 and then the user has 10 chances to guess the correct numbers. I need the feedback to display as YYYY for 4 correct numbers guessed, YNNY for first and last number guessed etc. (you get the point). the code below keeps coming back saying IndexError: list index out of range.
from random import randint
guessesTaken = 0
randomNumber = []
for x in range(4):
tempNumber = randint(1, 9)
randomNumber.append(tempNumber)
Guess = []
Guess.append(list(input("Guess Number: ")))
print(randomNumber)
print(Guess)
if randomNumber[0] == Guess[0]:
print("Y")
elif randomNumber[1] == Guess[1]:
print("Y")
elif randomNumber[2] == Guess[2]:
print("Y")
elif randomNumber[3] == Guess[3]:
print("Y")
elif randomNumber[0] != Guess[0]:
print("N")
elif randomNumber[1] != Guess[1]:
print("N")
elif randomNumber[2] != Guess[2]:
print("N")
elif randomNumber[3] != Guess[3]:
print("N")
You need four guesses to match for random numbers, you can also shorted your code using a list comp:
from random import randint
guessesTaken = 0
randomNumber = []
Guess = []
for x in range(4):
tempNumber = str(randint(1, 9)) # compare string to string
randomNumber.append(tempNumber)
Guess.append(input("Guess Number: "))
print("".join(["Y" if a==b else "N" for a,b in zip(Guess,randomNumber)]))
You can also use enumerate to check elements at matching indexes:
print("".join(["Y" if randomNumber[ind]==ele else "N" for ind, ele in enumerate(Guess)]))
To give the user guesses in a loop:
from random import randint
guessesTaken = 0
randomNumber = [str(randint(1, 9)) for _ in range(4)] # create list of random nums
while guessesTaken < 10:
guesses = list(raw_input("Guess Number: ")) # create list of four digits
check = "".join(["Y" if a==b else "N" for a,b in zip(guesses,randomNumber)])
if check == "YYYY": # if check has four Y's we have a correct guess
print("Congratulations, you are correct")
break
else:
guessesTaken += 1 # else increment guess count and ask again
print(check)
Right now you're only asking the user for one guess, and appending the guess to the Guess list. So the Guess list has one element, but you're using Guess[1], Guess[2], etc., which of course results in the IndexError
I'll rearrange your code a bit, so it doesn't stray too far from what you've done.
from random import randint
guessesTaken = 0
randomNumbers = []
Guess = [] # Combine your guesses with your loop
for x in range(4):
tempNumber = randint(1, 9)
randomNumbers.append(tempNumber)
# This should be done four times too
# In Python 2, instead of this:
# Guess.append(input("Guess Number: "))
# do this:
Guess.append(int(raw_input("Guess Number: "))) # raw_input and pass to int
# in python 3, raw_input becomes input, so do this instead:
# Guess.append(int(input("Guess Number: ")))
print(randomNumbers)
print(Guess)
You can combine these in a loop to avoid the repetitive code:
if randomNumbers[0] == Guess[0]:
print("Y")
else:
print("N")
if randomNumbers[1] == Guess[1]:
print("Y")
else:
print("N")
if randomNumbers[2] == Guess[2]:
print("Y")
else:
print("N")
if randomNumbers[3] == Guess[3]:
print("Y")
else:
print("N")
Perhaps, to print your desired result e.g. YNNY, like this:
result = []
for index in range(4):
if randomNumbers[index] == Guess[index]:
result.append("Y")
else:
result.append("N")
print(''.join(result))
If you want terser code use Python's ternary operation:
result = []
for index in range(4):
result.append("Y" if randomNumbers[index] == Guess[index] else "N")
print(''.join(result))
Or use the fact that True == 1 and False == 0 as indexes:
result = []
for index in range(4):
result.append("NY"[randomNumbers[index] == Guess[index]])
print(''.join(result))