import random
def g1to9():
a = random.randint(1,9)
wt = 0
b = input("Guess a number from 1 to 9:")
if a == b:
print("You guessed it correctly, it took you {} tries".format(wt))
while True:
if a != b:
print("You are wrong!")
b = input("Guess a number from 1 to 9:")
wt += 1
I am trying to create a game "Guess a number from 1 to 9". But when I run it I check all the numbers but a is never equal to b. I tried to make a a global variable,but it didn't work. What's wrong with my code?
b would of type str as it is an input. You need to cast it to an int first. You can do that by:
b = int(input("Guess a number from 1 to 9:"))
Related
My Tutor has set us a task: Create a higher/lower number guessing game with random integers. We must ask the user for a maximum value to generate and how many values we want to play.
For example:
max value: 12
number of values: 6
3 Hi(H) Lo(L):H
7 Hi(H) Lo(L):L
9 Hi(H) Lo(L):L
12 Hi(H) Lo(L):L
10 Hi(H) Lo(L):L
4
Your score is:4
The code I tried:
import random
print("This program plays out HI/LO game with random integer values")
mx_val = int(input("Enter maximun value: "))
num_val = int(input("Enter how many values to play(less than max value): "))
print("Get ready to play the game")
a = []
while len(a) != num_val:
r = random.randint(1, mx_val)
if r not in a:
a.append(r)
score = 0
for i in a:
print(a[0], end=" ")
guess = input("Enter Hi(H)or Lo(L): ")
while guess != "H" and guess != "L":
guess = input("You must enter 'H' or 'L': ")
if guess == "H" and a[1] > a[0]:
score += 1
if guess == "L" and a[1] < a[0]:
score += 1
a.pop(0)
print("Final score is ", score)
This is my code but it does not ask the right amount of questions. It's always way short.
Do not iterate over list and remove items from that list at the same time
It's not enough values in your a list. You need to increase it by one
Code:
import random
print("This program plays out HI/LO game with random integer values")
mx_val = int(input("Enter maximun value: "))
num_val = int(input("Enter how many values to play(less than max value): "))
print("Get ready to play the game")
a = []
while len(a) != num_val+1:
r = random.randint(1, mx_val)
if r not in a:
a.append(r)
score = 0
for i in range(num_val):
print(a[0], end=" ")
guess = input("Enter Hi(H)or Lo(L): ")
while guess != "H" and guess != "L":
guess = input("You must enter 'H' or 'L': ")
if guess == "H" and a[1] > a[0]:
score += 1
if guess == "L" and a[1] < a[0]:
score += 1
a.pop(0)
print("Final score is ", score)
Output:
This program plays out HI/LO game with random integer values
Enter maximun value: 12
Enter how many values to play(less than max value): 6
Get ready to play the game
10 Enter Hi(H)or Lo(L): H
4 Enter Hi(H)or Lo(L): L
8 Enter Hi(H)or Lo(L): H
7 Enter Hi(H)or Lo(L): L
9 Enter Hi(H)or Lo(L): H
11 Enter Hi(H)or Lo(L): L
Final score is 2
random = random.randint(1000, 9999)
guess = int(input("Enter your guess: "))
while guess != random:
guess = int(input("That was incorrect! Enter your guess: "))
This works as a very simple guessing game, however I would like to include something where after every unsuccessful try it would say how many numbers out of the four digit number were correct.
I have not attempted this, mainly because I'm not sure how this could be done.
e.g
random = 1234
Enter your guess: 1111
You guessed 1 number correct
Enter your guess: 1222
You guessed 2 numbers correct
...... and so on
If you meant with positions
random = random.randint(1000, 9999)
guess = int(input("Enter your guess: "))
while guess != random:
right = 0
index = 0
for char in str(guess):
if char == str(random)[index]:
index += 1
right += 1
print(f'{right} were right')
guess = int(input("That was incorrect! Enter your guess: "))
If you really wanted to keep both numbers as int, you could use % (modulo operator) to find the remainder of your integer once divided by its base-10 value.
For example.
correctnum = 0
random = 1234
guess = 1111
if ((((random-(random % 1000 )) /1000) == (((guess-(guess % 1000 )) /1000)):
correctnum++
Formula repeated for 100/10/1 should all compare numbers in that "spot" without having to convert datatypes. Follow that up with an output of the value of correctnum and you should have what you need.
random = 1234
random = str(random)
#guess = str(input('enter your guess'))
guess = '1222'
correct = 0
for i in range(len(guess)):
if guess[i] == random[i]:
correct += 1
print(correct)
ouput: 2
or simply:
correct = sum(guess[i] == random[i] for i in range(len(guess)))
I am trying to make a program that randomly selects a number, and then you have to guess that number until you get that number correct. So far it works so that I can guess one time, and then the program ends, i need it to repeat my input until i guess the correct number.
import random
a = random.randint(1,20)
print("My number is somewhere between one and twenty")
b = int(input("What is your guess?: "))
if b == a:
print("You guessed my number!")
elif b > a:
print("You're number is too large")
elif b < a:
print("You're number is too small")
input("\n\nPress the enter key to exit")
You're missing the while loop which will execute until a certain condition is met. In your case, the code would be like this:
import random
a = random.randint(1,20)
print("My number is somewhere between one and twenty")
b = 0 # We create the variable b
while b != a: # This executes while b is not a
b = int(input("What is your guess?: "))
if b > a:
print("Your number is too large")
elif b < a:
print("Your number is too small")
print("You guessed my number!") # At this point, we know b is equal to a
input("\n\nPress the enter key to exit")
It's working
import random
a = random.randint(1,20)
print("My number is somewhere between one and twenty")
while True: #missing the while loop
b = int(input("What is your guess?: "))
if b == a:
print("You guessed my number!")
exit()
elif b > a:
print("You're number is too large")
elif b < a:
print("You're number is too small")
Below is my code to generate random number between 0 - 9 and checking with user input whether it is higher lower or equal. When I run the code, it is not taking input and showing
error in 'guessNumber = int(input("Guess a Random number between 0-9")) File "", line 1 '
Can somebody please tell me where I'm making mistake
#Guess Random Number
#Generate a Random number between 0 to 9
import random
turn = 0
def guessRandom():
secretNumber = random.randint(0,9)
guessNumber = int(input("Guess a Random number between 0-9"))
while secretNumber != guessNumber:
if(secretNumber > guessNumber):
input("You have Guessed the number higher than secretNumber. Guess Again!")
turn = turn + 1
elif (secretNumber < guessNumber):
input("You have guessed the number lower than secretNumber. Guess Again! ")
turn = turn + 1
if(secretNumber == guessNumber):
print("you Have Guessed it Right!")
guessRandom()
I think guessRandom() was meant to be outside of the method definition, in order to call the method. The guessNumber variable never changes since the inputs are not assigned to be guessNumber, thus it will continuously check the initial guess. Also, the less than / greater than signs seem to conflict with the intended message. Additionally, turn is outside of the scope of the method.
#Generate a Random number between 0 to 9
import random
def guessRandom():
secretNumber = random.randint(0, 9)
guessNumber = int(input("Guess a Random number between 0-9: "))
i = 0
while secretNumber != guessNumber:
if secretNumber < guessNumber:
print "You have guessed a number higher than secretNumber."
i += 1
elif secretNumber > guessNumber:
print "You have guessed a number lower than secretNumber."
i += 1
else:
print("you Have Guessed it Right!")
guessNumber = int(input("Guess Again! "))
return i
turn = 0
turn += guessRandom()
EDIT: Assuming you're using input in Python3 (or using raw_input in older versions of Python), you may want to except for ValueError in case someone enters a string. For instance,
#Generate a Random number between 0 to 9
import random
def guessRandom():
secretNumber = random.randint(0, 9)
guessNumber = input("Guess a Random number between 0-9: ")
i = 0
while True:
try:
guessNumber = int(guessNumber)
except ValueError:
pass
else:
if secretNumber < guessNumber:
print "You have guessed a number higher than secretNumber."
i += 1
elif secretNumber > guessNumber:
print "You have guessed a number lower than secretNumber."
i += 1
else:
print("you Have Guessed it Right!")
break
guessNumber = input("Guess Again! ")
return i
turn = 0
turn += guessRandom()
I changed the while loop condition to True and added a break because otherwise it would loop indefinitely (comparing an integer to a string input value).
I'm working on improving my python 3 skills by creating this simple game.
Very basic, you have a random number between 1 and 5 and if you guess it correct them you win. However for reason reason whenever I try to run it all I get is the "you lose" result even when my test print shows I got the same number.
#!/usr/bin/python3
import random
B = input("Pick a number between 1 and 5:" )
F = random.randrange(1, 5, 1)
if B == F:
print("You win")
else:
print("You lose")
print (B, F)
I can't tell if it's the == function that is causing the problem or the if function is wrong for some reason but it doesn't look it.
import random
B = int(input("Pick a number between 1 and 5 ")) # Input goes inside int()
F = random.randrange(1,5,1)
if B == F:
print("you win")
else:
print("you lose")
print(B, F)
Side Note: The code you produced actually works fine in Python 2 where input returns an int if appropriate.
Cast the input in order to get an int
#!/usr/bin/python3
import random
B = int(input("Pick a number between 1 and 5 " ))
F =(random.randrange(1,5,1))
if B == F:
print("you win")
else:
print("you lose")
print (B, F)
B = int(input("Pick a number between 1 and 5 " ))
Change the type for the input to an integer.