I'm writing a program that is supposed to guess the user's secret number using bisection search. I feel like I understand the concept of bisection search quite well but my IDE (Canopy) won't let me 'run' the code, which I assume is due to an error or something that it wants me to do before I run it.
lowend = 1
highend = 100
guess = 50
choice = 0
print "Please think of a number between 0 and 100!"
while choice != 'c':
print "Is your secret number " + str(guess) + "?"
print "Enter 'h' to indicate the guess is too high.",
print "Enter 'l' to indicate the guess is too low.",
choice = raw_input("Enter 'c' to indicate I guessed correctly.")
if choice == 'c':
break
elif choice == 'h':
highend = guess
guess = (highend + lowend)/2
print 'Is your secret number ' + str(guess) + "?"
choice = 0
elif choice == 'l':
lowend = guess + 1
guess = (highend + lowend)/2
print 'Is your secret number ' + str(guess) + "?"
else:
print "Sorry, I did not understand your input."
choice = 0
print 'Your number is: ' + str(guess) + "."
I'm not sure if there's something I'm doing wrong, but Canopy's green 'run' button is greyed out. Why does this happen? Does anyone see anything obviously wrong with my code?
Did you get this yet?
I think your initial choice should be a space: choice = " "
Also you need parenthesis on your print statements.
Maybe you don't need the raw_ for your input?
Maybe some rounding or making your answers integers.
I guess u need to ask for an input with the raw_input function insted of just printin' those messages, the programm can't find l,h or c to make the comparissons.
Restart Canopy's IDE to solve your problem.
I faced similar problem when the other script went into an infinite loop.
Related
I've been trying to solve the issue with guessing the number program,
The first number the program has to print Ans which is (Startlow + Starthigh)/2 and then Ans gets updated depends on the input
I can't figure out why my while loop keeps waiting for the input for at least 2 times until it prints the results even if I press l or h (unless I press c) which breaks the loop
Startlow = 0
Starthigh = 100
Ans = (Startlow + Starthigh)/2
print("Please think of a number between 0 and 100!")
while True:
print("Is your secret number " + str(int(Ans)))
if input() == "c":
print("Game over,Your secret number was: "+str(int(Ans)))
break
elif input() == "l":
Startlow = Ans
Ans = (Startlow + Starthigh)/2
elif input() == "h":
Starthigh = Ans
Ans = (Startlow + Starthigh)/2
else:
print("Sorry, I did not understand your input.")
any help appreciated :)
You should be asking for input once in the loop, and then comparing that answer to the items you want.
You are instead requesting a (potentially different) answer at each of your conditionals.
The number of questions asked depends on how many conditionals you fall through.
Just do:
x = input()
if x == "c":
#And so on...
I found an exercise on a website to make a hangman game. Here is what I did:
score = int(5)
word = 'orange'
guess = str(input('Enter your guess: '))
while score > 0 or guess == 'o' and 'r' and 'a' and 'n' and 'g' and 'e' or 'orange'
if 'o' or 'r' or 'a' or 'n' or 'g' or 'e' or 'orange' == guess:
print('CORRECT')
else:
score = score - 1
print('Your score is ' + score)
print('WRONG')
This code just doesn't work! Especially the while loop ruins everything! How to make this actually work? I have written this code in the Jupyter notebook.
This is a working example of the guessing game, with some removal of code redundancy and a bit of clean-up. Important: break-statement inserted inside the if-statement to avoid infinite looping, and new guess prompt inserted in the else-statement:
score = 5
word = 'orange'
guess = str(input('Enter your guess: '))
while (score > 0) or (guess in ('o', 'r', 'a', 'n', 'g', 'e', 'orange')):
if guess in ('o', 'r', 'a', 'n', 'g', 'e', 'orange'):
print('CORRECT')
break
else:
score -= 1
print('WRONG')
print('Your score is ' + str(score))
guess = str(input('Enter your guess: '))
Example run:
Enter your guess: u
WRONG
Your score is 4
Enter your guess: o
CORRECT
There's lots here to do - 1st, your code only allows for a game of hangman for which the word to be guessed is "orange". Fine for a single game, but useless for the second round, unless all players have acute memory problems.
So you need to abstract a little - write some pseudo-code down, think about the steps your program is going to need to take in order to perform the operations required in the game.
This is like writing down instructions for a human, just in a form that's also close to your final programming language.
So something like:
# choose a word to play the game with, save it to the variable called word
word = 'orange'
# Reserve a list of letters that have been guessed.
# Start off with it empty - do the same to keep track of
# good and bad guesses
guesses = []
good_guesses = []
bad_guesses = []
# Reserve a number of bad tries allowed before game over
bad_tries_before_game_over = 5
# Reserve a number of bad tries so far
bad_tries_so_far = 0
# Start a loop, we'll come back to this point each time
# the player makes a new guess.
# There are two conditions when to not loop and those are:
# 1. when the player has won by guessing all the letters or
# 2. when the player has lost by getting too many wrong tries
# we'll use a variable called "finished" to track whether either of these conditions is met
finished = False
while not finished:
guess = str(input('Enter your guess: '))
# Check whether the person already guessed this letter
if guess in guesses:
print ( "You already guessed that letter.")
print ( "Try using a letter you've not already guessed.")
print ( guesses )
else:
# if guess is correct, then great, otherwise, add bad tries + 1
if guess in word:
print ( "Yes, {g} is in the word.".format(g=guess) )
guesses.append(guess)
good_guesses.append(guess)
else:
print ( "No, {g} is not in the word.".format(g=guess) )
guesses.append(guess)
bad_guesses.append(guess)
bad_tries_so_far = bad_tries_so_far + 1
if bad_tries_so_far > bad_tries_before_game_over:
print ( "Hangman. Game over. ")
finished = True
if set(word)==set(good_guesses):
print ( "Hooray, you saved the man!.")
finished = True
Over time, you'll naturally think in python and it will kind of become its own pseudo code. But it's best to at least try and work your ideas out on paper, or in English (or whatever language is your natural one) first, just to set out the logical flow that you want the game to have.
If you want to check guess against a set of different options, use in; you can't use and or or like that due to different precedences.
if guess in ('o', 'r', 'a', 'n', 'g', 'e', 'orange'):
would work better for you (though that's probably not the only problem in your code).
Well, here's one that I made. It's slightly more interactive and realistic, but making the words are kind of annoying. If you want to make it more fun, try adding more words with a random word generator or something like that, make the hangman more realistic, or adding game modes and VS matches.
I hope this helps =)
If you're still wondering how this code works, I'll try and explain as much as possible. First of all, I imported time to make pauses, making it more dramatic. If you want to remove the pauses, be my guest.
The first bunch of code is just the beginning and all that. You could delete/change it if you want
After, it asks you to input your name. Like I said, completely optional.
Next, it tells you to enter a number. Each number has a specific word.
Then, it's time to guess. I should explain what will happen. Let's say the word is secret. That's 6 letters.
It would look like this:
_
_
_
_
_
_
Then it asks you to start guessing. If you had your 10 tries, you lose. Let's say you managed to guess an "s". This happens:
s
_
_
_
_
_
Hope this explains everything. I'm working on this code and planning to add a party mode next.
Have a great day =)
Phantom
import time
time.sleep(5)
print('Welcome to... hangman!')
time.sleep(2)
print("Are you ready? Ok, let's start.")
time.sleep(3)
name =input("What is your name? ")
time.sleep(1)
print("Hello, " + name + ". Time to play hangman! I wish you good luck- you'll need it.")
time.sleep(3)
darealword=int(input('Please enter a number. 1-30 only> '))
if darealword==1:
word='hypothesize'
elif darealword==2:
word='tube'
elif darealword==3:
word='blow'
elif darealword==4:
word='volume'
elif darealword==5:
word='parachute'
elif darealword==6:
word='biography'
elif darealword==7:
word='paragraph'
elif darealword==8:
word='abortion'
elif darealword==9:
word='exaggerate'
elif darealword==10:
word='complain'
elif darealword==11:
word='diagram'
elif darealword==12:
word='produce'
elif darealword==13:
word='abnormal'
elif darealword==14:
word='account'
elif darealword==15:
word='interactive'
elif darealword==16:
word='jump'
elif darealword==17:
word='goalkeeper'
elif darealword==18:
word='glimpse'
elif darealword==19:
word='story'
elif darealword==20:
word='coal'
elif darealword==21:
word='weave'
elif darealword==22:
word='dynamic'
elif darealword==23:
word='credibility'
elif darealword==24:
word='rhythm'
elif darealword==25:
word='trunk'
elif darealword==26:
word='admire'
elif darealword==27:
word='observation'
elif darealword==28:
word='rough'
elif darealword==29:
word='representative'
else:
word='thought'
time.sleep(3)
print("Start guessing... you can do this.")
time.sleep(1)
guesses = ''
turns = 10
while turns > 0:
failed = 0
for char in word:
if char in guesses:
print(char,)
else:
print("_",)
failed += 1
if failed == 0:
time.sleep(5)
print('Aaaaaaand... you...')
time.sleep(3)
print('won!!!!! I congratulate you, '+ name +'.')
break
print
guess = input("Guess a character> ")
guesses += guess
if guess not in word:
turns -= 1
print("Sorry, this character isn't in the word. Don't get it wrong next time.")
# print("You have", + turns, 'more guesses')
if turns == 0:
print("Aaaaaaand... you...")
time.sleep(3)
print("lost. I feel bad. Better luck next time. And if you're wondering, the word is "+ word +'.')
My code will always take the first input despite the input. I have tried taking guess and making guess into an int but that leads to both if statements to trigger
x = 1
answer = 4
A=0
guess = 0
while A < 10:
for _ in range (5):
x = random.randint(1,5)
print ("Ralph holds up " + str(x) + " fingers what is the answer")
guess=input()
if guess != answer:
print("WRONG PROGRESS RESET")
A=0
answer = x
if guess == answer:
A += 1
print ("correct")
print ("You have " + str(A) + " out of 10 finished")
answer = x
print ("You win congrats")
First off your code never even import random to use randint. But I'll assume you did import it and you just never pasted it in.
input reads your input as a str, but you want it to read as an int. All you really need to do is wrap the input() call in an int invocation. Additionally, input takes an argument, which prompts that argument in the console.
Also #tobias_k has a good point, but instead of elif guess == answer:, just use else:.
I also changed some variable logic, and I changed A to a much more meaningful identifier, as well as fixing formatting, like a = b is more aesthetically pleasing than a=b.
Oh and indentation. Indentation is important, not only for readability, but in Python, it's required. Python is whitespace significant, meaning scope delimiters are whitespace.
import random
finished_count = 0
while finished_count < 10:
for _ in range(5):
answer = random.randint(1, 5)
guess = int(input("Ralph holds up %d finger%s. What is the answer?\n" % (answer, "" if answer == 1 else "s")))
if guess != answer: # incorrect answer
print("WRONG PROGRESS RESET")
finished_count = 0
else: # correct
finished_count += 1
print("Correct. You have %d out of 10 finished" % finished_count)
print("You win, congrats!")
I just used this code up until I got to 10 and it works fine
I’m trying to write a guessing word program in Python 2.7. The user has 50 chances to correctly guess the word. I’ve already written a function that generates a random word from a list of words. The user needs to correctly guess the word.
For example, if the correct word is “dog” and the user guesses “apple,” the program will return “too low” and the user will then guess again. If the user guesses “pear,” the program will return “too high.”
I don’t really know how to start writing this piece of code. I tried using a while loop, but I don’t know where to go from here. Thank you all in advance.
Here’s what I have so far:
Note: ‘correct’ is the word the user is trying to guess; guess is the word the user guessed
while guess != 'correct':
if guess < correct:
print 'Too low'
guess = int(raw_input('Enter a word')
elif guess > correct:
print 'Too high'
guess = int(raw_input('Enter a word')
else:
print 'You finally got it!'
break
print
while tries < 50:
guess = raw_input('Guess a word')
if guess not in word:
print "Sorry, try again."
else:
print 'Good job!'
else:
print "Sorry. My word was ", word, ". Better luck next time!"
there is no need for 2 loops. You can use the AND this will stop your loop if a person guessed the word right or if that person run out of lives. Also there is no need to say int() for your input as you only input a word. If the word is "too low" you print it decrease lives and enter a new word, similarly for "too high". You stop when your lives are at 0 or you guessed the word
guess = raw_input('Guess a word: ')
correct = 'dog'
lives = 50
while guess != correct and lives != 0:
if guess < correct:
print 'Too low'
lives -= 1
guess = raw_input('Enter a word: ')
else:
print 'Too high'
lives -= 1
guess = raw_input('Enter a word: ')
if lives == 0 and guess != correct:
print "Sorry. My word was", correct,". Better luck next time!"
else:
print "You finally got it!"
I like OmO Walker's answer to the question. Here is a slight variation of OmO's code.
# I like adding a .lower() so the person doesn't have to worry about the case matching.
correct = 'dog'.lower()
lives = 2
guess = None
# I like doing a > check not an != because stuff happens and if lives become < 0 you
# get stuck in an infinite loop. BUT in some cases comparisons <, > can be slower than ==.
# So if speed is a problem stick to ==
while not guess == correct and not lives <= 0:
# Moving this here makes it so there are fewer places you have to get input.
# Prints how many lives the user has left.
print "{} lives remaining".format()
guess = raw_input('Guess a word: ').lower()
if guess < correct:
print '{} was too low'.format(guess)
elif guess > correct:
print '{} was too high'.format(guess)
lives -= 1
if not lives > 0 and not guess == correct:
# I like using the format string method instead of adding strings or using ',' in a print. It is more reliable if
# the variable you are trying to print is not a string.
print "Sorry. My word was {}. Better luck next time!".format(correct)
# Makes sure the guess is really right before giving the confirmation
elif guess == correct:
print "You got it! The word was {}".format(correct)
# This is an added safety that will be triggered if some how the other conditions fall through. Its better to
# have an error thrown than have a program silently break.
else:
print "ERROR. Something is broken"
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Here is my code:
name = input("What is your name? ")
print name + " do you want to play a game?"
answer = input("To play the game, type either yes or no. ")
if answer == yes:
print "Great," + name + "lets get started!"
elif answer == no:
print "Okay, good bye!"
import random
number = random.randint(1,50)
guess = input ("Pick a number between 1 and 50. This number cannot be a decimal. ")
if guess > number:
print "Your guess is too high!"
elif guess < number:
print "Your guess is too low!"
while guess != number:
print "Try again!"
else import random
number = random.randint(1,50)
if guess == number:
print "You guessed it!"
print "Great job."
print "Do you want to play again?"
while answer == yes:
import random
number = random.randint(1,50)
guess = input ("Pick a number between 1 and 50. This number cannot be a decimal. ")
if guess > number:
print "Your guess is too high!"
elif guess < number:
print "Your guess is too low!"
while guess != number:
print "Try again!"
if guess == number:
print "You guessed it!"
print "Great job."
print "Do you want to play again?
elif answer == no:
print "Okay. Good game " + name + "!"
print "Play again soon!"
Ok, my first question is why does python not recognize input for the name variable as a string.
The second question is the last elif statement keeps giving me a syntax error. I am not sure why.
The last question is can I loop this code any easier way?
In Python 2x versions, input() takes variable as integer, you could use raw_input() to take it as string.
So basically change your input() to raw_input() for taking the data as string.
In Python 3x versions there is no raw_input, there is only input() and it takes the data as string.
Second question;
elif guess < number:
print "Your guess is too low!"
while guess != number:
print "Try again!"
else import random
number = random.randint(1,50)
This is not a correct syntax, your else needs an if block above itself. You can't use else without an if block.If you think for a second, that makes sense.
Your last question is not fit with SO rules.