Determinate loop and Indeterminate Loops in Python - python

I need to show "Determinate loop" and "Indeterminate Loops" on this code. (nested)
This is a simple code, pick a random number, and gives you 2 opportunities to guess the number, if you can't, it will let you know what the magic number was and start the game again.
questions:
is there any other way to make the game start over? like a while or nested loop.
can I get an opinion if it is enough?
the problem with the code is, every time you make a guess, it prints
"Can you guess the magic number?"
how can it print that only at the beginning of the code and then only prints:
"try a lower number"
"try a higher number"
I feel like the code is not nested enough, anyway I can make it more professional?
repeat_the_game = True
def start():
import random
magic_number = random.randint(1, 10)
trying = 0
limit = 2
while trying < limit:
guess = int(input("can you guess the magic number?"))
trying += 1
if guess > magic_number:
print("try a lower number")
elif guess < magic_number:
print("try a higher number")
elif guess == magic_number:
print("wow, you are right")
break
else:
print("sorry, the magic number was", magic_number)
while repeat_the_game:
start()

Move the text out of the loop to a print statement. Then you can still keep fetching the input inside the loop:
repeat_the_game = True
def start():
import random
magic_number = random.randint(1, 10)
trying = 0
limit = 2
print("can you guess the magic number?")
while trying < limit:
trying += 1
guess = int(input())
if guess > magic_number:
print("try a lower number")
elif guess < magic_number:
print("try a higher number")
elif guess == magic_number:
print("wow, you are right")
break
else:
print("sorry, the magic number was", magic_number)
while repeat_the_game:
start()
However, if the second guess is still wrong you probably don't want to print "try a lower/higher number". If you guess it right the second time you do want to print "wow, you're right". I'd put the "try a lower/higher number" after an additional check of whether all tries have been used up already. You can move the "wow, you're right" part before that check:
while trying < limit:
guess = int(input())
trying += 1
if guess == magic_number:
print("wow, you are right")
break
if trying == limit:
continue
if guess > magic_number:
print("try a lower number")
elif guess < magic_number:
print("try a higher number")
else:
print("sorry, the magic number was", magic_number)

Related

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.

Python: why is my print statement not running for my else?

import random
number = random.randint(0,10)
#print (number)
guess = int(input("I'm thinking of a number between 1 and 10. \nPlease guess what it is: "))
#print(guess)
while guess != number:
if guess > number:
print("That is too high!")
guess = int(input())
elif guess < number:
print("That is too low")
guess = int(input())
else:
print("Thats it! You win!")
I'm working out a few python coding examples and I am confused why my else statement isn't printing?
The code objective is to generate a random number, and then have the user input a guess and then depending if the guess is lower or higher than the random number for the computer to notify the user and if the user guess correctly, then to tell the user that they won.
I'm tested this out and when I input the correct number the code just ends and doesn't print out "That's it! You win!". Why is this and how can I get it to print it out?
Guess input prior to the loop will most times be different than the number to guess, therefore the loop will not enter.
You also have other more subtle bugs: for instance, input is taken twice in one loop, creating conditions for improper feedback. Further, your win is confirmed by default, that is if guess not too high, and if guess not too low, then it is a win; a positive assertion such as if guess equals number, is probably safer to declare a win.
Here is a design that segregates each actions in one place in the loop, minimizing the risks of a faulty logic.
import random
number = random.randint(0, 10)
guess = None
while guess != number:
guess = int(input())
if guess > number:
print("That is too high!")
elif guess < number:
print("That is too low")
elif guess == number:
print("Thats it! You win!")
else:
print('that was not supposed to happen')

Number guessing game, unable to take the next guess

Here is the concept of my game, the computer randomly generates a number from 1-100 and the player has to guess that number. If the number they guess is higher or lower the computer tells them so.
I added some code to make sure that the guess that the user enters is a number, but for some reason, it only works for their first guess.
import random
x = random.randint(1, 100)
guess = input("Guess the number")
while guess.isnumeric() == True:
if x > int(guess):
print("Too low, guess again")
guess = input("Guess the number")
if x < int(guess):
print("Too high, guess again")
guess = input("Guess the number")
if x == int(guess):
print ("That is correct!")
break
if guess.isnumeric() == False:
print("Please enter a valid number")
guess = input("Guess the number")
I don't really know how to else to explain it. But for example, if I guess the number 20 as my first guess, it would output too high or too low depending on the randomly generated number, but after that, if I input a bunch of random letters it would give me an error that the guess could not be compared to the randomly generated number.
I've fixed your code for you. Try this:
import random
x = random.randint(1, 100)
while True:
try:
guess = int(raw_input("Guess the number: "))
except ValueError:
print("Not a valid number, try again!")
continue
if guess < x:
print("Too low, guess again")
elif guess > x:
print("Too high, guess again")
elif x == guess:
print ("That is correct!")
break
You don't need to prompt the user for input after every guess, that's what the first input prompt is for. Because we are specifying while True, the user will get prompted to input a number every single time unless they enter the correct number, which in that case, we break the infinite loop.
Additionally, we can put the input statement in a try block, because we are casting the input as an integer right there. If the user enters a string, the program would otherwise fail if it tried to cast it as an integer, but if we except ValueError: and then continue, we will alert the user that their input is invalid, and then prompt them for input once again.
Your if statements are all independent:
if x > int(guess):
print("Too low, guess again")
guess = input("Guess the number")
if x < int(guess):
print("Too high, guess again")
guess = input("Guess the number")
if x == int(guess):
print ("That is correct!")
break
The second and third if statements will always test guess again, even if the first if test matched. And if the first if test matched and you entered a non-numeric guess value, those two tests will fail as the int() call will throw a ValueError exception.
You could tell Python that the tests are interdependent by using elif and else; now Python will only execute the first matching block, and skip the others entirely:
if x > int(guess):
print("Too low, guess again")
guess = input("Guess the number")
elif x < int(guess):
print("Too high, guess again")
guess = input("Guess the number")
else:
print ("That is correct!")
break
This means that execution continuous after the else block when either the if or elif tests matched.
Note that I used else at the end; if the number is neither too high nor too low, the number must be equal, there is no other option. There is no need to test for that explicitly.
You are now repeating yourself however. You are asking for a guess in 3 different places. You could ask once and let the loop take care of asking for a new value:
while True:
while True:
guess = input("Guess the number:")
if guess.isnumeric():
break
print("Not a valid number, try again!")
guess = int(guess)
if x > guess:
print("Too low, guess again")
elif x < guess:
print("Too high, guess again")
else:
print ("That is correct!")
break
That's a lot less repetition already; a separate while loop asks for a number until it is actually numeric, and guess is converted to int() just once.
You could remove that nested while True: and just use the outer one here, the result would be the same, provided you use the continue keyword to skip the rest of the loop when you don't have a numeric value:
while True:
guess = input("Guess the number:")
if not guess.isnumeric():
print("Not a valid number, try again!")
continue # skip to the top of the loop again, so ask again
guess = int(guess)
if x > guess:
print("Too low, guess again")
elif x < guess:
print("Too high, guess again")
else:
print ("That is correct!")
break
You need to surround your guessing logic in another loop that continues until the guess is correct.
pseudocode:
choose_target_answer
while player_has_not_guessed_answer
get_player_guess
if player_guess_is_valid
respond_to_player_guess
else
give_error_message

Guess the Number Game with Different Guess Names

This is my first time visiting using stackoverflow--I'm new to programming and am taking a beginner's course for Python. Excited to get started!
Our second assignment asks us to create the well-known Guess the Number Game. For those of you who already know this game, I would love some help on an extra piece that's been added to it: we must list off each guess with their respective order. A sample output should look like this:
I'm thinking of an integer, you have three guesses.
Guess 1: Please enter an integer between 1 and 10: 4
Your guess is too small.
Guess 2: Please enter an integer between 1 and 10: 8
Your guess is too big.
Guess 3: Please enter an integer between 1 and 10: 7
Too bad. The number is: 5
I've got the coding down to where I have Guess 1 and Guess 3 appear, but I cannot make Guess 2 appear. I've been reworking and replacing every "while", "if", "elif", and "else" command to fix this, but can't seem to come up with a solution! Here is my code so far:
def guess():
print ("I'm thinking of an integer, you have three guesses.")
attempts = 0
from random import randint
number = randint(0,10)
guess = eval(input("Guess 1: Please enter an integer between 1 and 10: "))
while guess != number and attempts == 0:
if guess < number:
print("Your guess is too small.")
break
if guess > number:
print("Your guess is too big.")
break
elif guess == number:
print("You got it!")
attempts = attempts + 1
if number != guess and attempts == 1:
guess = eval(input("Guess 2: Please enter an integer between 1 and 10: "))
if guess < number:
print("Your guess is too small.")
elif guess > number:
print("Your guess is too big.")
while guess == number:
print("You got it!")
attempts = attempts + 1
elif number != guess and attempts == 2:
guess = eval(input("Guess 3: Please enter an integer between 1 and 10: "))
if guess < number:
print("Too bad. The number is: ", number)
elif guess > number:
print("Too bad. The number is: ", number)
while guess == number:
print("You got it!")
This code outputs Guess 1 and then quits. Can anyone help me figure out how to make Guess 2 and 3 appear?? All ideas are welcome--Thanks!
You can shorten you code quite a bit, just move the input in the loop and keep looping for either three attempts using range or the user guesses correctly:
def guess():
print ("I'm thinking of an integer, you have three guesses.")
from random import randint
number = randint(0,10)
# loop three times to give at most three attempts
for attempt in range(3):
# cast to int, don't use eval
guess = int(input("Guess 1: Please enter an integer between 1 and 10: "))
if guess < number:
print("Your guess is too small.")
elif guess > number:
print("Your guess is too big.")
else: # not higher or lower so must be the number
print("You got it!")
break
It would be better to use a while with a try/except to verify the user inputs a number, looping until the user has used 3 attempts or guesses correctly:
def guess():
print ("I'm thinking of an integer, you have three guesses.")
attempts = 0
from random import randint
number = randint(0,10)
while attempts < 3:
try:
guess =int(input("Guess 1: Please enter an integer between 1 and 10: "))
except ValueError:
print("That is not a number")
continue
if guess < number:
print("Your guess is too small.")
attempts += 1
elif guess > number:
print("Your guess is too big.")
attempts += 1
else: # if it is a number and not too high or low it must be correct
print("You got it!")
break # break the loop
You cannot just use an if/else if you actually want to give the user feedback on whether their guess was too low or too high.
Also as commented don't use eval. Some good reason why are outlined here
All your while guess!=number and attempts == loops are useless, because you're either breaking out of them or incrementing attempts so their condition evaluates to False after the first iteration.
Guess 2 is never reached because either number equals guess (so number != guess is False) or attempts is still zero.
Guess 3 is never reached for the same reason. However, if guess 2 would be reached, guess 3 would never be reached because you put elif in front.
Try to get rid of the code for guess 2 and guess 3. Write all the code for guess = eval(input()) and if guess < number: ... elif guess > number: ... once and put it inside a loop. Here's a bit of pseudocode to illustrate the idea:
while attempts < 3
ask for user input
if guess equals number
print "you win"
exit the loop
else
print "that's wrong"
I used the "concatenation" method along with some of your helpful response ideas and finally got my code to work!! Thank you all so, so much for the help!! Here is the correct code for this program:
def guess():
from random import randint
number = randint(0,10)
print("I'm thinking of an integer, you have three guesses.")
attempts = 0
while attempts < 2:
guess = eval(input("Guess " + str(attempts + 1) + ": Please enter an integer between 1 and 10: "))
if guess < number:
print("Your guess is too small.")
attempts += 1
elif guess > number:
print("Your guess is too big.")
attempts += 1
else:
print("You got it!")
break
else:
attempts == 3
guess = eval(input("Guess 3: Please enter an integer between 1 and 10: "))
if guess < number:
print("Too bad. The number is: ", number)
elif guess > number:
print("Too bad. The number is: ", number)
else:
print("You got it!")
And then ending it with a call to function ("guess()"). Hope this serves well for those who experience this problem in the future. Again, thank you guys!

Guessing game in python

I have only just started to learn to program following http://learnpythonthehardway.org.
After learning about loops and if-statements I wanted to try to make a simple guessing game.
The problem is:
If you make an incorrect guess it gets stuck and just keeps repeating either "TOO HIGH" or "TOO LOW" until you hit crtl C.
I have read about while loops and have read other peoples code but I simply dont want to just copy the code.
print ''' This is the guessing game!
A random number will be selected from 1 to 10.
It is your objective to guess the number!'''
import random
random_number = random.randrange(1, 10)
guess = input("What could it be? > ")
correct = False
while not correct:
if guess == random_number:
print "CONGRATS YOU GOT IT"
correct = True
elif guess > random_number:
print "TOO HIGH"
elif guess < random_number:
print "TOO LOW"
else:
print "Try something else"
You have to ask the user again.
Add this line at the end (indented by four spaces to keep it within the while block):
guess = input("What could it be? > ")
This is just a quick hack. I would otherwise follow the improvement proposed by #furins.
Moving the request inside the while loop does the trick :)
print ''' This is the guessing game!
A random number will be selected from 1 to 10.
It is your objective to guess the number!'''
import random
random_number = random.randrange(1, 10)
correct = False
while not correct:
guess = input("What could it be? > ") # ask as long as answer is not correct
if guess == random_number:
print "CONGRATS YOU GOT IT"
correct = True
elif guess > random_number:
print "TO HIGH"
elif guess < random_number:
print "TO LOW"
else:
print "Try something else"

Categories

Resources