Computer guessing a user-selected number within a defined range - python

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)

Related

I'm trying to print the largest number from the inputs that the user gives, but it's printing the wrong number

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

Error in repeating input in a tictactoe game

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.

PYTHON Problem: Why is my code showing "NONE" when line no. 9 is executed? can anyone assist me?

print("\tWELCOME TO DRY_RUN CLASS ASSAIGNTMENT!\t")
userList = []
def mainSystem():
number = 1
userInput = int(input("Enter the size of the List: "))
if userInput > 0:
for x in range(0, userInput):
variable = int(input(print("Enter number",number )))
number = number + 1
userList.append(variable)
else:
print("Number should not be less than or equal to '0'!")
def maxAll():
maxofall = 0
for element in userList:
if element > maxofall:
maxofall = element
print("The maximum number is:", element)
while True:
mainSystem()
askUser = int(input("What do you want to do with the numbers?\n1.Max All\n2.Average\n3.Quit\nYour answer: "))
if askUser == 1:
maxAll()
this is the code i am using right now...
what do i need to fix i am getting an error like this wheni am executing line no. 9
:-
Enter Number whatever the number is
Noneinput starts here
???
def mainSystem():
number = 1
userInput = int(input("Enter the size of the List: "))
if userInput > 0:
for x in range(0, userInput):
variable = int(input("Enter number {} : ".format(number) ))
number = number + 1
userList.append(variable)
else:
print("Number should not be less than or equal to '0'!")
Change your function to this.
print() is a function. Which returns nothing (None) in your case.
input() function thinks this None object is worth displaying on console.
Hence None appears on screen before taking any input.
There are a couple of problems:
1)You have a misplaced print() inside input() in your mainSystem() function
2)You probably want to use f-strings to print the right number instead of the string literal 'number'
def mainSystem():
number = 1
userInput = int(input("Enter the size of the List: "))
if userInput > 0:
for x in range(0, userInput):
variable = int(input(f"Enter number {number} : "))
number = number + 1
userList.append(variable)

Python: Cow And Bull Game

*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

Broken binary converter. Index error

i have no idea why this is broken. Also dont tell me to use python's built in function because this is designed for some practice not to actually be used. It is binary to decimal that is broken. It has a index error with the variable 'index'
print('Please choose from the list below:')
print('')
print('1) Convert from decimal/denary to binary; ')
print('2) Covert from binary to denary/decimal; ') #Main Menu
print('3) Infomation and settings (coming soon);')
print('4) Exit. ')
print('')
menu_choice = str(input('Enter your choice here: ')) #User inputs choice here
if menu_choice == '1':
dec_binary()
elif menu_choice == '2':
binary_dec()
elif menu_choice == '3':
print('By Callum Suttle')
else:
return 'Thank You'
def dec_binary(): #Module 1: decimal to binary
dec = int(input('Enter a number in decimal up to 255: ')) #Checks The number is an ok size, could be made bigger
while dec > 255:
dec = int(input('Enter a number up to 255, no more: '))
power = int(7) #change 7 to make bigger by 1 digit
convert = []
while power > -1: #until power goes below zero
if dec - pow(2, power) >= 0: #if entered number subtract 2 to the power of var-pow returns posotive number
convert.append(1)
power -=1 # add a 1
dec = dec - pow(2, power) >= 0
else:
convert.append(0)#if not add a zero
power -=1
print('')
print(convert) # print completed number
print('')
binary_decimal_converter() #back to main menu
def binary_dec():
anwser = 0
l_bi = str(input('Enter a number in binary up to 7 digits: '))
while len(l_bi) != 7: #checks for correct length
l_bi = str(input('Enter a number in binary up to 7 digits, you may add zeros before: '))
power = 7 #size can be increased by using this
index = 0
while index > 6: #until every power has been checked (in reverse order)
if l_bi[index] == '1': #if the digit is equal to 1
anwser += pow(2, power) #add that amount
power -= 1 #take the power to check next #why is this broken
index += 1 # add another index to check previous
else:
power -= 1 #as above
index += 1 #/\
print('')
print(anwser) #prints result
print('')
binary_decimal_converter() #main menu
this doesn't seem right
index = 0
while index > 6: #until every power has been checked (in reverse order)
...
you never enter this loop, do you?
a better loop would be something like
for i, bit in enumerate(l_bi):
answer += int(bit) * pow(2, 7-i)
also, since you're just practicing, you should find a better way to jump from menu to functions and back. you're doing recursive calls, which is a waste of stack, i.e. your functions actually never finish but just call more and more functions.
Some fixes:
def binary_dec():
anwser = 0
l_bi = str(input('Enter a number in binary up to 7 digits: '))
while len(l_bi) > 7: # LOOP UNTIL LENGTH IS LESS THAN 7
l_bi = str(input('Enter... : '))
power = len(l_bi) - 1 # directly set the power based on length
index = 0
while index < len(l_bi): # CORRECT LOOP CONDITION

Categories