Python. Variable in while loop not updating. - python

I'm very new to programming and I've encountered a problem with a basic guessing game I've been writing.
x is a random number generated by the computer. The program is supposed to compare the absolute value of (previous_guess - x) and the new guess minus x and tell the user if their new guess is closer or further away.
But the variable previous_guess isn't updating with the new value.
Any help would be appreciated.
Here is the code so far:
###Guessing Game
import random
n = 100
x = random.randint(1,n)
print("I'm thinking of a number between 1 and ", n)
##print(x) ## testing/cheating.
count = 0
while True:
previous_guess = 0 # Should update with old guess to be compared with new guess
guess = int(input("Guess the number, or enter number greater that %d to quit." % n))
count += 1
print(previous_guess)
print("Guesses: ", count)
if guess > n:
print("Goodbye.")
break
elif count < 2 and guess != x:
print("Unlucky.")
previous_guess = guess #####
elif count >= 2 and guess != x:
if abs(guess - x) < abs(previous_guess - x):
previous_guess = guess #####
print("Getting warmer...")
else:
previous_guess = guess #####
print("Getting colder...")
elif guess == x:
print("You win! %d is correct! Guessed in %d attempt(s)." % (x,count))
break

Your previous guess is being reinitialized every time you loop. This is a very common error in programming so it's not just you!
Change it to:
previous_guess = 0
while True:
#Rest of code follows
Things you should be thinking about when stuff like this shows up.
Where is your variable declared?
Where is your variable initialized?
Where is your variable being used?
If you are unfamiliar with those terms it's okay! Look em up! As a programmer you HAVE to get good at googling or searching documentation (or asking things on stack overflow, which it would appear you have figured out).
Something else that is critical to coding things that work is learning how to debug.
Google "python debug tutorial", find one that makes sense (make sure that you can actually follow the tutorial) and off you go.

You're resetting previous_guess to 0 every time the loop begins again, hence throwing away the actual previous guess. Instead, you want:
previous_guess = 0
while True:
guess = ....

You need to initialize previous guess before while loop. Otherwise it will be initialized again and again.
You have updated previous guess in multiple places. You can make it simpler:
import random
n = 100
x = random.randint(1,n)
print("I'm thinking of a number between 1 and ", n)
##print(x) ## testing/cheating.
count = 0
previous_guess = 0 # Should update with old guess to be compared with new guess
while True:
guess = int(input("Guess the number, or enter number greater that %d to quit." % n))
count += 1
print(previous_guess)
print("Guesses: ", count)
if guess > n:
print("Goodbye.")
break
elif count < 2 and guess != x:
print("Unlucky.")
elif count >= 2 and guess != x:
if abs(guess - x) < abs(previous_guess - x):
print("Getting warmer...")
else:
print("Getting colder...")
elif guess == x:
print("You win! %d is correct! Guessed in %d attempt(s)." % (x,count))
break
previous_guess = guess #####

You need to initialize previous guess before while loop Otherwise it will be initialized again and again. You have to set the value of previous guess to x the computer generator and when you move on after loop you have to update the previous guess to next simply like this:
Add before while { previous_guess = x }
Add After While { previous_guess += x }
###Guessing Game
import random
n = 100
x = random.randint(1,n)
print("I'm thinking of a number between 1 and ", n)
##print(x) ## testing/cheating.
count = 0
previous_guess = x
while True:
# Should update with old guess to be compared with new guess
previous_guess += x
guess = int(input("Guess the number, or enter number greater that %d to quit." % n))
count += 1
print(previous_guess)
print("Guesses: ", count)
if guess > n:
print("Goodbye.")
break
elif count < 2 and guess != x:
print("Unlucky.")
previous_guess = guess #####
elif count >= 2 and guess != x:
if abs(guess - x) < abs(previous_guess - x):
previous_guess = guess #####
print("Getting warmer...")
else:
previous_guess = guess #####
print("Getting colder...")
elif guess == x:
print("You win! %d is correct! Guessed in %d attempt(s)." % (x,count))
break
Picture When u win
Picture When u loose

Related

Working on a python problem trying to guess a randomly generated number im generally new to python and would appreciate some advice

having trouble when it trys comparing the input and the random integer
import random
target = random.randint(1,100)
counter = 0
print(target)
print(int(input('Guess an integer between 1 and 100 ')))
guess = input
while guess != target():
if guess > target():
print("Guess is to high")
elif guess < target():
print("Guess was to low")
counter = counter + 1
print(int(input('Guess an integer between 1 and 100 ')))
print("Correct it took you " + str(counter) + " guesses to get the correct number")
i tried changing the variable names starting from scratch several times googled tons of stuff but im lost and and confused and need an answer so please if you understand my problem id appreciate some advice
Problems:
print(int(input('Guess an integer between 1 and 100 '))) is reading a value, converting it to int, printing it, then throwing it away so your guesses are never used
guess = input is assigning the function input to guess (which is useless, and actively harmful when you get to comparing to target, since a function and an int are not orderable relative to one another); since you never reassign it, this never changes
target should never be called (replace every use of target() with target), it's an int, not a callable function
Minor: If possible, it's nicer to avoid duplicating code; the Python 3.8+ walrus operator (:=) lets you both read a value and compare in the while conditional, which avoids the need to double the input code
Fixing all of these gets:
import random
target = random.randint(1,100)
print(target)
counter = 1 # Start counter at 1, since we can't increment it if the input actually matches
# Walrus allows reading, assigning, and testing in a single line
while (guess := int(input('Guess an integer between 1 and 100 '))) != target:
if guess > target:
print("Guess is too high") # sp fix
elif guess < target:
print("Guess was too low") # sp fix
counter += 1 # Save a little typing by using counter += 1 instead of counter = counter + 1
# f-string saves manual string conversion and piecemeal concatenation
print(f"Correct it took you {counter} guesses to get the correct number")
You have several issues with your code:
You have print(int(input('Guess an integer between 1 and 100 '))) followed by guess = input. You are not assigning to guess what was entered but rather setting it to refer to a function.
In several places you have target(). But target is of type int, not a function, and you cannot call it as if it were a function.
After a user enters a guess, it narrow downs the range of legal guess and therefore your prompt should change accordingly.
You should check for guess outside the legal range.
import random
target = random.randint(1,100)
low = 1
high = 100
counter = 0
while True:
guess = int(input(f'Guess an integer between {low} and {high}: '))
if guess == target:
break
if not low <= guess <= high:
print('Your guess is outside the legal range of guesses.')
elif guess > target:
print("Guess is to high.")
high = guess - 1
else:
print("Guess was to low.")
low = guess + 1
counter = counter + 1
print("Correct! It took you", counter, "guesses to get the correct number.")
I have added new changes, get rid of # while guess != target
import random
target = random.randint(1,100)
counter = 0
print(target)
check=False
while not check:
guess = int(input('Guess an integer between 1 and 100 '))
if guess > target:
print("Guess is to high")
elif guess < target:
print("Guess was to low")
else:
check = True
break
counter = counter + 1
print("Correct it took you " + str(counter) + " guesses to get the correct number")enter code here
Try these changes,
import random
target = random.randint(1,100)
counter = 0
print(target)
guess = int(input('Guess an integer between 1 and 100 '))
while guess != target:
if guess > target:
print("Guess is to high")
elif guess < target:
print("Guess was to low")
counter = counter + 1
print("Correct it took you " + str(counter) + " guesses to get the correct number")
You do not to print when you ask for an input value, as that function will take care of printing the text you give it. You're also not updating guess after a new request. Try this instead:
import random
target = random.randint(1,100)
counter = 0
print(target)
guess = int(input('Guess an integer between 1 and 100 '))
while guess != target:
if guess > target:
print("Guess is to high")
elif guess < target:
print("Guess was to low")
counter = counter + 1
guess = int(input('Guess an integer between 1 and 100 '))
print("Correct it took you " + str(counter) + " guesses to get the correct number")

Python newbie does not understand why his comparison doesnt work

So i've set myself the goal of learning programming with Python. I've started about 3 days ago and decided to start with a random number generating game as a starting Project.
The problem i have with my code is that my make_try method isn't giving me the right outputs. It just always goes with the else statement, even if the comparison in the if statement should be right. I personally am very frustrated right now and i hope you can help me.
Greetings Marc
import random
class Test:
def __init__(self):
self.number1 = random.randrange(1, 20)
self.score = 100
def first_tip(self):
print(self.number1)
if(self.number1 % 2 == 0 and self.number1 <= 10):
print("Your number is even and smaller than 10")
elif(self.number1 % 2 == 0 and self.number1 >= 10):
print("Your number is even and bigger than 10")
elif(self.number1 % 2 != 0 and self.number1 <= 10):
print("Your number is uneven and smaller than 10")
elif(self.number1 % 2 != 0 and self.number1 >= 10):
print("Your number is uneven and bigger than 10")
def make_try(self):
print("My guess would be:")
testguess = input()
if(self.number1 == testguess):
new_score = self.score + 100
print("*****************")
print("*Congratulations*")
print("*****************")
print(f"Your final score: {new_score}")
else:
new_score = self.score -10
print("Wrong!")
print(f"Your new score: {new_score}")
x = input("Try again?(Yes/No)")
print(x)
if __name__ == "__main__":
T1 = Test()
T1.first_tip()
T1.make_try()
You have different types in your comparison
testguess = input() means that testguess is a string
self.number1 = random.randrange(1, 20) means that self.number1 is an integer
simplest way to fix this is by: testguess = int(input())
Problem is input types, thats why as a newbie I would probably recommend C# or C++ bc you have more or total control over your types,
To fix this problem of your I simply added a cast to this line, and it works properly
if(self.number1 == int(testguess)):

How can i stop a for-loop iterating when the input is not valid? (not allowed to use a while loop) - Python

for i in range (0, 3):
print() # When iterates creates a space from last section
raw_mark = int(input("What was student: " + str(student_id[i]) + "'s raw mark (0 - 100)?: "))
days_late = int(input("How many days late was that student (0 - 5)?: "))
penalty = (days_late * 5)
final_mark = (raw_mark - penalty)
# Selection for validation
if 0 <= raw_mark <= 100 and 0 <= days_late <= 5 and final_mark >= 40:
print("Student ID:", str(student_id[i]))
print() # Spacing for user readability
print("Raw mark was:", str(raw_mark),"but due to the assignment being handed in",
str(days_late),"days late, there is a penalty of:", str(penalty),"marks.")
print()
print("This means that the result is now:", final_mark,"(this was not a capped mark)")
elif 0 <= raw_mark <= 100 and 0 <= days_late <= 5 and final_mark < 40: # Final mark was below 40 so mark must be capped
print("Student ID:", str(student_id[i]))
print()
print("Raw mark was:", str(raw_mark),"but due to the assignment being handed in",
str(days_late),"days late, there is a penalty of:", str(penalty),"marks.")
print()
print("Therefore, as your final mark has dipped below 40, we have capped your grade at 40 marks.")
else:
print("Error, please try again with applicable values")
At the else i would like the loop to loop back through but not having iterated i to the next value, so that it can be infinite until all 3 valid inputs are entered... cannot use a while loop nor can i put the if - elif- else outside the loop. Nor can i use a function :(
You can have your for loop behave like a while loop and have it run forever and implement your i as a counter. Then the loop can be terminated only if it ever hits 3 (or 2 so that you indices dont change), while otherwise it is set back to 0:
cnt_i = -1
for _ in iter(int, 1):
cnt_i += 1
if ...
else:
cnt_i = 0
if cnt_i == 2:
break
But seriously, whatever the reason for not using a while loop, you should use it anyhow..
Try something like this. You can keep track of the number of valid inputs, and only stop your loop (the while) once you hit your target number.
valid_inputs = 0
while valid_inputs <= 3:
...
if ...:
...
elif ...:
...
else:
# Immediately reset to the top of the while loop
# Does not increment valid_inputs
continue
valid_inputs += 1
If you really cannot use a while loop...
def get_valid_input():
user_input = input(...)
valid = True
if (...): # Do your validation here
valid = False
if valid:
return user_input
else:
return get_valid_input()
for i in range (0, 3):
input = get_valid_input()
# Do what you need to do, basically your program from the question
...
...
There are some additional gotchas here, as in you need to worry about the possibility of hitting the maximum recursion limit if you keep getting bad input values, but get_valid_input should ideally only return when you are sure you have something that is valid.
You can put the input statement inside while loop containing try block.
for j in range(3): # or any other range
try:
raw_mark = int(input("What was student: " + str(student_id[i]) + "'s raw mark (0 - 100)?: "))
days_late = int(input("How many days late was that student (0 - 5)?: "))
break
except:
pass

How do I make my program check whether user input is within 5,10,15,20, etc of the random integer?

import random
print("Pick a number from 1-50")
randomNumber = random.randint(1,50)
correct = False
while not correct:
try:
userInput = int(input("Insert your number here. "))
except ValueError:
print("That is not a Number!")
continue
if userInput > randomNumber:
print("Guess lower.")
elif userInput < randomNumber:
print("Guess Higher.")
else:
print("You got it!")
break
So this code currently takes the user input and says whether the user guessed the random integer, or if they should guess higher/lower. I want to edit the code to now say whether the user input is within 5,10,15, etc of the random integer.
So if the random integer was 30, and the user inputs 20, the program would say something like "You are within 10; guess higher."
Any advice? I'm extremely new to python, so please respond with more simple methods if possible.
Thanks.
PS: Oh, preferably without the use of modules, mainly because I'm still learning.
I think this does what you want, and it cuts down on the if chains a little:
import random
print("Pick a number from 1-50")
randomNumber = random.randint(1,50)
correct = False
while not correct:
try:
userInput = int(input("Insert your number here. "))
except ValueError:
print("That is not a Number!")
continue
if randomNumber == userInput: # Let's check this first!
print ("YOU WIN!!!")
break # We use break b/c changing correct would still run rest of loop
acceptable_ranges = [5, 10, 15, 20, 25, 30, 25, 40, 45, 50]
guess_error = userInput - randomNumber
i = 0
while abs(guess_error) > acceptable_ranges[i]: # see how close they are
i += 1
if guess_error < 0: # let's figure out where they need to go
next_guess_direction = "higher"
else:
next_guess_direction = "lower"
print (("You are within %i: Please guess %s")
%(acceptable_ranges[i], next_guess_direction))
Let's look. at the last if statement a little further and the final print line. We are checking to see if guess_error, defined above (line 15) guess_error = userInput - randomNumber is less than 0 (negative). If it is less than zero, then we make the variable next_guess_direction equal to the string "higher," because the next guess needs to be larger than the last one (randomNumber was larger than userInput. If guess_error is not negative, then it is positive, because we already eliminated the we eliminate the possibility of 0 using:
if randomNumber == userInput: # Let's check this first!
print ("YOU WIN!!!")
So, if guess_error is positive, we know that userInput was larger than randomNumber and we set next_guess_direction equal to the string "lower." Finally, we print out everything that we have found:
print (("You are within %i: Please guess %s")
%(acceptable_ranges[i], next_guess_direction))
I am using an older version of formatting where %i and %s are placeholders for integer and string, respectively. I then define what should be formatted there using %(acceptable_ranges[i], next_guess_direction), which simply means to put acceptable_ranges[i] in for the integer and next_guess_direction in for the string. Keep in mind, we found i in acceptable_ranges[i] right above the if statement.
I know that is all long, but I did not know how much detail you needed!
Update: I see you ask to do it without modules. Here's a solution:
def ceil(xx):
if int(xx) < xx:
return int(xx) + 1
else:
return int(xx)
def generate_response(actual, guess, interval=5):
diff_interval_units = (guess - actual) / float(interval)
within = ceil(abs(diff_interval_units)) * interval
response = "You are within %d" % within
if diff_interval_units > 0:
response += "; guess lower"
elif diff_interval_units < 0:
response += "; guess higher"
return response
-- original answer:
You can do this with numpy's ceil function.
For instance:
import numpy as np
def generate_response(actual, guess, interval=5):
diff_interval_units = (guess - actual) / np.float(interval)
within = np.ceil(np.abs(diff_interval_units)) * interval
response = "You are within %d" % within
if diff_interval_units > 0:
response += "; guess lower"
elif diff_interval_units < 0:
response += "; guess higher"
return response
A solution using the modulo operator:
import random
randomNumber = random.randint(0,100)
def guess(divisor = 5):
while 1:
try:
print("Pick a number from 0-100")
userInput = int(input("Insert your number here: "))
except ValueError:
print("That is not a Number!")
continue
delta = randomNumber - userInput
if delta == 0:
print("You got it!")
return
remainder = delta % divisor
# this takes advantage of python truncating non-floating point numbers
rounded_delta = (abs(delta) / divisor) * divisor + divisor * bool(remainder)
high_or_low = 'higher' if delta > 0 else 'lower'
print("You are within %s. Guess %s." % (rounded_delta, high_or_low))

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