While loop spamming output instead of printing output once? - python

I'm making a regular guess the number game. I'm having problems when I enter the guess and the program spams lower or higher instead of just typing it once, since I'm using a while True loop.
Here I'm just opening the CSV file and picking a random number.
import random
numbers = open('numbers_1-200.csv').read().splitlines()
number = int(random.choice(numbers))
Here I'm importing numbers 1-50 and picking two random numbers which will be what's added and subtracted from the original number. So the computer can write two numbers where the original number is between.
I know I could have just made the program pick two numbers from the first fifty lines in the same CSV that includes numbers from 1-200 but I choose to make another CSV which only had the numbers 1-50.
differences = open('numbers_1-50').read().splitlines()
difference = int(random.choice(differences))
difference2 = int(random.choice(differences))
clue = number + difference
clue2 = number - difference2
This is my welcome screen which also includes the main program on the last row¨
def welcome_screen():
print('The number is between ' + str(clue) + ' and ' + str(clue2))
print('Guess the number: ')
guess_the_number()
This is my loop where you guess the number
def guess_the_number():
guess = int(input())
while True:
if guess == number:
print('Correct! The number was' + str(number))
break
elif guess > number:
print('Lower')
elif guess < number:
print('Higher')
I'm getting outputs like these:
The number is between 45 and 97
Guess the number: 72
lower
lower
lower
lower
lower
lower
lower
lower
How can I get a output where it just says "lower" (or "higher") one time and then I can guess again?

Just move the input function inside the while loop:
def guess_the_number():
while True:
guess = int(input())
if guess == number:
print('Correct! The number was' + str(number))
break
elif guess > number:
print('Lower')
elif guess < number:
print('Higher')

def guess_the_number():
while True:
guess = int(input())
if guess == number:
print('Correct! The number was' + str(number))
break
elif guess > number:
print('Lower')
elif guess < number:
print('Higher')

Related

Why does my program stop after 3 wrong guesses? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
So i'm new to programming and I was trying to make a 'guess the number' program but it stops after 3 wrong guesses. I'm probably doing something really stupid so sorry if the question sounds dumb.
Thanks in advance
from random import *
number = randrange(1,100)
guess = int(input('Guess the number (between 1-100)'))
if guess == number:
print('Well done!')
while guess > number:
print('Lower')
guess = int(input('Try again: '))
while guess < number:
print('Higher')
guess = int(input('Try again: '))
By having the three cases (equal, more than, less than) handled in separated blocks, once you get past one, you don't come back to it. For instance, the program checks for equality only once, and if it fails the first time, then it never checks again. You should put all three in one block.
from random import *
number = randrange(1,100)
max_attempts = 100
for attempt in range(max_attempts):
guess = int(input('Guess the number (between 1-100)'))
if guess == number:
print('Well done!')
break
if guess > number:
print('Lower')
continue
if guess < number
print('Higher')
continue
break means to stop the loop, and continue means to go on to the next iteration of the loop. I used a for-loop since that is guaranteed to halt.
As soon as you break out of a while loop, you can not revisit that loop again. I.E for while guess > number, as soon as the user guesses a number that is <= number then you will break out the loop and the program will move past it.
Instead use this code:
from random import *
number = randrange(1,100)
guess = int(input('Guess the number (between 1-100)'))
while guess != number:
if guess < number:
print('Higher')
else:
print('Lower')
guess = int(input('Try again: '))
print('Well done!')
This program runs the while loop when guess != number. This condition will break when guess != number is False, or in other words, when the user guesses the correct number.
You need to change the while loops to this:
while guess != number:
if guess > number:
print('Higher')
guess = int(input('Try again: '))
elif guess < number:
print('Lower')
guess = int(input('Try again: '))
Basically, previously, if the guess is smaller that the number, it starts the while loop, while guess < number However, when the guess is bigger, the while loop stops because the guess is no longer smaller than the number.
To fix this, create one while loop and, in that, check to see in the guess is bigger or smaller than the number.
You could therefore, remove the guess from each if statement, and put it at the end of the while loop, if that makes sense, like this:
while guess != number:
if guess > number:
print('Lower')
elif guess < number:
print('Higher')
guess = int(input('Try again: ')
Using multiple while loops makes your debugging more complicated without any gain.
I would suggest you to use a single while loop:
from random import *
number = randrange(1,100)
guessed = False
while not guessed:
guess = int(input('Guess the number (between 1-100)'))
if guess > number:
print('Lower')
elif guess < number:
print('Higher')
else:
print('Well done!')
guessed = True
I'm not very much of a programmer neither but I Have been using python regularly lately , although i'm not sure what causes this problem , you can try this alternative code that worked pretty well for me :
from random import *
number = randrange(1,100)
guess = int(input('Guess the number (between 1-100)'))
while True:
if guess > number:
print('Lower')
guess = int(input('Try again: '))
elif guess < number:
print('Higher')
guess = int(input('Try again: '))
else:
print('Well done!')
break

Trouble with an assignment

I am doing an assignment for school where I need to make a list and assign 4 random integers to the list between 1 and 9. Then, I need to prompt the user for what their guess is for each value. If they get any of the numbers right, I need to say how many, but I've been working on this for like 3 hours and I'm getting nowhere. Currently, all I have is a massive useless nested if/elif statements.
This is the assignment prompt:
Program Specifications:
Computer should generate 4 random numbers from 1 - 9 as the "Secret Code".
User should be prompted for their guess of those four numbers.
After they provide their full guess, the user is told how many are correct.
As long as the user does not get all four correct, they keep getting asked for their guess.
After the user finally gets all of them correct (yes - all four), they are congratulated and then told how many tries it took them.
Technical Requirements:
Use at least one list
Use at least one function with parameters
I'm so confused and I don't know where to start. Here is my current code:
import random
count = 0
guess1 = 1
guess2 = 1
guess3 = 1
guess4 = 1
def getGuess(count,guess1,guess2,guess3,guess4):
while True:
guess1 = input("What is your guess for the first number? ")
guess2 = input("What is your guess for the second number? ")
guess3 = input("What is your guess for the third number? ")
guess4 = input("What is your guess for the fourth number? ")
if str(guess1) == numbers[0] and str(guess2) == numbers[1] and str(guess3) == numbers[2] and str(guess4) == numbers[3]:
print("Your first, second, third, and fourth numbers are correct!")
elif guess1 == numbers[0] and guess2 == numbers[1] and guess3 == numbers[2]:
print("Your first, second, and third numbers are correct!")
elif guess1 == numbers[0] and guess2 == numbers[1]:
print("Your first and second number are correct!")
elif guess1 == numbers[0]:
print("Your first number is correct!")
elif guess2 == numbers[1]:
print("Your second number is correct!")
elif guess2 == numbers[1] and guess3 == numbers[2]:
print("Your second and third numbers are correct!")
elif guess2 == numbers[1] and guess3 == numbers[2] and guess4 == numbers[3]:
print("Your second, third, and fourth numbers are correct!")
elif guess3 == numbers[2]:
print("Your third number is correct!")
elif guess3 == numbers[2] and guess4 == numbers[3]:
print("Your third and fourth numbers are correct!")
elif guess4 == numbers[3]:
print("Your fourth number is correct!")
else:
print("None of your numbers are correct. Try again.")
numbers = []
for i in range(4):
num = int(random.randrange(1,9))
numbers.append(num)
print(numbers)
getGuess(count,guess1,guess2,guess3,guess4)
I see your attempt so I'm going to tell you the problems, as comments said:
Logic flow: your if else statement are serving 4 numbers, what if 10, 100 numbers? It should be generic
You are comparing string with integer, should cast it
Should package your variables inside your function. Which is very ambiguous of guess1 = 1, guess1 function variable, guess1 from input,...
Init random numbers
import random
numbers = []
for i in range(4):
num = int(random.randrange(1,9))
numbers.append(num)
getGuess function, which is getting guess numbers from input string, then split it and convert to int.
def getGuess(numbers):
retryCount = 0
while True:
# You can put try catch here for number validation
guessNums = [int(x) for x in input("Numbers: ").split()]
# To make sure your input must be the same length
if len(guessNums) != len(numbers):
print('Not available numbers')
continue
# Here we just check for incorrect, once it's met, the for loop will be broken and go to the next while loop
isIncorrect = False
for index, num in enumerate(numbers):
if num != guessNums[index]:
isIncorrect = True
retryCount += 1
print('Order of ' + str(index + 1) + ' is incorrect')
break
# When every number is equal, not incorrect occured, return retry count
if isIncorrect == False:
return retryCount
Using:
print('Your retry count: ' + str(getGuess(numbers)))
You can optimize many of the parts of your code.
Assumption: You know how to use lists as you are already using numbers as a list. I am staying away from dictionary. Not sure if you know its use. Also assume you understand list comprehension. If you dont, see this link on list comprehension.
Now let's look at your code. Here are a few things to consider:
You don't need 4 variables to store the 4 input values. You can use a list and store all 4 of them there.
As many have already suggested, you should convert the input value into an integer. When you convert string to integer, there is a potential that the string is not an integer. This can result in code getting broken. So use Try Except to catch the error while converting to int
Your random.randrange(1,9) will create integers. So you dont have to explicitly convert them back to integer.
You have 4 inputs and 4 values to compare. You can map each value to the position and compare. That will reduce the complexity. For the ones that are successful, keep a tab of it. Then print the ones that matched. Again, this can be done using a list or dictionary.
With all that to consider, I have re-written your code as follows. See if this helps you with the solution.
import random
nums = [random.randrange(1,9) for _ in range(4)]
def getGuess():
g = ['first','second','third','fourth']
i = 0
gx = []
while i<4:
try:
x = int(input(f"What is your guess for the {g[i]} number? :"))
gx.append(x)
i+=1
except:
print ('Not numeric, please re-enter')
gwords = [g[i] for i in range(4) if nums[i] == gx[i]]
if gwords:
if len(gwords) == 1:
resp = "Your " + gwords[0] + ' number is correct!'
else:
resp = "Your " + ', '.join(gwords[:-1]) + ' and ' + gwords[-1] + ' numbers are correct!'
print (resp)
else:
print ("None of your numbers are correct. Try again.")
getGuess()
Here's an example run of the above code:
What is your guess for the first number? :1
What is your guess for the second number? :6
What is your guess for the third number? :5
What is your guess for the fourth number? :4
Your second, third and fourth numbers are correct!

what is causing reference before assignment errors in below code?

I'm getting this error with refrenced before assignment and im not sure how to fix it.
I havent tried anything at the moment. It would be appreciated if this could be answered. (im just trying to fill up more words so it can be posted)
this is the error code i am getting:
number = int(number)
UnboundLocalError: local variable 'number' referenced before assignment
And this is the rest of my code
import random
import sys
again = True
while True:
myName = input('Hello, Enter your name to get started')
if myName.isdigit():
print('ERROR,Your Name is not a number, please try again')
print('')
continue
break
myName = str(myName.capitalize())
print('')
print('Hi {}, This is Guessing Game, a game where you have a certain amount of attempts to guess a randomly generated number. Each level has a different amount of attempts and a higher range of number. After each guess, press enter and the program will determine if your guess is correct or incorrect.' .format (myName))
print('--------------------------------------------------------------------------------')
while True:
level = input('{}, Please select a level between 1 and 3. Level 1 being the easiest and 3 being the hardest')
if not level.isdigit():
print('Please enter a number between 1 and 3. Do not enter a number in word form')
continue
break
def guessNumber(): # Tells the program where to restart if the user wants to play again
guessesTaken = 0
List = []
if level == 1:
number = random.randint (1, 16)
print('You chose Level 1, Guess a number a between 1 and 16, you have 6 guesses.')
allowedGuesses = 6
boundary = 16
if level == 2: # The code for level 2
number = random.randint (1,32)
print('You chose Level 2, Guess a number between 1 and 32, You have 8 guesses.')
allowedGuesses = 8
boundary = 32
if level == 3:
number = random.randint (1, 40)
print('You chose Level 3, Guess a number between 1 and 40, you have 10 guesses.')
allowedGuesses = 10
boundary = 40
if level == 4:
number = random.randint (1, 50)
print('You chose Level 4, Guess a number between 1 and 50, you have 10 guesses.')
allowedGuesses = 10
boundary = 50
if level == 5:
number = random.randint (1, 60)
print('You chose Level 5, Guess a number between 1 and 60, you have 10 guesses.')
allowedGuesses = 10
boundary = 60
guess = input()
guess = int(guess)
while guessesTaken < allowedGuesses:
guessesTaken = guessesTaken + 1
guessesLeft = allowedGuesses - guessesTaken
if guess < number:
List.append(guess)
print('Your guess is too low, You must guess a higher number, you have {} guesses remaining. You have guessed the numbers {}, Take another guess' .format (guessesLeft, List))
if guess > number:
List.append(guess)
print('Your guess is too high, You must guess a lower number, you have {} guesses remaining. You have guessed the numbers {}, Take another guess' .format (guessesLeft, List))
if guess > boundary:
List.append(guess)
print('You must input a number between 1 and 16. You have {} guesses remaining. You have guessed the numbers {}, Take another guess' .format (guessesLeft, List))
if guess == number:
List.append(guess)
print('Good Job {}!, You guessed my number in {} guesses. You guessed the numbers {}.' .format (myName, guessesTaken, List))
print('Your high score for your previous game was {}' .format(guessesTaken))
else:
number = int(number)
print('')
print('--------------------------------------------------------------------------------')
print('Sorry {}, Your gueses were incorrect, The number I was thinking of was {}. You guessed the numbers {}.' .format(myName, number, List))
guessNumber()
print('')
print('It is recommended to pick a harder level if you chose to progress')
print('')
while True:
again = input('If you want to play again press 1, if you want to stop playing press 2')
if not again.isdigit():
print('ERROR: Please enter a number that is 1 or 2. Do not enter the number in word form')
continue
break
if again == 1:
level + 1
guessNumber()
if again == 2:
print('Thanks for playing Guessing Game :)')
sys.exit(0)
In your code you are getting level as input and checking that if level is in between 1 to 5.
else you are trying number = int(number)
but you should write number = int(level).
Since level is a string rather than a number, none of the conditions like
if level == 1:
will succeed. So none of the assignments like number = random.randint (1, 16) ever execute, and number is never assigned.
Since if level == 5: doesn't succeed, it goes into the else: block, which starts with
number = int(number)
Since none of the other number assignments took place, this tries to use int(number) before the variable has been assigned, which doesn't work.
I'm not sure why you even have this assignment there. When number is assigned, it's always set to an integer, so there's no need to use int(number).
You need to use
level = int(level)`
after you confirm that it contains digits. And you need to do similarly with again.
There are a number of other problems with your code. For instance, the code that asks for the user's guess and checks it is inside the if level == 5: block, it should run in all the levels.
When you have a series of mutually exclusive tests, you should use elif for each successive test. If you just use if for each of them, and then use else: at the end, that else: will only apply to the last test, so it will be executed even if one of the early tests also succeeded.

How to fix guessing game

The objective is to create a simple program that generates a number between 1 and 100, it will then ask the user to guess this, if they guess outside of the number range it should tell them to guess again, if not it should tell them whether their guess was too high or too low, prompting them to guess again. Once they do guess the correct number it should tell them they've won and the number of tries it took for them to guess it correctly.
Here is what I have so far
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 1
while True:
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
#the age is valid
return play_game
else:
print("Invalid number.")
return play_game()
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
return
count+=1
play_game()
The issue I'm currently running into is when it checks to see if their guess was between 1-100 instead of moving on to weather or not their number was too how or to low, it stays and loops.
If anyone could help me with this issue and review the code in general I'd appreciate it.
I think the problem is with some indentation and some logical problems in the flow.
When you call play_game() from inside the game, it starts a completely different game
with different random_number.
A good code that satisfies your condition might look like the following
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 1
while True:
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
return
count+=1
else:
print("Invalid number.")
play_game()
You could re-adjust your code:
1. if no. within range, run your high, low, match checks
2. break if guess matches the no
import random
def play_game():
number = random.randint(1, 100)
print("Guess a number between 1 and 100 inclusive.")
count = 0
while True:
count += 1
guess = int(input("Your guess: "))
if guess > 0 and guess <= 100:
#the age is valid
if guess < number:
print("Too low.")
elif guess > number:
print("Too high.")
elif guess == number:
print("You won! You guessed it in " + str(count) + " tries.\n")
break
else:
print("Invalid number, try again")
play_game()
The issue you are running into is because of incorrect indentation. The if-else statements that check whether the number is within the valid range are at the same indentation level as the while loop and thus are not executed within it. Simply indenting should fix the problem.
Furthermore, you have called play_game without parenthesis, making it incorrect syntax for a function call. However, rather than checking if the number is greater than 0 and lesser than 100, it would more optimal to check whether number is lesser than 0 or greater than 100, and if that is the case, print invalid number and call play_game().
It would look something like this:
while True:
if guess < 0 and guess > 100:
print ("Invalid number.")
return play_game()
The rest of your code looks good. I've also attached the link on the section of indentations of the Python documentation here.

I want to loop 100 times but not print 100 times in the loop (Python)

for lp in range(100):
if guess == number:
break
if guess < number:
print "Nah m8, Higher."
else:
print "Nah m8, lower."
This is some basic code that I was told to make for a basic computing class. My aim is to make a simple 'game' where the user has to guess a random number that the computer has picked (1-100) This is a small section of the code where I want to continue checking if the guess is equal to, lower or higher than the number; but if I put a print statement below, it will print the text 100 times. How can I remove this problem?
Thanks in advance.
It seems like you're omitting the guessing stage. Where is the program asking the user for input?
Ask them at the beginning of the loop!
for lp in range(100):
guess = int(input('Guess number {0}:'.format(lp + 1)))
...
You need to get a new input each time through your loop; otherwise you just keep checking the same things.
for lp in range(100):
if guess == number:
break
if guess < number:
# Get a new guess!
guess = int(raw_input("Nah m8, Higher."))
else:
# Get a new guess!
guess = int(raw_input("Nah m8, lower."))
You should ask for a guess inside the loop:
while True:
guess = int(raw_input("Guess: "))
if guess == number:
break
if guess < number:
print "Nah m8, Higher."
else:
print "Nah m8, lower."
import random
number = 0
x = []
while number < 100:
guess = random.randint(1,100)
if number < guess:
print(f 'Number {number} is less than guess {guess}')
elif number > guess:
print(f 'Number {number} is greater than guess {guess}')
number += 1
This will work for you

Categories

Resources