My "while loop" not working as expected - python

I am a new coder, sorry if my question is bad or I am not following proper etiquette!
I am designing a basic program that rolls dice. It is supposed to roll dice until the total points of either the computer or the user equals 100. However, even though my point totaler is working, the loop won't end. Anyone know why this is? Thank you!
def main():
GAME_END_POINTS = 100
COMPUTER_HOLD = 10
is_user_turn = True
user_pt = 0
computer_pt = 0
welcome()
while computer_pt < GAME_END_POINTS or user_pt < GAME_END_POINTS:
print_current_player(is_user_turn)
if is_user_turn is True:
user_pt = user_pt + take_turn(is_user_turn, COMPUTER_HOLD)
elif is_user_turn is False:
computer_pt = computer_pt + take_turn(is_user_turn, COMPUTER_HOLD)
report_points(user_pt, computer_pt)
is_user_turn = get_next_player(is_user_turn)

The condition is always True because either the computer or the user will have a points total less than 100.
Instead of or use and:
while computer_pt < GAME_END_POINTS and user_pt < GAME_END_POINTS:
Now the loop will continue only when both the user and the computer have a points total less than 100. As soon as one of them has more than 100 the condition will be be False and the loop will terminate.

You while loop will only end if both computer_pt >= GAME_END_POINTS and user_pt >= GAME_END_POINTS. Are you sure that those two variables satisfy those two conditions?

you can print computer_pt and user_pt in the loop to see what happened in this two variable, then you will find the answer by your self.
Print variable in loop is a common way to debug your code.

Related

false if statements being called/variable not being assigned?

I wasn't too sure what to call this post.
Anyways, what I'm trying to do is assign 'diff' to a user input, and if 'diff' is not average or advanced, recall the function so that the user can (hopefully) enter average or advanced.
However, no matter what I input, it will always recall the function, even if the input is 'average' or 'advanced'.
Code -
def choices():
global diff
diff = input("Choose a difficulty: Average/Advanced ")
diff = diff.lower()
x = 0
while x > 1:
if diff == 'average':
print('Difficulty set to average.')
x = x + 1
elif diff == 'advanced':
print('Difficulty set to advanced.')
x = x + 1
if diff != 'average' or 'advanced':
print('Your input is invalid. Please try again.')
choices()
choices()
The same thing is also happening for another decision I have that is similar to this, but I figured that there's no point in putting it down if it follows the same logic.
Sorry if this is a stupid question. I'm only a beginner.
You can also wrap it all into the while loop, I'm new to python but spawning recursive instances of a function seems dangerous to me.
def choices():
global diff
while true:
diff = input("Choose a difficulty: Average/Advanced ")
diff = diff.lower()
if diff == 'average':
print('Difficulty set to average.')
return
if diff == 'advanced':
print('Difficulty set to advanced.')
return
print('Your input is invalid. Please try again.')
Your first bug lies in this statement:
while x > 1:
You'll never execute the code within that loop because you set x = 0 at the top of the function. When it hits the while loop, x = 0 and so the while loop will be completely skipped.
There are a number of other problems, but this one is what's stopping the "if" logic from running.
I'm so confused about this function that I can't determine exactly what you're trying to do so I can't supply a complete working solution to your problem, only the first rather large bug in it.

Break out of Loop but Still make Loop Useable

I'm a beginner to Python, so this might sound pretty easy.
Anyway, I'm a little confused on when to use break, pass, or continue. I want to have a loop where it breaks out of it, but then after all the code runs again, then the loop will run again. This is some example code:
score = 100
while True:
score + 1
# break, continue, or pass
score - 30
Basically, what I want to happen is have score go up by 1, then have it go down by 30, and then keep going up by 1.
How can I achieve this? Thanks in advance!
score = 100
first = True
while True:
while True:
score += 1
if first:
first = False
break
score -= 30

Loop and validation in number guessing game

I have previously studied Visual Basic for Applications and am slowly getting up to speed with python this week. As I am a new programmer, please bear with me. I understand most of the concepts so far that I've encountered but currently am at a brick wall.
I've written a few functions to help me code a number guessing game. The user enters a 4 digit number. If it matches the programs generated one (I've coded this already) a Y is appended to the output list. If not, an N.
EG. I enter 4567, number is 4568. Output printed from the list is YYYN.
import random
def A():
digit = random.randint(0, 9)
return digit
def B():
numList = list()
for counter in range(0,4):
numList.append(A())
return numList
def X():
output = []
number = input("Please enter the first 4 digit number: ")
number2= B()
for i in range(0, len(number)):
if number[i] == number2[i]:
results.append("Y")
else:
results.append("N")
print(output)
X()
I've coded all this however theres a few things it lacks:
A loop. I don't know how I can loop it so I can get it to ask again. I only want the person to be able to guess 5 times. I'm imagining some sort of for loop with a counter like "From counter 1-5, when I reach 5 I end" but uncertain how to program this.
I've coded a standalone validation code snippet but don't know how I could integrate this in the loop, so for instance if someone entered 444a it should say that this is not a valid entry and let them try again. I made an attempt at this below.
while myNumber.isnumeric() == True and len(myNumber) == 4:
for i in range(0, 4)):
if myNumber[i] == progsNumber[i]:
outputList.append("Y")
else:
outputList.append("N")
Made some good attempts at trying to work this out but struggling to patch it all together. Is anyone able to show me some direction into getting this all together to form a working program? I hope these core elements that I've coded might help you help me!
To answer both your questions:
Loops, luckily, are easy. To loop over some code five times you can set tries = 5, then do while tries > 0: and somewhere inside the loop do a tries -= 1.
If you want to get out of the loop ahead of time (when the user answered correctly), you can simply use the break keyword to "break" out of the loop. You could also, if you'd prefer, set tries = 0 so loop doesn't continue iterating.
You'd probably want to put your validation inside the loop in an if (with the same statements as the while loop you tried). Only check if the input is valid and otherwise continue to stop with the current iteration of your loop and continue on to the next one (restart the while).
So in code:
answer = [random.randint(0, 9) for i in range(4)]
tries = 5
while tries > 0:
number = input("Please enter the first 4 digit number: ")
if not number.isnumeric() or not len(number) == len(answer):
print('Invalid input!')
continue
out = ''
for i in range(len(answer)):
out += 'Y' if int(number[i]) == answer[i] else 'N'
if out == 'Y' * len(answer):
print('Good job!')
break
tries -= 1
print(out)
else:
print('Aww, you failed')
I also added an else after the while for when tries reaches zero to catch a failure (see the Python docs or maybe this SO answer)

Can someone tell me why this wont loop?

I'm making a number guessing game and can someone tell me why it wont work properly?
import random
import time
time.time()
count=0
a = random.randint(0,100)
b = int(input("What number will you guess?"))
while b != a:
if b > a:
print("TOO BIG")
count = count + 1
elif b < a:
print("TOO SMALL")
count = count + 1
else b == a:
print("YOU WIN")
count = count + 1
time=time.time()
print("You took",count,"tries")
print("It took you",time,"second")
The reason this isn't working properly is because you're calling b = input outside of your while loop. As it stands, the user will be asked a single time what their guess is, then the loop will just move infinitely, because b is never being modified.
This loop will accomplish more what you want:
a = random.randint(0,100)
b = -1
while b != a:
b = int(input("What number will you guess?"))
A few notes, though:
Firstly, as Lee Daniel Crocker points out, the user will actually never see "YOU WIN", because you've structured your if-elif-else statement incorrectly. else by definition cannot have a condition - it exists purely in exclusion to all other conditionals in the same block. Additionally, your else statement is the opposite of your while condition. When that else becomes true, the loop exits. You'll need to handle printing "YOU WIN" somewhere else.
Second, you're not validating the user's input in any way - if they enter 'a', the program will crash, because you can't cast 'a' to an int. Either add an exception handler (for ValueError) or using isdigit() on the string, then casting it.
Third, you're not using time.time() correctly - you need to subtract the time at which the user wins from the time at which they started, then represent that value, which is in seconds, in some meaningful way. As it stands you're telling each player that they took the number of seconds since the beginning of the UNIX epoch to complete the game.
Also, for usability reasons, you should probably provide the user some way to break out - a string like "QUIT" - because as it stands, the only way to restart/quit is to either close the application or KeyboardInterrupt.
You need to accept input in the loop. Move the line b = int(input("What number will you guess?")) within the loop.

How can I improve this loop?

Once again, i'm still getting the hang of python. I made a program that has the user guess a 'magic number', randomly generated by the computer. After 5 incorrect tries, it provides a hint in the form of an addition problem using two randomly generated variables whose sum is equal to the magic number.
This is the code:
def moot():
count = 0
# magicNumber is the randomly generated number from 1 to 100 that must be guessed
magicNumber = random.randint(1,100)
var1 = 0
var2 = 0
guess = eval(input('Enter a number: '))
# This loop sets random values for var1 and var2 that sum up to the magicNumber
while var1 + var2 != var:
var2 = random.randint(1,100)
var3 = random.randint(1,100)
# an addition problem is made from var1 and var2 to be used as a hint later
hint = 'Try adding '+ str(var1)+ ' and '+ str(var2)+'\n'
# withinRange checks to see if the users guess is (valid) within the range of 1 to 100
# if not, asks for another number until a valid one is provided
withinRange = True if (guess <= 100 and guess >= 1) else False
while not withinRange:
count = count + 1
guess = eval(input('Number is invalid.Enter a number between 1 and 100: '))
withinRange = True if (guess <= 100 and guess >= 1) else False
# rng tells the user if his guess is too high or low
rng = 'low' if guess < magicNumber else 'high'
# the following loop repeatedly asks for input until the user enteres the majicNumber
while magicNumber != guess:
count = count + 1
print('\nThats incorrect. Your number is too',rng,end='\n')
# after 5 incorrect guesses the program prints out the addition problem that
# was made using var1 and var2
if count > 5:
print(hint)
guess = eval(input('Guess: '))
withinRange = True if (guess <= 100 and guess >= 1) else False
while not withinRange:
count = count + 1
guess = eval(input('Nope, has to be between 1 and 100. Try again: '))
withinRange = True if (guess <= 100 and guess >= 1) else False
rng = 'low' if guess < magicNumber else 'high'
print('\nYou entered the right number!')
print('Number:',magicNumber)
print('range of last guess was too',rng)
print('Number of guesses:',count + 1)
Last time, I was told that I didn't provide enough information about my program. And I hope I didn't over do it with the comments. This is my goal/question/inquiry/objective: I want to add some line of code into the program to have it terminate after 7 tries.
What the program does now is accept guesses over and over until the right one is reached. But I want to add some code that kills it after the 'count' variable reaches 6. The count variable goes up each time a guess is entered. Regardless of whether it is correct or not.
Any suggestion would be awesomely appreciated, Thanks in advance wizards!
There are a lot of problems with the code.
Please don't use eval() to convert a string to an integer. int() does this without the security risks of eval.
In your while loop you compare var1 and var2 with var. What is var? You didn't define it anywhere. I guess you meant magicNumber. Then in the loop you set var2 and var3. Why var3. You don't use it. And least, the best way to get the two numbers for the addition would be to get one number with the maximum of magicNumber and just calculate the second number.
True if (guess <= 100 and guess >= 1) else False could be written as
True if 1 <= guess <= 100 else False
Get rid of the duplicate code in the loop and outside of the loop. You might want to add other functions e.g. a function just for getting the input from the user and to do some basic checks.

Categories