Beginner python - stuck in a loop - python

I have two begininer programs, both using the 'while' function, one works correctly, and the other gets me stuck in a loop. The first program is this;
num=54
bob = True
print('The guess a number Game!')
while bob == True:
guess = int(input('What is your guess? '))
if guess==num:
print('wow! You\'re awesome!')
print('but don\'t worry, you still suck')
bob = False
elif guess>num:
print('try a lower number')
else:
print('close, but too low')
print('game over')``
and it gives the predictable output of;
The guess a number Game!
What is your guess? 12
close, but too low
What is your guess? 56
try a lower number
What is your guess? 54
wow! You're awesome!
but don't worry, you still suck
game over
However, I also have this program, which doesn't work;
#define vars
a = int(input('Please insert a number: '))
b = int(input('Please insert a second number: '))
#try a function
def func_tim(a,b):
bob = True
while bob == True:
if a == b:
print('nice and equal')
bob = False
elif b > a:
print('b is picking on a!')
else:
print('a is picking on b!')
#call a function
func_tim(a,b)
Which outputs;
Please insert a number: 12
Please insert a second number: 14
b is picking on a!
b is picking on a!
b is picking on a!
...(repeat in a loop)....
Can someone please let me know why these programs are different? Thank you!

In the second example, the user doesn't get a chance to enter a new guess inside the loop, so a and b remain the same.

In the second program you never give the user a chance to pick two new numbers if they're not equal. Put the lines where you get input from the user inside the loop, like this:
#try a function
def func_tim():
bob = True
while bob == True:
#define vars
a = int(input('Please insert a number: '))
b = int(input('Please insert a second number: '))
if a == b:
print('nice and equal')
bob = False
elif b > a:
print('b is picking on a!')
else:
print('a is picking on b!')
#call a function
func_tim()

in your 2nd program, if b > a, you will go back to the loop because bob is still true. You forgot to ask the user to input again.. try it this way
def func_tim():
while 1:
a = int(input('Please insert a number: '))
b = int(input('Please insert a second number: '))
if a == b:
print('nice and equal')
break
elif b > a:
print('b is picking on a!')
else:
print('a is picking on b!')
func_tim()

Your second program doesn't allow the user to reenter his guess if it's not correct. Put the input into the while loop.
Additional hint: Don't make checks like variable == True, just say while variable:.

Related

How to end a try loop in a dice game at the correct place?

I am trying to make a program where the player enters a number (1-6) to guess what a fair randomised dice lands on.
Then it should stimulate the dice throw, and informs the player whether it was correct or not.
It should continue to ask the player to guess by entering a number until the guess is correct.
If it is correct the game should end.
If it is not correct the game continues to ask the player to select a number.
I have tried:
from random import randint
def validateNumber():
valid = False
if 1 <= number_in <=6:
valid = True
return valid
game_1 = randint(1,6)
while True:
try:
number_in = int(input("Enter a number between 1-6: "))
is_valid = validateNumber()
if not is_valid:
number_in = int(input("Enter a number between 1-6: "))
if number_in == game_1:
print(f"The result was {game_1}. Your guess was correct!")
else:
print(f"The result was {game_1}. Your guess was NOT correct. Please try again")
except ValueError:
break
However, now it does not end when the guess is correct.
Does anyone know how to fix this?
I have tried many variants, but this is the closest I got to the wanted result, but still it is not satisfactory. Also it does not seem to truly handle the user input?
(I am quite new to Python and trying to learn the most before starting college in January:)) All help appreciated!
Your main issue is that you should break out of the while loop when the user guess the number. You have a couple of other issues:
if the user inputs an invalid number twice, you accept it the second time
it would be better to pass number_in to validateNumber as a parameter rather than relying on a global
if the user inputs something which is not an integer, the game terminates
Note also you can simplify validateNumber as follows:
def validateNumber(number):
return 1 <= number <= 6
Overall I would rewrite the code as:
from random import randint
def validateNumber(number):
return 1 <= number <= 6
game_1 = randint(1, 6)
while True:
# play game
is_valid = False
while not is_valid:
# read an input
try:
number_in = int(input("Enter a number between 1-6: "))
is_valid = validateNumber(number_in)
except ValueError:
pass
# check the input
if number_in == game_1:
print(f"The result was {game_1}. Your guess was correct!")
# all done
break
else:
print(f"The result was {game_1}. Your guess was NOT correct. Please try again")
# get another number for them to guess
game_1 = randint(1, 6)
After you get correct answer (number_in == game_1), you should break the while.
I think, this is what you want:
from random import randint
def validateNumber():
valid = False
if 1 <= number_in <= 6:
valid = True
return valid
game_1 = randint(1, 6)
guess_was_correct = False
while not guess_was_correct:
is_valid = False
while not is_valid:
try:
number_in = int(input("Enter a number between 1-6: "))
is_valid = validateNumber()
if not is_valid:
print("You entered a number outside of the 1-6 range. Please enter a number between 1 and 6!")
except ValueError:
print("You did not enter a number. Please enter a number.")
if number_in == game_1:
print(f"The result was {game_1}. Your guess was correct!")
guess_was_correct = True
else:
print(f"The result was {game_1}. Your guess was NOT correct. Please try again")
You need an inner loop to check the validity of the input, and the exception handling needs to go there too.
Checking the correctness of the guess is done in the outer loop. It's a separate thing and needs to be done only once we have a valid input.

Executing one line of code inside a while loop only once

How do I make a specific line of code execute only once inside a while loop?
I want the line:
"Hello %s, please enter your guess: " %p1" to run only once and not every time the player guesses wrong.
Is there are command or function I can use or do I have to structure the whole game differently? Is there a simple fix to the program in this form?
import random
number = random.randint(1,9)
p1 = input("Please enter your name: ")
count = 0
guess = 0
while guess != number and guess != "exit":
guess = input("Hello %s, please enter your guess: " % p1)
if guess == "exit":
break
guess = int(guess)
count += 1
if guess == number:
print("Correct! It Took you only", count, "tries. :)")
break
elif guess > number:
print("Too high. Try again.")
elif guess < number:
print("Too low. Try again.")
You can create a flag variable, e. g.
print_username = True
before the while loop. Inside the loop uncheck it after loop's first iteration:
if print_username:
guess = input("Hello %s, please enter your guess: " % p1)
print_username = False
else:
guess = input("Try a new guess:")
You have to ask for a new guess on every iteration - else the code will loop either endlessly (after first wrong guess) or finish immediately.
To change up the message you can use a ternary (aka: inline if statement) inside your print to make it conditional:
# [start identical]
while guess != number and guess != "exit":
guess = input("Hello {}, please enter your guess: ".format(p1) if count == 0
else "Try again: ")
# [rest identical]
See Does Python have a ternary conditional operator?
The ternary checks the count variable that you increment and prints one message if it is 0 and on consecutive runs the other text (because count is no longer 0).
You might want to switch to more modern forms of string formatting as well: str.format - works for 2.7 as well
A way to execute an instruction only x times in a while loop could be to implement a counter, and add an if condition that checks if the counter < x before executing the instruction.
You should ask for the username outside of the loop and request input at the beginning of the loop.
Inside the loop you create output at the end and request input on the next iteration. The same would work for the first iteration: create output (outside of the loop) and then request input (first thing inside the loop)

Write a simple looping program

I want to write a program with this logic.
A value is presented of the user.
Commence a loop
Wait for user input
If the user enters the displayed value less 13 then
Display the value entered by the user and go to top of loop.
Otherwise exit the loop
You just need two while loops. One that keeps the main program going forever, and another that breaks and resets the value of a once an answer is wrong.
while True:
a = 2363
not_wrong = True
while not_wrong:
their_response = int(raw_input("What is the value of {} - 13?".format(a)))
if their_response == (a - 13):
a = a -13
else:
not_wrong = False
Although you're supposed to show your attempt at coding towards a solution and posting when you encounter a problem, you could do something like the following:
a = 2363
b = 13
while True:
try:
c = int(input('Subtract {0} from {1}: '.format(b, a))
except ValueError:
print('Please enter an integer.')
continue
if a-b == c:
a = a-b
else:
print('Incorrect. Restarting...')
a = 2363
# break
(use raw_input instead of input if you're using Python2)
This creates an infinite loop that will try to convert the input into an integer (or print a statement pleading for the correct input type), and then use logic to check if a-b == c. If so, we set the value of a to this new value a-b. Otherwise, we restart the loop. You can uncomment the break command if you don't want an infinite loop.
Your logic is correct, might want to look into while loop, and input. While loops keeps going until a condition is met:
while (condition):
# will keep doing something here until condition is met
Example of while loop:
x = 10
while x >= 0:
x -= 1
print(x)
This will print x until it hits 0 so the output would be 9 8 7 6 5 4 3 2 1 0 in new lines on console.
input allows the user to enter stuff from console:
x = input("Enter your answer: ")
This will prompt the user to "Enter your answer: " and store what ever value user enter into the variable x. (Variable meaning like a container or a box)
Put it all together and you get something like:
a = 2363 #change to what you want to start with
b = 13 #change to minus from a
while a-b > 0: #keeps going until if a-b is a negative number
print("%d - %d = ?" %(a, b)) #asks the question
user_input = int(input("Enter your answer: ")) #gets a user input and change it from string type to int type so we can compare it
if (a-b) == user_input: #compares the answer to our answer
print("Correct answer!")
a -= b #changes a to be new value
else:
print("Wrong answer")
print("All done!")
Now this program stops at a = 7 because I don't know if you wanted to keep going with negative number. If you do just edited the condition of the while loop. I'm sure you can manage that.

Python "if" statement not working

I was writing a complex program and I was getting an if statement...
(this isn't the complex code, this is just an example)
print("The 24 game will give you four digits between one and nine")
print("It will then prompt you to enter an ewuation one digit at a time.")
import random
a = random.randint(1,9)
b = random.randint(1,9)
c = random.randint(1,9)
d = random.randint(1,9)
print(a,b,c,d)
f=input("Enter one of the above numbers")
if f==a:
print("ok")
elif f != a:
print("No")
No matter what I type it always outputs "NO".
It would work after converting the user input string to a number:
if int(f) == a:
print("ok")

How do i make my program move on to the next elif in python

import random
print"hello what is your name?"
name = raw_input()
print"hello", name
print"wanna play a game? y, n"
choice = raw_input()
if choice =='y':
print'good lets start a number guessing game'
elif choice =='n':
print'maybe next time'
exit()
random.randint(1,10)
number = random.randint(1,10)
print'pick a number between 1-10'
numberofguesses = 0
guess = input()
while numberofguesses < 10:
if guess < number:
print"too low"
elif guess > number:
print"too high"
elif guess == number:
print'your correct the number is', number
break
if guess == number:
print'CONGRATS YOU WIN THE GAME'
when i enter my guess into the program it only gives me one output for example
i enter 8
programs output is "too high"
but when i guess again the output is blank, how do i fix this?
hello what is your name?
ed
hello ed
wanna play a game? y, n
y
good lets start a number guessing game
pick a number between 1-10
2
too low
>>> 5
5
>>> 3
3
>>> 2
2
>>>
I think this is what you want:
numberofguesses = 0
while numberofguesses < 10:
guess = input() #int(raw_input("Pick a number between 1 and 10: ")) would be much better here.
numberofguesses+=1
if guess < number:
print "too low"
elif guess > number:
print "too high"
elif guess == number:
print 'your correct the number is', number
break
With your version of the code, you guess once. If you're wrong, your program tries the same guess over and over again forever (assuming your break was actually supposed to be indented in the elif). You might be typing new guesses into the terminal, but your program never sees them. If the break was actually in the correct place in your code, then you guess once and whether write or wrong it exits the loop right away.
your break is outside of your ifstatement
It will execute while loop one time and break no matter what

Categories