how to make a guess number game? - python

im trying to make a guessing game, user can input the level she wants, if 1 just numbers between 1,9 and if 2 between 10,99 otherwise between 100,99... here is my code:
fals = 0
while fals < 10:
if level == 1:
x = random.randint(0,9)
y = random.randint(0,9)
elif level == 2:
x = random.randint(10,99)
y = random.randint(10,99)
else: # Next convert to else
x = random.randint(100,999)
y = random.randint(100,999)
answer = x + y
while (guess := input(f'{x} + {y} = ')) != answer:
fals += 1
if fals == 3:
print(f'{x} + {y} = {answer}')
break
problem is when i input 1 or 2 or 3 it always returns a 3digit question like 395 + 341
--- anyway the other problem is i want to ask 10 questions and also for each question if user inputs the answer 3 time false, program will give the user correct answer and keep asking other question

import random
fals = 1
while fals <= 10:
level = int(input(str(fals)+". Enter level :"))
if level == 1:
x = random.randint(0,9)
y = random.randint(0,9)
elif level == 2:
x = random.randint(10,99)
y = random.randint(10,99)
else: # Next convert to else
x = random.randint(100,999)
y = random.randint(100,999)
answer = x + y
i = 0
while i < 3:
guess = input(f'{x} + {y} = ')
if int(guess) == answer:
print("Correct")
break
i += 1
if i == 3:
print("Answer ",answer)
fals+=1
Hope this code works.

Related

Why this isn't working, it's giving me an this error ('bool' object is not subscriptable)

here is the code, it's a car parking system:
import time
parking_slots = []
start = []
for i in range(6):
start.append(0)
for i in range(6):
parking_slots.append(False)
while True:
print("1.view empty\n2.add\n3.remove\n4.save\n5.load\n6.exit")
choice = int(input())
if choice == 1:
print("Empty slots are: ")
for slot in range(6):
if parking_slots[slot] == 0:
print(slot, end=" - ")
print("")
if choice == 2:
index = int(input("Enter the index of the slot: "))
if start[index] == 0:
start[index] = int(time.time())
parking_slots[index] = True
else:
print("this slot is already token, please choose another one")
if choice == 3:
index = int(input("Enter the index of the slot: "))
print("Your bill is", int(time.time()) - start[index])
parking_slots[index] = False
start[index] = 0
if choice == 4:
open("cps.txt", "w").write("")
for i in start:
open("cps.txt", "a").write(str(i) + "\n")
if choice == 5:
file = open("cps.txt", "r").readlines()
start = [float(x.strip("\n")) for x in file]
for x in range(6):
if start[x] == 0:
parking_slots = False
else:
parking_slots = True
if choice == 6:
break
the error is when I enter choice 1, it tells me bool object is not subscriptable
When choice == 5 you do
for x in range(6):
if start[x] == 0:
parking_slots = False
else:
parking_slots = True
which replaces the list that was contained in parking_slots with a plain boolean, which gives you that error when you later try to index it. Probably here you meant
for x in range(6):
if start[x] == 0:
parking_slots[x] = False
else:
parking_slots[x] = True

Giving one hint for each of the tries (guessing number game)

I am making a game which requires the user to enter a number. They get four tries, and if they get the number wrong, they get a hint.
How can I try to give only one hint for each of the four tries the user has to get the number right? For example, after the user gets the first try wrong, I would like the program to display the even_or_odd hint.
from random import randrange
new_number = randrange(1, 101)
class Hints:
def __init__(self, new_number):
self.new_number = new_number
def even_or_odd(self):
if self.new_number % 2 == 0:
print('Hint. The number is even.')
else:
print('Hint. The number is odd.')
def multiple3to5(self):
for x in range(3, 6):
n = self.new_number % x
if n == 0:
print(f'Hint. The number is a multiple of {x}', end = ' ' )
def multiple6to10(self):
for x in range(6, 11):
n = self.new_number % x
if n == 0:
print(f'Hint. The number is a multiple of x {x}', end = ' ')
print('Guess a number beteen 1 and 100.')
hint = Hints(new_number)
for x in range(1, 5):
is_answer_given = False
while not is_answer_given:
try:
user_input = int(input(f'Attempt {x}: '))
is_answer_given = True
except ValueError:
print('Please enter a numerical value.')
if user_input == new_number and x == 1: #hint after first attempt
print('You win!')
break
else:
print('Incorrect!')
hint.even_or_odd()
if user_input == new_number and x == 2: #hint after second attempt
print('You win!')
break
else:
print('Incorrect!')
hint.multiple3to5()
if user_input == new_number and x == 3: #hint after third attempt
print('You win!')
break
else:
print('Incorrect!')
hint.multiple6to10()
if x == 4:
print('You are out of attempts!')
print(f'The number was {new_number}')
break
You should make one if statement that checks for the correct answer. In the else statement you can use if - elif statements to check for the attempt number.
if user_input == new_number:
print('You win!')
break
else:
print('Incorrect!')
if x == 1:
hint.even_or_odd()
elif x == 2:
hint.multiple3to5()
elif x == 3:
hint.multiple6to10()
else:
print('You are out of attempts!')
print(f'The number was {new_number}')
The reason you see multiple hints on attempt is that for multiple if statements their condition is not true, so their 'else' block is run
Here is a neat trick:
from random import randrange
new_number = randrange(1, 101)
class Hints:
def __init__(self, new_number):
self.new_number = new_number
self.choices = {
1: self.even_or_odd,
2: self.multiple3to5,
3: self.multiple6to10
}
def run(self,key):
action = self.choices.get(key)
action()
def even_or_odd(self):
if self.new_number % 2 == 0:
print('Hint. The number is even.')
else:
print('Hint. The number is odd.')
def multiple3to5(self):
for x in range(3, 6):
n = self.new_number % x
if n == 0:
print(f'Hint. The number is a multiple of {x}', end = ' ' )
else:
print("Well, Not a multple of 3 or 5")
def multiple6to10(self):
for x in range(6, 11):
n = self.new_number % x
if n == 0:
print(f'Hint. The number is a multiple of x {x}', end = ' ')
else:
print("Well, Not a multple of 6 or 10")
print('Guess a number beteen 1 and 100.')
hint = Hints(new_number)
print(new_number)
i = 3
win = False
while i >= 1 :
is_answer_given = False
while not is_answer_given:
try:
user_input = int(input(f'Attempt {i}: '))
is_answer_given = True
except ValueError:
print('Please enter a numerical value.')
if user_input == new_number:
print('You win!, Number is: {new_number}')
win = True
break
hint.run(i)
i -= 1
if not win:
print("You lost!")
print(f"Number is {new_number}")

Why does python show 'list index out of range' error?

I am very new to python, and started learning just 1 week ago. This program works very well except when I enter a number into guess1 variable that starts with 0.
import random
import sys
def script():
while True:
number1 = random.randint(1000, 9999)
number1 = int(number1)
while True:
print ("Enter Your Guess")
guess1 = input()
guess1 = int(guess1)
while True:
if guess1 != number1:
break
elif guess1 == number1:
print ("Your Guess Was Right!")
print ("Do you want to play again? Type YES or NO")
ask = input()
ask = str(ask)
if ask == "YES" or ask == "yes":
script()
elif ask == "NO" or ask == "no":
sys.exit()
else:
print ("Invalid input, try again.")
continue
number = list(str(number1))
guess = list(str(guess1))
if len(guess) > 4:
print ("Please type a 4-digit number")
continue
bulls = 0
wr = 0
cows = 0
a = 3
while a >= 0:
if number[a] == guess[a]:
number[a] = 'a'
guess[a] = 'b'
bulls += 1
a -= 1
b = 0
c = 0
while b < 4:
c = 0
while c < 4:
if number[b] == guess[c]:
number[b] = 'a'
guess[c] = 'b'
wr += 1
c += 1
b += 1
z = bulls + wr
cows = 4 - z
bulls = str(bulls)
cows = str(cows)
wr = str(wr)
print ("Cows: "+cows)
print ("Bulls: "+bulls)
print ("Wrongly Placed: "+wr)
break
script()
This was a program written for a game, in which a 4-digit number is to be guessed. We do it by starting with a random number, and we get clues in the form of cows, bulls and wrongly placed. Cows mean the number is wrong, Bulls mean the number is right, and wrongly placed means the number is right but wrongly placed.
The whole thing works properly, but when I enter a number starting with 0, it shows something like this :-
Traceback (most recent call last):
File "GuessingGame.py", line 61, in <module>
script()
File "GuessingGame.py", line 36, in script
if number[a] == guess[a]:
IndexError: list index out of range
Please help, thanks!
UPDATE:
Thanks to user #blue_note 's answer, The program works now! This is how it has been modified -
import random
import sys
def script():
while True:
number1 = random.randint(1000, 9999)
number1 = int(number1)
while True:
print ("Enter Your Guess")
guess1 = input()
number = list(str(number1))
guess = list(str(guess1))
if guess[0] == 0:
guess1 = str(guess1)
else:
guess1 = int(guess1)
while True:
if guess1 != number1:
break
elif guess1 == number1:
print ("Your Guess Was Right!")
print ("Do you want to play again? Type YES or NO")
ask = input()
ask = str(ask)
if ask == "YES" or ask == "yes":
script()
elif ask == "NO" or ask == "no":
sys.exit()
else:
print ("Invalid input, try again.")
continue
bulls = 0
wr = 0
cows = 0
a = 3
while a >= 0:
if number[a] == guess[a]:
number[a] = 'a'
guess[a] = 'b'
bulls += 1
a -= 1
b = 0
c = 0
while b < 4:
c = 0
while c < 4:
if number[b] == guess[c]:
number[b] = 'a'
guess[c] = 'b'
wr += 1
c += 1
b += 1
z = bulls + wr
cows = 4 - z
bulls = str(bulls)
cows = str(cows)
wr = str(wr)
print ("Cows: "+cows)
print ("Bulls: "+bulls)
print ("Wrongly Placed: "+wr)
break
script()
Since my guess will always be wrong if the first digit is 0, I don't have the need to convert it into int.
Again, thanks for the help guys! This was my first question on the website. It is really a cool website.
When you pass, say, an integer starting with 0, say, 0123, and you convert it to int in the next line, you are left with 123 (3 digits). Later, you do number = list(str(number1)), so your number is ['1', '2', '3'] (length 3). Then, you try to get number[a] with a=3, and that's were you get the error.
You could do something like
number = list(str(number1) if number1 > 999 else '0' + str(number1))

Python Guess number game - While loop not responding

I am a relative newcomer and was trying to create a game where the user and the comp take turns at guessing each others games. I know I am doing something wrong in the while / if operators when the user enters a string eg. Y.
In two places:
1. where the user decides who should go first (if a in ["Y", "y"]
2. while loop in compguess function (while ans = False:) it just skips down.
a = input("Shall I guess first? (Y/N):")
userscore = 1
compscore = 1
def compguess():
global compscore
low = 0
high = 100
c = 50
ans = False
while ans = False:
print ("Is the number", c , "?")
d = input("Enter Y if correct / L if your number is lower or H if higher:")
if d in ["Y" , "y"]:
ans = True
elif d in ["H"]:
high = c
c = int((c + low) / 2)
compscore = compscore + 1
elif d in ["L"]:
low = c
c = int((c + high) / 2)
compscore = compscore + 1
else:
print ("invalid input")
def userguess():
global userscore
g = r.randint(1,100)
h = input("Enter your guess number:")
i = int(h)
while g != i:
if g > i:
h = input("You guessed lower. Guess again:")
i = int(h)
userscore = userscore + 1
else:
h = input("You guessed higher. Guess again:")
i = int(h)
userscore = userscore + 1
if a in ["Y", "y"]:
compguess()
userguess()
else:
userguess()
compguess()
if userscore == compscore:
print("Its a tie !!")
elif userscore < compscore:
print ("Congrats ! You won !")
else:
print ("I won !! Better luck next time")
I'd change your while loop condition to:
while not ans:
Also, in r.randint(1,100), r is undefined. If you want to use a function from random, you need to import it:
You could do either import random or from random import randint. If you want to keep the r, you can do import random as r.
You should also indicate when the guessing games end. Although it's implied they flow right into each other and I was confused at first.
The wording is incorrect for the computer guessing:
Is the number 50 ?
Enter Y if correct / L if your number is lower or H if higher:H
Is the number 25 ?
Enter Y if correct / L if your number is lower or H if higher:L
Is the number 37 ?
Enter Y if correct / L if your number is lower or H if higher:Y
I won !! Better luck next time
Initial guess is 50. Then, I say my number is higher. Then the subsequent guess is lower. You reversed either the math or the phrasing.
while ans = False:
should be
while ans == False:
print ("Is the number", c , "?")
d = input("Enter Y if correct / L if your number is lower or H if higher:")
if d in ["Y" , "y"]:
ans = True
elif d in ["H"]:
high = c
c = int((c + low) / 2)
compscore = compscore + 1
elif d in ["L"]:
low = c
c = int((c + high) / 2)
compscore = compscore + 1
else:
print ("invalid input")
Here you check if d is H (higher) and you calculate like it is lower ((50 + 0) /2) = 25
So you need to switch that
Also you forgot one more = in while ans = False:

why am i getting an UnboundLocalError after i add my while loop and if then else if statements?

Whats going on here?
It's a basic slot machine game but when i try and add my conditions for the coins and coin generating I get the UnboundLocalError.
The random numbers generate when i don't have my while loop and if then else if statements
import random
def main():
coins = 50
x = 0
y = 0
z = 0
while coins >= 0 or giveUp != yes:
coins = (coins - 3)
x = random.randrange(1, 7)
y = random.randrange(1, 7)
z = random.randrange(1, 7)
x = x
y = y
z = z
print (x + y + Z)
if (x == y) or (x == z):
if (x == 1):
coins = (coins + 3)
print ("you win 3 coins")
elif x == 2:
coins = (coins +3)
print = ("you win 3 coins")
elif x == 3:
coins = (coins + 3)
print = ("you win 3 coins")
elif x == 4:
coins = (coins +3)
print = ("you win 3 coins")
elif x == 5:
coins = (coins + 3)
print = ("you win 3 coins")
elif x == 6:
coins = (coins + 3)
print = ("you win 3 coins")
elif x == 7:
coins = (coins + 3)
print = ("you win 3 coins")
giveUp = (input("do you give up?"))
main()
This assignment (also called "binding")
giveUp = (input("do you give up?"))
means giveUp is a local.
The whileloop is trying to test this local variable before you have assigned to it (ie bound it)
You could fix this by setting giveUp = "No" before the while loop
Also the yes should probably be "yes"
while coins >= 0 or giveUp != yes:
In here your loop condition is up to a variable called giveUp, but you're trying to define that variable in the loop. You have to define it before the loop first. The best solution is define giveUp="No" before the while loop. Also input() returns string so it must be;
giveUp="No"
while coins >= 0 or giveUp != "yes":
#codes
Another tip, you're using or operator, so if user type no even without any coins user still can play. You should change it to and;
while coins >= 0 and giveUp != "yes":
Now if user want to play, need coins and 'yes'
Please correct your code...
print (x + y + Z) name Z in your code is Upper.
Sure error in here.. and print = name print should not follow the character =
Try this..
>>> import random
>>> def main():
coins = 50
x = 0
y = 0
z = 0
while coins >= 0 or giveUp != yes:
coins = (coins - 3)
x = random.randrange(1, 7)
y = random.randrange(1, 7)
z = random.randrange(1, 7)
x = x
y = y
z = z
print (x + y + z)
if (x == y) or (x == z):
if (x == 1):
coins = (coins + 3)
print ("you win 3 coins")
elif x == 2:
coins = (coins +3)
print ("you win 3 coins")
elif x == 3:
coins = (coins + 3)
print ("you win 3 coins")
elif x == 4:
coins = (coins +3)
print ("you win 3 coins")
elif x == 5:
coins = (coins + 3)
print ("you win 3 coins")
elif x == 6:
coins = (coins + 3)
print ("you win 3 coins")
elif x == 7:
coins = (coins + 3)
print ("you win 3 coins")
giveUp = (input("do you give up?"))
>>> main()
you win 3 coins
do you give up?3
12
12
9
7
12
9
14
10
15
you win 3 coins
do you give up?1
9
>>>

Categories