How do I break out loops with a keyboard input in Python - python

All this below is the context for the main program, could mostly be ignored if you change it around
from random import randint
from time import sleep
import cursor
numbers = 0
random = 0
mini = 0
maxi = 0
nums = list()
cursor.show()
while True:
try:
miniRange = int(input("Enter the Lower Range: "))
maxiRange = int(input("Enter the Maxium Range: "))
if miniRange > maxiRange:
print("Minium number is higher than Maxium number!")
elif miniRange < maxiRange and maxiRange > miniRange:
break
except:
print("Error! Not a number!")
while True:
try:
finder = int(input(f"Enter the number you want to find between {miniRange} and {maxiRange}: "))
if finder < miniRange:
print(f"Not valid! Lower than {miniRange}!")
elif finder > maxiRange:
print(f"Not valid! Higher than {maxiRange}!")
elif finder >= miniRange and finder <= maxiRange:
print("--------------------------------------")
break
except:
print("Error! Not a number!")
cursor.hide()
This is the loop I want to break out of, I've tried while x != "" and I've tried importing keyboard but I couldn't find a solution
while True:
try:
random = randint(miniRange, maxiRange)
numbers += 1
nums.append(random)
print(random)
if random == finder:
mini = min(nums)
maxi = max(nums)
print(f"\nIt took {numbers} Tries to find {finder}!")
print(f"\nThe lowest number found is! {mini}")
print(f"\nThe highest number found is! {maxi}")
print("--------------------------------------\n")
numbers = 0
nums.clear()
sleep(5)
except:
print("You messed up in a great capacity")

Related

How can I get two variables to hold the amount of higher than and lower than guesses?

I am creating a game in which the computer selects a random number 1-10
Then the user guesses the number until they get it right.
The trouble I am having is that when the users enter the wrong answer the variables high or low should be updated, but it just continues looping until the user does enter the right answer. Which causes high and low to always be at 0.
Any ideas? I know there is probably something wrong with the way I am looping?
Any pushes in the right direction would be great!
# module to generate the random number
import random
def randomNum():
selection = random.randint(0,9)
return selection
# get the users choices
def userGuess():
correct = True
while correct:
try:
userPick = int(input('Please enter a guess 1-10: '))
if userPick < 1 or userPick >10:
raise ValueError
except ValueError:
print('Please only enter a valid number 1 - 10')
continue
return userPick
# define main so we can play the game
def main():
correctNum = randomNum()
guess = userGuess()
high = 0
low = 0
if guess != correctNum:
print('uhoh try again!')
guess=userGuess()
elif guess > correctNum:
print('That guess is too high!')
high = high + 1
elif guess < correctNum:
print('That guess is too low')
low = low + 1
else:
print('You win!')
# the outcome of the game:
print('Guesses too high:', high)
print('Guesses too low:',low)
print('Thank you for playing!')
main()
Try modifying your main function :
def main():
correctNum = randomNum()
guess = userGuess()
high = low = 0 # nifty way to assign the same integer to multiple variables
while guess != correctNum: # repeat until guess is correct
if guess > correctNum:
print('That guess is too high!')
high = high + 1
else:
print('That guess is too low')
low = low + 1
print('Try again!')
guess=userGuess()
print('You win!')
# the outcome of the game:
print('Guesses too high:', high)
print('Guesses too low:',low)
print('Thank you for playing!')
Also, be careful with random.randint(0,9) : this will give a number between 0-9 (including 0 and 9, but never 10)!
You want to be doing random.randint(1, 10)
# module to generate the random number
import random
def get1to10():
selection = random.randint(1,10)
return selection
# get the users choices
def userGuess():
correct = True
while correct:
try:
userPick = int(input('Please enter a guess 1-10: '))
if userPick < 1 or userPick >10:
raise ValueError
except ValueError:
print('Please only enter a valid number 1 - 10')
continue
return userPick
# define main so we can play the game
def main():
correctNum = get1to10()
guess = 0
high = 0
low = 0
# use a while loop to collect user input until their answer is right
while guess != correctNum:
guess = userGuess()
# use if statements to evaluate if it is < or >
if guess > correctNum:
print('This is too high!')
high = high + 1
continue
# use continue to keep going through the loop if these are true
elif guess < correctNum:
print('this is too low!')
low = low + 1
continue
else:
break
# the outcome of the game:
print('----------------------')
print('Guesses too high:', high)
print('Guesses too low:',low)
print('The correct answer was:', '*',correctNum,'*', sep = '' )
print('Thank you for playing!')
print('---------------------')
main()
I found this solution to work well for what I needed!
Thank you everyone who answered this post!
You can try using a dictionary:
guesses = {'Higher': [],
'Lower': [],
'Correct': False,
} # A Dictionary variable
def add_guess(number, correct_number):
if number > correct_number:
guesses['Higher'].append(number)
elif number < correct_number:
guesses['Lower'].append(number)
else:
guesses['Correct'] = True
return guesses
add_guess(number=5, correct_number=3) # Higher
add_guess(10, 3) # Higher
add_guess(2, 3) # Lower
# Correct is False, and higher has the numbers (10, 5) while lower has the numbers (2)
print(guesses)
add_guess(3, 3) # Correct should now be True
print(guesses)
This, of course, isn't the entire code but should point you in the right direction. There is a ton of resources on python dictionaries online.

Python : If statement within a while loop

I wrote a program, which keeps rolling a "num" sided die until it reaches the maximal roll which is the number you write as "num". However, if it happens that the first roll is the number, the program does not say "You landed on your number!" as it should. Here is the code
import random
num = () #put the number here#
i = random.randint(1,num)
while i != num:
print(i)
print("Not lucky")
i = random.randint(1,num)
if i == num:
print("You landed on your number!")
Again, if the roll equals the number choice, I get "Process finished with exit code 0", not the text I want. How do I fix this?
Put the final print, outside of the while loop, as you're always land there
num = 5 # put the number here#
i = random.randint(1, num)
while i != num:
print("Not lucky,", i, "isn't the one")
i = random.randint(1, num)
print("You landed on your number!")
what if something like that?
import random
num = int(input('Put your number: '))
i = random.randint(1, num)
while True:
if i == num:
print("You landed on your number!")
print(num)
break
else:
print(i)
print("Not lucky")
i = random.randint(1, num)
You can do it like this:
import random
num = (2) #put the number here#
i = random.randint(1,num)
while i != num:
i = random.randint(1,num)
if i != num:
print(i, "Not lucky")
print(i, "You landed on your number!")
import random
num = #put the number here#
while True:
i = random.randint(1,num)
print(i)
if i == num:
print("You landed on your number!")
break
print("Not lucky")

why my code not working AttributeError: 'int' object has no attribute 'isdigit'

#Guess the num
import random
def is_valid_num(num):
if num.isdigit() and 1 <= int(num) <= 100:
return True
else:
return False
def main():
number = random.randint(1,100)
guessed_number = False
guess = input('enter a num')
#guess = (input('enter a num'))
num_of_guesses = 0
while not guessed_number:
if not is_valid_num(guess):
#return False
guess = input('i count only digits enter 1<num<100')
continue
else:
num_of_guesses += 1
#break
guess = int(guess)
if guess < number:
print ('entered number is low')
elif guess > number:
print ('entered number is high')
else:
print ('you got in',num_of_guesses, 'guesses')
guessed_number = True
main()
Expected Out
if random number is system is 51 and we pressed 50 it will print too low, then continue this process lets say we gave input 51
output will you got in 2 guesses
isdigit() is a string method, it doesn't work on int inputs.
change this :
guess = int(input('enter a num'))
to this:
guess = input('enter a num')
your code after editing:
#Guess the num
import random
def is_valid_num(num):
if num.isdigit() and 1 <= int(num) <= 100:
return True
else:
return False
def main():
number = random.randint(1,100)
guessed_number = False
guess = input('enter a num')
#guess = (input('enter a num'))
num_of_guesses = 0
while not guessed_number:
if not is_valid_num(guess):
#return False
guess = input('i count only digits enter 1<num<100')
continue
else:
num_of_guesses += 1
break
guess = int(guess)
if guess < number:
print ('entered number is low')
elif guess > number:
print ('entered number is high')
else:
print ('you got in',num_of_guesses, 'guesses')
guessed_number = True
main()
#Thanks Issac Full code is below
#Guess the num
import random
def is_valid_num(num):
if num.isdigit() and 1 <= int(num) <= 100:
return True
else:
return False
def main():
number = random.randint(1,100)
guessed_number = False
guess = input('enter a num')
#guess = (input('enter a num'))
num_of_guesses = 0
while not guessed_number:
if not is_valid_num(guess):
#return False
guess = input('i count only digits enter 1<num<100')
continue
else:
num_of_guesses += 1
#break
guess = int(guess)
if guess < number:
guess = (input('entered number is low try again'))
elif guess > number:
guess = (input('entered number is high try again'))
else:
print ('you got in',num_of_guesses, 'guesses')
guessed_number = True
main()
Output is below
>>enter a num55
entered number is high try again55
entered number is high try again45
entered number is high try again88
entered number is high try again30
entered number is high try again10
entered number is low try again20
entered number is low try again25
entered number is high try again22
entered number is low try again23
you got in 10 guesses

Number Guessing Game (Python)

Working in Python 3.
I'm still relatively new to Python (only a few weeks worth of knowledge).
The prompt that I was given for the program is to write a random number game where the user has to guess the random number (between 1 and 100) and is given hints of being either too low or too high if incorrect. The user would then guess again, and again until they reach the solution. After the solution, the number of guesses should tally at the end.
import random
def main():
# initialization
high = 0
low = 0
win = 0
number = random.randint(1, 100)
# input
userNum = int(input("Please guess a number between 1 and 100: "))
# if/else check
if userNum > number:
message = "Too high, try again."
high += 1
elif userNum == number:
message = "You got it correct! Congratulations!"
win += 1
else:
message = "Too low, try again."
low += 1
print()
print(message)
# loop
# while message != "You got it correct! Congratulations!":
# display total
print()
print("Number of times too high: ", high)
print("Number of times too low: ", low)
print("Total number of guesses: ", (high + low + win))
main()
I'm struggling to figure out how to make the loop work. I need the random number to be static while the user guesses with inputs. After each attempt, I also need them to be prompted with the correct message from the if/else check.
You could set 'userNum' to be 0, and encase all the input in a while loop:
userNum = 0
while (userNum != number):
This will continually loop the guessing game until the user's guess equals the random number. Here's the full code:
import random
def main():
# initialization
high = 0
low = 0
win = 0
number = random.randint(1, 100)
userNum = 0
while (userNum != number):
# input
userNum = int(input("Please guess a number between 1 and 100: "))
# if/else check
if userNum > number:
message = "Too high, try again."
high += 1
elif userNum == number:
message = "You got it correct! Congratulations!"
win += 1
else:
message = "Too low, try again."
low += 1
print()
print(message)
# loop
# while message != "You got it correct! Congratulations!":
# display total
print()
print("Number of times too high: ", high)
print("Number of times too low: ", low)
print("Total number of guesses: ", (high + low + win))
print("You win")
main()
You can just put your guesses in a simple loop:
import random
def main():
# initialization
high = 0
low = 0
win = 0
number = random.randint(1, 100)
while win == 0:
# input
userNum = int(input("Please guess a number between 1 and 100: "))
# if/else check
if userNum > number:
message = "Too high, try again."
high += 1
elif userNum == number:
message = "You got it correct! Congratulations!"
win += 1
else:
message = "Too low, try again."
low += 1
print()
print(message)
# loop
# while message != "You got it correct! Congratulations!":
# display total
print()
print("Number of times too high: ", high)
print("Number of times too low: ", low)
print("Total number of guesses: ", (high + low + win))
main()
Any of the other answers will work, but another check you can do for the loop is 'not win', which will stop the loop for any value of win that isn't zero.
while not win:
# input
userNum = int(input("Please guess a number between 1 and 100: "))
# if/else check
...
import random
def main():
# initialization
high = 0
low = 0
win = 0
number = random.randint(1, 100)
# input
while(True): #Infinite loop until the user guess the number.
userNum = int(input("Please guess a number between 1 and 100: "))
# if/else check
if userNum > number:
message = "Too high, try again."
high += 1
elif userNum == number:
message = "You got it correct! Congratulations!"
win += 1
break #Break out of the infinite loop
else:
message = "Too low, try again."
low += 1
print(message) ##Display the expected message
print()
print(message)
# display total
print()
print("Number of times too high: ", high)
print("Number of times too low: ", low)
print("Total number of guesses: ", (high + low + win))
if __name__ == '__main__':
main()
There's so many ways you can go about this kind of task, it's what makes programming epic.
I have written a little something that answers your question, it even has a simple feel to it!
What i've done is done a for loop to give the user a total of range(10) tries. For every guess the user makes, it adds 1 'tries' to 0. In my if statement, all I'm wanting to know is if the guess is the same as the_number and below the number of tries available, you've done it. Otherwise, higher or lower :)
Hope this helps!
import random
print("\nWelcome to the guessing game 2.0")
print("Example for Stack Overflow!\n")
the_number = random.randint(1, 100)
tries = 0
for tries in range(10):
guess = int(input("Guess a number: "))
tries += 1
if guess == the_number and tries <= 10:
print("\nCongratulations! You've guessed it in", tries, "tries!")
break
elif guess < the_number and tries < 10:
print("Higher...")
tries += 1
elif guess > the_number and tries < 10:
print("Lower...")
tries += 1
elif tries >= 11:
print("\nI'm afraid to haven't got any tries left. You've exceeded the limit.")
import random
def display_title():
return print("Number Guessing Game")
def play_game():
cpu_num = random.randint(1, 10)
user_guess = int(input("Guess a number from 1 to 10:")
while user_guess != cpu_num:
print("Try Again")
user_guess = int(input("Guess a number from 1 to 10:"))
if user_guess == cpu_num:
print("Correct!")
def main():
title = print(display_title())
game = print(play_game())
return title, game
print(main())

How do I make this program loop indefinitely?

I want to loop this code indefinitely (until the user kills it) from the very beginning to the end, so I won't have to keep rerunning it. Is there anyway to make this possible? I would appreciate the help greatly.The program should restart itself after the user inputs "done" (and its printed all the details.)
print ("Input done when finished")
print ("Input thresholds")
maximumnum = int(input("Input maximum number: "))
minimumnum = int(input("Input minimum number: "))
minimum = None
maximum = None
while True:
inp =input("Enter a number: ")
if inp == "done":
break
try:
num = float(inp)
except:
print ("Invalid input")
continue
## ---- Additional Check ---- ##
if num > maximumnum:
print('Number greater the maximum allowed range')
break
if num < minimumnum:
print('Number smaller the maximum allowed range')
break
## -------------------------- ##
if minimum is None or num < minimum:
minimum = num
if maximum is None or num > maximum:
maximum = num
print ("Maximum:", maximum)
print ("Minimum:", minimum)
print ("Try again")
Why not just wrap the whole script in another while True? To stop, the user must kill the running process.
while True:
print ("Input done when finished")
print ("Input thresholds")
maximumnum = int(input("Input maximum number: "))
minimumnum = int(input("Input minimum number: "))
minimum = None
maximum = None
while True:
inp =input("Enter a number: ")
if inp == "done":
break
try:
num = float(inp)
except:
print ("Invalid input")
continue
## ---- Additional Check ---- ##
if num > maximumnum:
print('Number greater the maximum allowed range')
break
if num < minimumnum:
print('Number smaller the maximum allowed range')
break
## -------------------------- ##
if minimum is None or num < minimum:
minimum = num
if maximum is None or num > maximum:
maximum = num
print ("Maximum:", maximum)
print ("Minimum:", minimum)
print ("Try again")
I would wrap this on method and run that in infinite loop. Please try following:
def process_input(maximumnum, minimumnum):
minimum = None
maximum = None
while True:
inp =input("Enter a number: ")
if inp == "done":
break
try:
num = float(inp)
except:
print("Invalid input")
continue
## ---- Additional Check ---- ##
if num > maximumnum:
print('Number greater the maximum allowed range')
break
if num < minimumnum:
print('Number smaller the maximum allowed range')
break
## -------------------------- ##
if minimum is None or num < minimum:
minimum = num
if maximum is None or num > maximum:
maximum = num
return minimum, maximum
def main():
print("Input done when finished")
print("Input thresholds")
maximumnum = int(input("Input maximum number: "))
minimumnum = int(input("Input minimum number: "))
minimum, maximum = process_input(maximumnum, minimumnum)
print("Maximum:", maximum)
print("Minimum:", minimum)
print("Try again")
if __name__ == '__main__':
while True:
main()
Hope this helps.
I frequently use a paradigm such as this to accomplish a "loop until I say so"
sort of thing.
class UserKilledException(KeyboardInterrupt):
pass
try:
while True:
#do stuff
except UserKilledException:
#do cleanup here
Just have your code throw a UserKilledException whenever the user decides to close the application somehow. If it's a cli application then KeyboardInterrupt will do the trick.

Categories