Python 3.5 While loop not entering the If Statements - python

My apologies in advance. I know this question has probably been asked on stack exchange before and I do see some relevant posts,but I'm having some issue interpreting the responses.
I've been asked to create a guessing program that uses 'bisection search' to guess the number that you've selected (in your mind).
I have a program that runs on Python 2 interpreters when I change input() to raw_input(). My program also runs on a python 3 interpreter (python tutor). However when I run the program from scipython, pycharm or command line I do not see the response I'm expecting. Instead of moving through the if statements under the while loop the program seems to loop through the top of the while statement over and over again. I'll paste my code any suggestions would be appreciated.
low = 0
high = 100
flag = True
print("Please think of a number between 0 and 100!")
while flag:
ans = (high + low) // 2
print("Is your secret number " + str(ans))
question = input(
"Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ")
if question == 'l':
low = ans
elif question == 'h':
high = ans
elif question == 'c':
flag = False
print("Game over. Your secret number was: " + str(ans))
else:
print('invalid response, please choose again.')
EDIT:
This is the output to console. There is no failure but as you can see the program is not entering the if conditionals. I entered the response to each conditional and it just returns the same guess. I assume that I'm not entering the if statements because I do not get a change to the answer or if I hit an incorrect character, I do not get to the else: print.
Is your secret number 50
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
Is your secret number 50
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. h
Is your secret number 50
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. c
Is your secret number 50
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.
EDIT #2:
I just got it to work for some random unknown reason. scipython still won't run the code correctly, but the grading program marked me correct. So frustrating!

Ok I figured it out after my code graded correctly. I was using the wrong console in scipython IDE to evaluate my code D'Oh
Anyways the code is a good example of taking an input() inside a while loop and using if/elsif/else to meet conditions.
Just remeber that in python 2 you'll want to use raw_input() instead of input() as the method changes from python 2 to 3

Related

Two Player guessing game python

So my professor told me to make a number guessing game. I did that but she later uploads guidelines on how she want's it done. My code is so different and I don't know how to edit it to match her expectation. Please help.
Player One picks a number and Player Two has 5 Guesses to guess it. If he manages to do so, he wins, if not, he losses and Player One wins.
If for example Player one picks the number '3' and Player Two enters the number '3' on any of his goes, it still says Player One wins.
This is my code and my attached assignment photo
def Game():
Guess = 0
NumberOfGuesses = 0
NumberToGuess = int(input("Player One enter you chosen number: "))
while NumberToGuess < 1 or NumberToGuess > 10:
NumberToGuess = int(input("Not a valid choice, please enter another number: "))
while Guess != NumberToGuess and NumberOfGuesses < 5:
Guess = int(input("Player Two have a guess: "))
NumberOfGuesses = NumberOfGuesses + 1
if Guess == NumberToGuess:
print("Player Two wins.")
else:
print("Player One wins.")
Game()
my assignment
So the assignment is pretty clear in my opinion.
This is a turn-based PvP Game with guessing a random number.
Your main_game loop needs the parameters on how many rounds are played.
Every round consists of 2 game_steps, which include 2 tries to guess the number + some I/O Stuff that is described in your assignment. Guessing on the first try rewards 5 points, and guessing on the second try rewards 3 points.
Personally, I refrain from using while loops unless for very specific use cases. In my opinion, for loops are just better. You can iterate over lists, ranges, dataframes, etc., and easily unpack data while you are at it.
The next thing I would recommend is to stick to the PEP-8 pythonic naming convention. It just makes it easier to read the code. Whenever I see a capital letter in a python script, I instantly think of a class. And later in the workplace, it is extremely important that code is easily readable.
If I were you, I would discard your code and start from scratch, I don't think there is much to salvage from the code you provided. Just read your assignment carefully and think about how you would solve it logically before starting to code.

I write a python program to ask my computer to guess a secret number but it does not work [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed last year.
Here is my code:
import random
def guessGame(x):
low=1
high=x
feedback=" "
while feedback != "c":
if high!=low:
guess=int(random.randint(low,high))
else:
guess=low
feedback= input(f"Is it {guess} too high(H),too lowe(L) or correct(C)?").lower()
if feedback == "h":
high = guess-1
elif feedback == "l":
low=guess+1
print(f"I guess the correct number{guess}!")
x=input("Please input a highest number in the range: ")
guessGame(x)
I wrote a python code to ask my computer to guess a secret number. But it did not work. I did some changes but still do know where I did wrong.
Python input type is a string you must convert to string to integer
x=int(input("Please input a highest number in the range: "))

Guess the Number game isn't working as intented [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed last year.
Random Number Generator - Guess It
Did a much more complex variant of this. (250+ lines) But when I tested it, even if I guessed the number correctly(it was between 1-20) it didn't accept it. Every stage, I programmed the computer to tell me a statement about the number, using if, elif and else commands. When I guessed the number, it just said the number is incorrect and told me a new statement about number. Could someone help, please? In this mini variant as well, if I get the correct answer, it still responds to the if statement.
import random
list = [1,2,3]
target = print(random.choice(list))
guess = input("What is the target number?")
if guess == target :
print("Well done.")
else:
print("The number you have guessed isn't correct.")
You need to convert the guess into an integer before comparison. and remove the print statement from the variable definition. You also need to rename the list variable as it is a protected name.
import random
listNumbers = [1,2,3]
target = random.choice(listNumbers)
guess = int(input("What is the target number?"))
if guess == target :
print("Well done.")
else:
print("The number you have guessed isn't correct.")

Trying to loop through Try and Except until correct input is entered

Situation:
I'm creating a "Casting of Lots" game for school. I have a function to validate the user's input for how much they want to "wager" this round. I want to catch all errors, while print out different error messages based on the error and ask for input again.
Problem:
I caught every error, however, I can't seem to figure out how to loops my first try-except statement so that if an integer is entered twice, it will continue to catch the error.
Here's my code (the talents argument is going to be used later in the function):
def validate_wager(talents):
"""
Validates user input for wager, checks for strings, negatives, and excessively high numbers
"""
# formats wager request
print('{wager:-<34}'.format(wager="How much do you wish to wager? "), end=" ")
try:
# gets user input for wager, captures Type and Value
# errors, asks again
wager = int(input())
except:
wager = int(input('Wager must be a whole number: '))
# if wager is 0 or negative, prints error, asks again
while wager <= 0:
# captures Value and Type Errors within loop
try:
wager = int(input('Wager cannot be zero or negative: '))
except:
wager = int(input('Wager must be a non-negative, whole number: '))
# if wager is greater than remaining talents, prints error, asks again
while wager > int(talents):
# captures Value and Type Errors within loop
try:
wager = int(input('Wager cannot be more than remaining talents: '))
except:
wager = int(input('Wager must be a whole number and less than remaining talents: '))
return wager
This is the output for the first iteration after a string is entered once:
Welcome to the Lots Game
Talents you have to play with: 100
1 - Field Bet
2 - Pass Bet
3 - Quit
Choice --------------------------- 1
How much do you wish to wager? --- H
Wager must be a whole number:
The solution:
If a string is entered again, the try-except statement will not catch it. I'd like it to repeat "Wager must be a whole number" until an integer is entered.
I've already tried nesting the try-except statement inside a while loop that updates a variable with "True" or "False" if the is or is not an error, but that didn't work. I've tried a number of other things as well, but I just can't seem to figure it out. Any help would be greatly appreciated.
As all condition are based on wager, use only one while True loop, and break it only when all conditions are meet
while True:
try:
wager = int(input('Wager must be a number, strictly positive and less than remaining talents: '))
if 0 < wager < int(talents):
break
except ValueError:
print("Invalid number")
When you have multiples values to get frmo the user, use the while True construction once per value

BASIC GUESSING GAME [duplicate]

This question already has answers here:
How does my input not equal the answer?
(2 answers)
Closed 5 years ago.
Hi all I hope you can explain what I am doing wrong. I am completely new to python and experimenting with basic code but it don't seem to work as i thought it might.
the program should be a simple one of guessing the right number contained in the variable, but even when guess correct it says "Nope, that's not right".
magic_number = 10
input("I am thinking of a number between 1 and 10, can you guess it? ")
if input == magic_number:
print("WOW! You must be psychic, that is spot on")
else:
print("Nope, that's not it")
first of all you should creat a variable that will store the answer, so for example.
answer = input("I am thinking of a number between 1 and 10, can you guess it? ")
thus you will also have to change if input == magic_number: to if answer == magic_number:
Nonetheless, the main problem is that when you enter something using the input method your input is automatically converted to a string.
So you have two choices:
Convert your magic number to a string (magic_number = 10to magic_number = "10") and run the code with the modifications that I have proposed
Convert your input too and Int modifying if answer == magic_number: to if int(answer) == magic_number:
Both of the methods work great, though be careful with the second one because if you input something that is not convertible to an int (for example "Hello", the code will return an error)
input isn't a variable, it's a function! You should type x=input("Enter a number"), and if x == magic_number. input returns a value, but you aren't storing the user's input anywhere.
try this :
magic_number = 10
guess = int(input("I am thinking of a number between 1 and 10, can you guess it? "))
if guess == magic_number:
print("WOW! You must be psychic, that is spot on")
else:
print("Nope, that's not it")

Categories

Resources