The question is to check the guess entered as the input to the random number generator,
Here is my code for that,
import random
int1 = 1
int2 = 50
correctNumber = random.randint(1, 50)
a =int(input("Please enter your number: "))
while True:
if a > correctNumber:
print("LOW")
a = int(input("Please enter again : "))
elif a < correctNumber:
print("HIGH")
a = int(input("Please enter again : "))
elif a == correctNumber:
print("YOU GOT IT RIGHT")
break
The loop breaks after one cycle,
This solves the problem:
import random
int1 = 1
int2 = 50
correctNumber = random.randint(1, 50)
a =int(input("Please enter your number: "))
while True:
if a > correctNumber:
print("LOW")
a = int(input("Please enter again : "))
elif a < correctNumber:
print("HIGH")
a = int(input("Please enter again : "))
elif a == correctNumber:
print("YOU GOT IT RIGHT")
break #break used inside elif to loop while correct is not provided
Your booleans seem backward to me. When if a > correctNumber: the the guess is "HIGH" not "LOW".
With that, instead of breaking. You could make your while loop condition based on whether the guess is correct.
import random
int1 = 1
int2 = 50
correctNumber = random.randint(int1, int2)
a = int(input("Please enter your number: "))
while a != correctNumber:
if a < correctNumber:
print("LOW")
elif a > correctNumber:
print("HIGH")
a = int(input("Please enter again : "))
print("YOU GOT IT RIGHT")
If you are using a recent version of python, you can simplify it even further by assigning in the while loop with the := (walrus) operator:
import random
int1 = 1
int2 = 50
correctNumber = random.randint(int1, int2)
while (a := int(input("Please enter your number: "))) != correctNumber:
print("LOW" if a < correctNumber else "HIGH")
print("YOU GOT IT RIGHT")
Indent the break statement from the final line.
The break keyword is used to break out of the while loop. At its current state, the loop is terminating after 1 cycle because it hits the break keyword.
If you indent the break statement, it will be part of the elif block of code, and will only execute after a == correctNumber.
This code would work:
import random
correctNumber = random.randint(1, 50)
a =int(input("Please enter your number: "))
while True:
if a > correctNumber:
print("LOW")
a = int(input("Please enter again : "))
elif a < correctNumber:
print("HIGH")
a = int(input("Please enter again : "))
elif a == correctNumber:
print("YOU GOT IT RIGHT")
break
Learn more about break here
Related
This program is supposed to do basic calculations by asking the user what type of calculation it wants to perform, then it collects two numbers via the user input and finally performs the calculation by spitting it out before asking you to close it. In the else statement I have here, if the user doesn't input what I want them to, it'll tell them to read more carefully and then it restarts the program. What I want to do is make it so that if the else statement has been executed 3 or 4 times, it will print "I give up" and then it asks the user to type anything to exit the program. I'm a beginner too!
while True:
Pick = input("add, sub, multiply, or divide? :")
# Pick the calculation and then actually do it
if Pick == "add":
num_one = float(input("First number: "))
num_two = float(input("Second number:"))
if num_one == 9 and num_two == 10:
print("Twenty one? You stupid.")
Exit = input("Type literally anything to exit ")
break
print("The sum is : ", num_one + num_two)
Exit = input("Type literally anything to exit ")
break
elif Pick == "sub":
num_one = float(input("First number: "))
num_two = float(input("Second number:"))
print("The result is : ", num_one - num_two)
Exit = input("Type literally anything to exit ")
break
elif Pick == "multiply":
num_one = float(input("First number: "))
num_two = float(input("Second number:"))
print("The product is : ", num_one * num_two)
Exit = input("Type literally anything to exit ")
break
elif Pick == "divide":
num_one = float(input("First number: "))
num_two = float(input("Second number:"))
print("The quoitient is : ", num_one / num_two)
Exit = input("Type literally anything to exit ")
break
else:
print("Read and type exactly what it says in the beginning.")
continue
You can simply count how often your loop runs, so before the the loop you would have to add a loop counter, which you increase whenever the last else is called. Within the last else you then simply have to check how high the counter is. See for example:
loop_counter = 0
while True:
...
else:
if loop_counter >= 4:
print("Okay, I give up!")
Exit = input("Type literally anything to exit ")
break
else:
loop_counter = loop_counter +1
print("Read and type exactly what it says in the beginning.")
continue
Hope this helps you
i = 0
while True:
Pick = input("add, sub, multiply, or divide? :")
print("NUMBER OF ELSE : "+str(i))
# Pick the calculation and then actually do it
if Pick == "add":
num_one = float(input("First number: "))
num_two = float(input("Second number:"))
if num_one == 9 and num_two == 10:
print("Twenty one? You stupid.")
Exit = input("Type literally anything to exit ")
break
print("The sum is : ", num_one + num_two)
Exit = input("Type literally anything to exit ")
break
elif Pick == "sub":
num_one = float(input("First number: "))
num_two = float(input("Second number:"))
print("The result is : ", num_one - num_two)
Exit = input("Type literally anything to exit ")
break
elif Pick == "multiply":
num_one = float(input("First number: "))
num_two = float(input("Second number:"))
print("The product is : ", num_one * num_two)
Exit = input("Type literally anything to exit ")
break
elif Pick == "divide":
num_one = float(input("First number: "))
num_two = float(input("Second number:"))
print("The quoitient is : ", num_one / num_two)
Exit = input("Type literally anything to exit ")
break
else:
i = i + 1
print("Read and type exactly what it says in the beginning.")
continue
The i variable will count the number of else executed
The rest is your job to do :))
I have removed some code duplication in your code, let me know if you have any questions about what I have done :)
while True:
user_input = input("add, sub, multiply, or divide? :")
num_one = float(input("First number: "))
num_two = float(input("Second number:"))
# Pick the calculation and then actually do it
if user_input == "add":
if num_one == 9 and num_two == 10:
print("Twenty one? You stupid.")
break
print(f"The sum is : {num_one + num_two}")
break
elif user_input == "sub":
print(f"The result is : {num_one - num_two}")
break
elif user_input == "multiply":
print(f"The product is : {num_one * num_two}")
break
elif user_input == "divide":
print(f"The quoitient is : {num_one / num_two}")
break
else:
print("Read and type exactly what it says in the beginning.")
continue
Exit = input("Type literally anything to exit ")
As for the counting, you can set a counter variable before the if statement to 0, and in each elif/else statement, it can be incremented by 1.
So it would look like this:
counter = 0
# in elif/else
counter += 1
I just created a simple calculator program using python language, but there is a little problem here, when I end the program by inputting number 1, there is always the text none.
The question is how do I get rid of the text none in the program that I created? Because to be honest it is very annoying and will damage the image of the program that I created.
def pilihan():
i = 0
while i == 0:
print('\n\tWelcome to the Simple Calculator Program')
print("\nPlease Select Existing Operations", "\n1. subtraction", "\n2. increase", "\n3. division", "\n4. multiplication")
pilihan2 = int(input('Enter your choice (1/2/3/4): '))
if pilihan2 == 1:
angka1 = int(input('Enter the First Number: '))
angka2 = int(input('Enter the Second Number: '))
print(angka1, "-", angka2, "=", angka1 - angka2)
elif pilihan2 == 2:
angka1 = int(input('Enter the First Number: '))
angka2 = int(input('Enter the Second Number: '))
print(angka1, "+", angka2, "=", angka1 + angka2)
elif pilihan2 == 3:
angka1 = int(input('Enter the First Number: '))
angka2 = int(input('Enter the Second Number: '))
print(angka1, ":", angka2, "=", angka1 / angka2)
elif pilihan2 == 4:
angka1 = int(input('Enter the First Number: '))
angka2 = int(input('Enter the Second Number: '))
print(angka1, "x", angka2, "=", angka1 * angka2)
else:
print('Error option, please try again')
continue
print('Program finished, want to restart?')
y = 0
while y == 0:
ulang = int(input('Type 0 for YES and 1 for NO = '))
if ulang == 0:
y += 1
break
elif ulang == 1:
y += 2
break
else:
print('\nThe command you entered is an error, please try again')
continue
if y == 1:
continue
else:
break
print(pilihan())
Change the print(pilihan()) to pilihan(), the return value of pilihan() is None :)
I have this very simple console game and I would like to restart the loop after the user answers a question but something doesn't seem to work properly.
import random
random_number = random.randrange(0, 500)
chosen_number = int(input("Please pick a number: "))
gameOn = 1
while gameOn == 1:
if chosen_number == 500 or chosen_number <= 0 :
print("Number must be below 500 and above 0.")
print(random_number)
chosen_number = int(input("Please pick a number: "))
continue
if chosen_number > random_number:
print("Too high")
chosen_number = int(input("Please pick a number: "))
elif chosen_number < random_number:
print("Too low")
chosen_number = int(input("Please pick a number: "))
else:
print("Congratulations, you guessed right. The number was " + str(chosen_number) + ".")
break
answer = input("Do you want to play again? Y/N ")
if answer == "Y" or "y" or "yes":
gameOn = 0
else:
print("Goodbye!")
You can do a simple thing, just put the whole code in a function and when you want to restart just call the function
Look at the code below:
import random
def game():
random_number = random.randrange(0, 500)
chosen_number = int(input("Please pick a number: "))
while True:
if chosen_number == 500 or chosen_number <= 0 :
print("Number must be below 500 and above 0.")
print(random_number)
chosen_number = int(input("Please pick a number: "))
continue
if chosen_number > random_number:
print("Too high")
chosen_number = int(input("Please pick a number: "))
elif chosen_number < random_number:
print("Too low")
chosen_number = int(input("Please pick a number: "))
else:
print("Congratulations, you guessed right. The number was " + str(chosen_number) + ".")
break
answer = input("Do you want to play again? Y/N ")
if answer.lower() == "y" or "yes": # Lower() is used for changing the whole string to lowercase
game()
else:
print("Goodbye!")
When you ask to play again you are setting gameOn to be 0 (as gameOn needs to be 1), which will exit the loop, your code should look like this
if answer in ("Y", "y", "yes"):
print("Starting again")
else:
print("Goodbye!")
gameOn = 0
for further clarification since you are choosing a number each game you need to put that into the loop as well
import random
gameOn = 1
while gameOn == 1:
random_number = random.randrange(0, 500)
chosen_number = int(input("Please pick a number: "))
if chosen_number == 500 or chosen_number <= 0 :
print("Number must be below 500 and above 0.")
print(random_number)
chosen_number = int(input("Please pick a number: "))
continue
if chosen_number > random_number:
print("Too high")
chosen_number = int(input("Please pick a number: "))
elif chosen_number < random_number:
print("Too low")
chosen_number = int(input("Please pick a number: "))
else:
print("Congratulations, you guessed right. The number was " + str(chosen_number) + ".")
break
answer = input("Do you want to play again? Y/N ")
if answer in ("Y", "y", "yes"):
print("Starting again")
else:
print("Goodbye!")
gameOn = 0
The loop will automatically restart if you don't change any of the variables. So I would change your if else statement to just an if statement that says:
if answer.lower() != "y" or answer.lower() != "yes":
break
but in order for the game to be re-run properly and change the random number variable you need to re-execute the entire program which you can do by putting the program in a function then putting the function and the if statement in that loop for example:
import random
def runGame():
random_number = random.randrange(0, 500)
chosen_number = int(input("Please pick a number: "))
running = True
while running:
if chosen_number == 500 or chosen_number <= 0 :
print("Number must be below 500 and above 0.")
print(random_number)
chosen_number = int(input("Please pick a number: "))
continue
if chosen_number > random_number:
print("Too high")
chosen_number = int(input("Please pick a number: "))
elif chosen_number < random_number:
print("Too low")
chosen_number = int(input("Please pick a number: "))
else:
print("Congratulations, you guessed right. The number was " + str(chosen_number) + ".")
break
while gameOn == 1:
runGame()
answer = input("Do you want to play again? Y/N ")
if answer.lower() != "y" or answer.lower() != "yes":
gameOn = 0
I have an issue with my simple guess the number game in python.The code is given below.The program never gives me a correct guess,it keep asking the number.
import random
import time
time1 = time.time()
number = random.randint(1,1000)
print ("welcome to the guessing game")
name = input("what is your name? ")
print("well, " + name + " iam thinking of the number between 1 and 1000")
while True:
guess = int(input("guess: ") )
if guess > number:
print("too high!")
if guess < number:
print("too low!")
if guess == number:
break
print("yahoo,you guessed the number!")
input()
time2 = time.time()
that is number guessing game in python 3.
You need to indent the code correctly, you should also use if/elif's as guess can only be one of higher, lower or equal at any one time. You also need to print before you break on a successful guess:
while True:
guess = int(input("guess: ") )
if guess > number:
print("too high!")
elif guess < number:
print("too low!")
elif guess == number:
print("yahoo,you guessed the number!")
time2 = time.time()
break
There is no way your loop can break as your if's are nested inside the outer if guess > number:, if the guess is > number then if guess < number: is evaluated but for obvious reasons that cannot possibly be True so you loop infinitely.
import random
import time
time1 = time.time()
number = random.randint(1,1000)
print ("welcome to the guessing game")
name = input("what is your name? ")
print("well, " + name + " i am thinking of the number between 1 and 1000")
while True:
guess = int(input("guess: ") )
if guess > number:
print("too high!")
if guess < number:
print("too low!")
if guess == number:
print("yahoo,you guessed the number!")
time2 = time.time()
break
without changing too much, here is a working code.
secret_number = 5
chance = 1
while chance <= 3:
your_guess = int(input("Your Guess:- "))
chance = chance + 1
if your_guess == secret_number:
print("You Won !!")
break
else:
print("You failed..TRY AGAIN..")
import random as rand
# create random number
r =rand.randint(0,20)
i=0
l1=[]
while(i<4):enter code here
number = int(input("guess the number : "))
if(number in l1):
print("this number is alraedy entered")
i=i
else:
l1.append(number)
if(number == r):
print(number)
break
if(number>r):
print(" number is less than your number ")
elif(number<r):
print("number is greater than your number")
i =i+1
print("number is")
print(r)
Why does the too low, too high and got it print repeatedly lots of times?
This is my code:
import random
name = input("Hello there! What's your name?\n")
print("Hello there", name, ". Welcome to GUESS THE NUMBER GAME")
number = random.randint(1,100)
guess = int(input("Please guess a number"))
n=1
while n<10:
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
elif guess == number:
print("Got it")
n=n+1
You need to move the guess inside the loop, from:
guess = int(input("Please guess a number"))
n=1
while n<10:
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
elif guess == number:
print("Got it")
n = n+1
to:
n = 1
while n < 10:
guess = int(input("Please guess a number"))
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
elif guess == number:
print("Got it")
n += 1
Also, you can simplify with:
for _ in range(9):
guess = int(input("Please guess a number"))
...
And should break when the user makes a correct guess:
elif guess == number:
print("Got it")
break
Is this your real indentation ?
if yes:
while n<10:
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
elif guess == number:
print("Got it")
and the last elif guess == number: can be just else ;)
edit: and I have forgotten your n++ and the real problem: the input
so:
while n<10:
guess = int(input("Please guess a number"))
n = n+1
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
else:
print("Got it")
and to exit the loop:
while n<10:
guess = int(input("Please guess a number"))
n = n+1
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
else:
print("Got it in "+n+" attempts.")
n=11
Assuming the code you provided has the correct indentation, then it's because the n = n + 1 statement is outside of the while loop. The corrected code is:
import random
name = input("Hello there! What's your name?\n")
print("Hello there", name, ". Welcome to GUESS THE NUMBER GAME")
number = random.randint(1,100)
guess = int(input("Please guess a number"))
n=1
while n<10:
if guess < number:
print("Too low")
elif guess > number:
print("Too high")
elif guess == number:
print("Got it")
n=n+1
One piece of advice (assuming you're using Python 2.X): Use raw_input() instead of input, because raw_input automatically parses the input into a string, while input allows your users to inject arbitrary python code.
ETA: As pointed out by others, the guess statement (guess = int(input("Please guess a number"))) should be moved into the while loop, and a break statement used if the guess is correct.