For some reason when I select "run module", IDLE won't run the first line of code until I press "enter". It's not a huge problem for this type of program, but I'm confused why this is happening. Can anyone clear this up for me? Here's the code:
print("Please think a number between 0 and 100!")
guess = 50
upper = 100
lower = 0
status = ""
while status != "c":
print("Is your secret number ") + str(guess) + ("?")
print ("Lower: ") + str(lower)
print ("Upper: ") + str(upper)
status = raw_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 status == "h":
upper = guess
guess = guess - (guess - lower)/2
elif status == "l":
lower = guess
guess = guess + (upper - guess)/2
elif status == "c":
break
else:
print("Sorry, I did not understand your input.")
print("Game over. Your secret number was: ") + str(guess)
Thanks so much!
See http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/execution.html (see section 1.9.2). It's a bug that occurs sometimes if the previous program was interrupted.
Related
to learn Python I'm working on a small terminal upgrade game. The user enters a number that is added to a random integer to get a score (called "Films Produced" in game). The problem I can't seem to fix is every time the player goes to the menu and back then back to entering more numbers the previous number is deleted instead of added on to the new one.
Here is the code:
print("TERMINAL FILM by Dominick")
print("---------------------")
# SCORE
def filmClicker():
global score
user_input = int(input(">> Enter a number: "))
score = user_input
if user_input > 5 or user_input < 0 or user_input == 0:
print(">> Not a valid number.")
filmClicker()
elif score > 0:
score = score + random.randint(1, 50)
print("")
print(">> You produced:", score, "films", "<<")
go_back_or_menu = input(">> Press ENTER to go again. Or type TAB to go back to the menu. ")
if go_back_or_menu == "":
filmClicker()
elif go_back_or_menu == "TAB" or "Tab" or "tab":
game()
def game():
print(">>>>>>>>>>>>> Menu >>>>>>>>>>>>>")
print(">> Type A to go make films. ")
print(">> Type B to see your current balance. ")
print(">> Type C to see the current box office. ")
print(">> Type D for your stats. ")
press_button_menu = input("")
if press_button_menu == "A":
filmClicker()
elif press_button_menu == "B":
print("Current Balance =", score)
press_enter()
game()
else:
filmClicker()
game()
So I want the player to be able to insert a number, the number gets added to another number by the computer, and then a final number is spit out. I got all that working. But it doesn't save when you do that multiple times. Which I don't want, I want it to stack each time you do it.
Sorry if I poorly explained it, I can answer more about it if needed. Any help is appreciated.
UPDATE:
I removed the score = "input" variable and declared it out of any function. But it's still not saving. Here is a better answer as to what I want it to do:
In the picture below I start at the game menu. I then decide to make films, I do it 5 times. But then when I go back to the menu and check my balance, the balance equals the last time I made films and not the TOTAL films. What I want it to do is add up all of the films. So in this case 48 + 49 + 9 + 38 + 25 instead of having just the last set (which is 25 in this case), to get a total balance which can be displayed by going to the menu and typing "B."
Here is the current code:
import random
score = 0
# SCORE
def filmClicker():
global score
user_input = int(input(">> Enter a number: "))
if user_input > 5 or user_input < 0 or user_input == 0:
print(">> Not a valid number.")
filmClicker()
elif score > 0:
score = score + random.randint(1, 50)
print("")
print(">> You produced:", score, "films", "<<")
go_back_or_menu = input(">> Press ENTER to go again. Or type TAB to go back to the menu. ")
print(go_back_or_menu)
if go_back_or_menu == "":
filmClicker()
elif go_back_or_menu == "TAB" or "Tab" or "tab":
game_menu()
# GAME MENU
def game_menu():
print(">>>>>>>>>>>>> Menu >>>>>>>>>>>>>")
print(">> Type A to go make films. ")
print(">> Type B to see your current balance. ")
print(">> Type C to see the current box office. ")
print(">> Type D for your stats. ")
press_button_menu = input("")
if press_button_menu == "A":
filmClicker()
elif press_button_menu == "B":
print("Current Balance =", score)
press_enter()
game_menu()
else:
filmClicker()
game_menu()
SECOND UPDATE:
Updated Code:
import random
score = 0
# PRINT BLANK LINE
def press_enter():
press_enter = print(input(""))
# SCORE
def filmClicker():
global score
user_input = int(input(">> Enter a number: "))
score += user_input
produced = random.randint(1, 50)
if user_input > 5 or user_input < 0 or user_input == 0:
print(">> Not a valid number.")
filmClicker()
elif score > 0:
score += produced
print("")
print(">> You produced:", produced, "films", "<<")
go_back_or_menu = input(">> Press ENTER to go again. Or type TAB to go back to the menu. ")
print(go_back_or_menu)
if go_back_or_menu == "":
filmClicker()
elif go_back_or_menu == "TAB" or "Tab" or "tab":
game_menu()
# GAME MENU
def game_menu():
print(">>>>>>>>>>>>> Menu >>>>>>>>>>>>>")
print(">> Type A to go make films. ")
print(">> Type B to see your current balance. ")
print(">> Type C to see the current box office. ")
print(">> Type D for your stats. ")
press_button_menu = input("")
if press_button_menu == "A":
filmClicker()
elif press_button_menu == "B":
print("Current Balance =", score)
press_enter()
game_menu()
else:
filmClicker()
game_menu()
In the picture below it's printing how much the player is producing from that turn but I also am testing the score (which is what the 6 and 49 stand for). It's scaling weird like that, where it adds a certain amount after every turn. Any way to fix this?
I think you are looking for the += operator.
Keep the score = 0 at the top of the file to initialize the variable, then use score += user_input to keep a running tally. This is the same as writing score = score + user_input.
In your filmClicker function, you should remove the following line:
score = user_input
By assigning to it, you've essentially erased its previous value which is why it doesn't accumulate between rounds.
For saving data, You can Use Files in python
For Saving:
f=open("data_game.txt","w")
f.write(<your score>)
f.close()
For Reading:
f=open("data_game.txt","r")
score=f.read()
print(score)
f.close()
i have to make this GUESS THE NUMBER Gamme from 1-100 that will restart if user wants to play again,
the user can try to find the number 10 times.
But i have a problem..
every time the user says "yes" to play again,the program will not change the random number,i try to find some solution but i didnt
here is the code
import random
guesses = 0 # μετραει ποσες προσπαθειεςς εγιναν απο τον χρηστη
print("Hello,lets play a game...and try to find the number i have guess!!")
number = random.randint(1, 100)
**while guesses < 11:
print('Please Guess a number from (1-100):')
enter = input()
enter = int(enter)
guesses = guesses + 1
if enter < number:
print('This number you enter is lower,please try again')
if enter > number:
print('This number you enter is higher,please try again')
if enter == number:
score = 10 - guesses
score = str(score)
guesses = str(guesses)
print('Well Done, You found it! \nYor Score is' + score + '!')
print('DO you want to play again; yes/no:')
out = input()
if out == "no":
break
elif out == "yes":
guesses = 0
if guesses > 10:
number = str(number)
print("i'm sorry you lost, the number is " + number)
print("Have a great time")**
In addition to reset the guesses inside the elif out == "yes" block, reset also the number. Try:
elif out == "yes":
guesses = 0
number = random.randint(1, 100)
i would like to know how to tell the computer to print different input for player using hint
and for someone who doesn't used it to congratulate them
import random
words = dict(
python = "type of snake",
honda = "type of car",
spanish = "type of language",)
word = list(words)
var = random.choice(word)
score = 0
chance = 5
x = list(var)
random.shuffle(x)
jumble = "".join(x)
print("the jumble word is :", jumble,)
while True:
guess = input(" this is my guess :")
if guess == "hint":
print(words[var])
if guess == var:
print("well done you only used ", score,"to guessed it ")
break
else:
print("try again")
score +=1
if score == chance:
print("better luck next time")
break
What about adding a boolean, say hintUsed, that keeps track of whether or not the user used a hint:
hintUsed = False
while True:
guess = input(" this is my guess :")
if guess == "hint":
hintUsed = True # change hintUsed to True !!
print(words[var])
And then, to congratulate:
if guess == var:
if hintUsed:
#print a message
else:
#print another message
break
I'm doing an assignment for the computer to generate a random number and have the user input their guess. The problem is I'm supposed to give the user an option to input 'Exit' and it will break the While loop. What am I doing wrong? I'm running it and it says there's something wrong with the line guess = int(input("Guess a number from 1 to 9: "))
import random
num = random.randint(1,10)
tries = 1
guess = 0
guess = int(input("Guess a number from 1 to 9: "))
while guess != num:
if guess == num:
tries = tries + 1
break
elif guess == str('Exit'):
break
elif guess > num:
guess = int(input("Too high! Guess again: "))
tries = tries + 1
continue
else:
guess = int(input("Too low! Guess again: "))
tries = tries + 1
continue
print("Exactly right!")
print("You guessed " + str(tries) + " times.")
The easiest solution is probably to create a function that gets the displayed message as an input and returns the user input after testing that it fulfils your criteria:
def guess_input(input_message):
flag = False
#endless loop until we are satisfied with the input
while True:
#asking for user input
guess = input(input_message)
#testing, if input was x or exit no matter if upper or lower case
if guess.lower() == "x" or guess.lower() == "exit":
#return string "x" as a sign that the user wants to quit
return "x"
#try to convert the input into a number
try:
guess = int(guess)
#it was a number, but not between 1 and 9
if guess > 9 or guess < 1:
#flag showing an illegal input
flag = True
else:
#yes input as expected a number, break out of while loop
break
except:
#input is not an integer number
flag = True
#not the input, we would like to see
if flag:
#give feedback
print("Sorry, I didn't get that.")
#and change the message displayed during the input routine
input_message = "I can only accept numbers from 1 to 9 (or X for eXit): "
continue
#give back the guessed number
return guess
You can call this from within your main program like
#the first guess
guess = guess_input("Guess a number from 1 to 9: ")
or
#giving feedback from previous input and asking for the next guess
guess = guess_input("Too high! Guess again (or X to eXit): ")
You are trying the parse the string 'Exit' to an integer.
You can add a try/except around the casting line and handle invalid input.
import random
num = random.randint(1,9)
tries = 1
guess = 0
guess = input("Guess a number from 1 to 9: ")
try:
guess = int(guess) // try to cast the guess to a int
while guess != num:
if guess == num:
tries = tries + 1
break
elif guess > num:
guess = int(input("Too high! Guess again: "))
tries = tries + 1
continue
else:
guess = int(input("Too low! Guess again: "))
tries = tries + 1
continue
print("Exactly right!")
print("You guessed " + str(tries) + " times.")
except ValueError:
if guess == str('Exit'):
print("Good bye")
else:
print("Invalid input")
my apologies if I'm asking a silly question, but I'm a bit confused...
I've been doing the MIT6.00X course at edx and one of the exercises is to use bisection search algorithm to find the secret number. It took me about 4 hours to finish the exercise (Yeah I'm a noob) but I managed to build this code:
numGuesses = 0
lo = 0
hi = 100
mid = (hi + lo)/2
num = raw_input( "Input a number between 0 and 100 ")
if num > 0 or num < 100:
while mid != num:
print ("Is your number " + str(mid) + "?")
userinput = raw_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 userinput == 'h':
hi = mid
mid = (hi + lo)/2
elif userinput == 'l':
lo = mid
mid = (hi + lo)/2
elif userinput == 'c':
print ("Game over. Your secret number was:" + str(mid))
break
else:
print ("Sorry, I did not understand your input.")
else:
print ("You should use a number between 0 and 100")
While testing it by hand it works just fine, although in the exercise there are a few questions that don't go through mainly because the site instead of keep guessing if it's higher or lower sometimes it presses the wrong key and I fail the exercise.
After trying to change the code I wasn't able to finish the course so I've seen the answer, and this is were I did wrong, I should had use a boolean to keep the code flowing until it finds the correct number.
My question is: Is my code that wrong? Also is there any mistake I did that's preventing the site to press the correct letter? Just curious
Many thanks
this is one of the MITx finger exercise that I just finally solved it today. here is my method:
print('Please think of an integers BETWEEN 0 and 100!')
#Define variable
x=100
low=0
high=x
ans=0
#Guessing code part
while ans<=x:
print'Is your secret number:', str((low+high)/2), '?'
s=raw_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 s!='h' and s!='l' and s!='c':
print'Sorry I did not understand your input.'
elif s=='h':
high=(low+high)/2
elif s=='l':
low=(low+high)/2
elif s=='c':
print'Game over. Your secret number is:', str((low+high)/2)
break
lo = 0
hi = 100
mid = (hi + lo)/2
print 'Please think of a number between 0 and 100!'
while True:
print ("Is your number " + str(mid) + "?")
userinput = raw_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 userinput == 'h':
hi = mid
mid = (hi + lo)/2
elif userinput == 'l':
lo = mid
mid = (hi + lo)/2
elif userinput == 'c':
print ("Game over. Your secret number was:" + str(mid))
break
else:
print ("Sorry, I did not understand your input.")