Example
Good=1
Bad=2
print("How was your day?")
input()
if Good:
Print("That's nice.")
elif Bad:
Print("That's unfortunate")
For some reason this program always respond with "That's nice." even when I say bad.
if Good is always True, you have to assign input to a variable and then compare:
inp = input()
if inp == Good:
...
You aquired the input value, but did not assign it to a variable.
You should introduce a new variable (let's call it answer):
good=1
bad=2
print("How was your day?")
answer = input() ## <-- changed
if answer == good: ## <-- changed
print("That's nice.")
elif answer == bad: ## <-- changed
print("That's unfortunate")
You didn't assign the input value to a variable.Try the following code:
Good = 1
Bad = 2
print('How was your day?')
inputVal = int(input())
if inputVal == Good:
print("That's nice.")
elif inputVal == Bad:
print("That's unfortunate")
Input:1
Output:That's nice.
Input:2
Output:That's unfortunate
Related
I'm making a guess the number game. My code is almost complete but I need to make it so that the program asks the player if they want to play again and then restarts. Could someone help me with how I should go about that? I tried making a new function ex. def game_play_again and then call the game_play() function but it's not reseting the attempts which leads to it not looping correctly.
This is my code right now
import random
MIN = 1
MAX = 100
attempts = 5
win = False
number = random.randint(MIN,MAX)
last_hint = f"{'EVEN' if number%2 == 0 else 'ODD'}"
#print game instructions
def game_start():
print(f"Im thinking of a number between {MIN} and {MAX}. Can you guess it within
{attempts} attempts? ")
input("Press enter to start the game ")
#process user input
def game_play():
global number, attempts, last_hint, win
while attempts > 0:
print()
print(f"You have {attempts} {'attempts' if attempts > 1 else 'attempt'} left.")
if attempts == 1:
print(f"This is your last chance. So i'll give you one more hint. Its's an {last_hint} number.")
while True:
try:
guess = int(input("Try a lucky number: "))
if guess in range(MIN, MAX+1):
break
else:
print(f"Please enter numbers between {MIN} and {MAX} only!")
except ValueError:
print("Plese enter numbers only!")
if guess == number:
win = True
break
if attempts == 1:
break
if guess > number:
if guess-number > 5:
print("Your guess is too high. Try something lower.")
else:
print("Come on you are very close. Just a bit lower.")
else:
if number-guess > 5:
print("Your guess is too low. Try something higher.")
else:
print("Come on you are very close. Just a bit higher.")
attempts -= 1
#print game results
def game_finish(win):
if win:
print("Congratulations you guessed it!")
else:
print(f"The number I was thinking of is {number}. Sorry you lost. Better luck next time!")
game_start()
game_play()
game_finish(win)
You can simply reset your variables to initial values and then call game_play()
def game_finish(win):
if win:
print("Congratulations you guessed it!")
else:
print(f"The number I was thinking of is {number}. Sorry you lost. Better luck next time!")
want_play_again = int(input("Want play again? [1-Yes / 2-No]"))
if want_play_again == 1:
game_play_again()
else:
print("Bye")
/
def game_play_again():
attempts = 0
win = False
game_play()
Within a while(True) loop, write a menu driven statement asking the user if they want to repeat. If they do, initialise values and call game methods. If they do not, break the loop.
pseudocode:
while(True):
choice = input('play again? y/n)
if choice=='y':
attempts, win = 5, False
number = random.randint(MIN,MAX)
last_hint = f"{'EVEN' if number%2 == 0 else 'ODD'}"
game_start()
game_play()
game_finish()
elif choice=='n':
break
else:
print('invalid input')
The above code should be in main, with all methods within its scope.
Better yet, in place of all the initializations, add an init() method declaring them and call them when necessary.
The indentation in the code you have submitted is faulty, so I'm not sure if a related error is involved.
I have a menu function and choice function that both worked. There are 3 menu choices. 1 and 3 worked properly at one point. 2 never has. I don't know what I did to mess it up, but when I run the module to test through IDLE, it doesn't ever work past the first prompting to enter my menu choice number. It should complete an if statement, then restart.
I don't know what else to try. I wish I knew what I changed to mess it up.
tribbles = 1
modulus = 2
closer= 3
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
menu()
def choice():
choice = int(input('\n Enter the number of your menu choice: ')
if choice == tribbles:
bars = int(input('\n How many bars of gold-pressed latinum do you have? '))
print('\n You can buy ',bars * 5000 / 1000,' Tribbles.')
menu()
choice()
elif choice == modulus:
num = int(input('\n Enter any number:'))
o_e = num % 2
if num == 0:
print(num,' is an even number')
elif num == 1:
print(num,' is an odd number')
menu()
choice()
elif choice == closer:
print('\n Thanks for playing!')
exit()
else:
print('Invalid entry. Please try again...')
menu()
choice()
print(' ')
choice = int(input('\n Enter the number of your menu choice: '))
I expect it to return with the string plus all formula results, then asking again, unless option 3 was selected and exit() is performed. However it returns with "Enter the number of your menu choice: " after the first input, then it returns blank after choosing any other choice on the second prompt.f
First things first!
It's good practice to define all functions at the top of the file, and call those functions at the bottom! Second your indenting is incorrect, i'm going to assume that happened after you pasted it here. Finally, you never actually call the function choice() you instead overwrite it with the result of a prompt.
Below i'm going to correct these issues.
tribbles = 1
modulus = 2
closer= 3
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
choice() #added call to choice here because you always call choice after menu
def choice():
my_choice = int(raw_input('\nEnter the number of your menu choice: ')) #you were missing a ) here! and you were overwriting the function choice again
#changed choice var to my_choice everywhere
if my_choice == tribbles:
bars = int(raw_input('\nHow many bars of gold-pressed latinum do you have? '))
print('\n You can buy ',bars * 5000 / 1000,' Tribbles.')
menu()
elif my_choice == modulus:
num = int(raw_input('\n Enter any number:'))
o_e = num % 2
if num == 0:
print(num,' is an even number')
elif num == 1:
print(num,' is an odd number')
menu()
elif choice == closer:
print('\n Thanks for playing!')
exit()
else:
print('Invalid entry. Please try again...')
menu()
print(' ')
if __name__ == "__main__": #standard way to begin. This makes sure this is being called from this file and not when being imported. And it looks pretty!
menu()
Before you check the value of choice, the variable choice is not declared. You have to catch your input before the line: if choice == tribbles:. Your are only defining a function which even don't return the value of your choice or set a global variable.
Try this:
def menu():
print(' -MENU-')
print('1: Tribbles Exchange')
print('2: Odd or Even?')
print("3: I'm not in the mood...")
menu()
choice = int(input('\n Enter the number of your menu choice: '))
if choice == tribbles:
...
I am a python noob, I have little experience so the code you will witness is garbage. Its a number guessing game. I keep getting a syntax error on the last line pointing me to just before the parenthesis and I cant figure out what the hell is it trying to say. Also any interpreter suggestions? I have a license in VS but I find it to be infuriating to use.
def func_guessdude(x):
if user_input == x:
print("you got it")
elif user_input > x:
print("just a little less")
else:
print("just a little more")
user_input == 16
print func_guessdude(15)
You are missing parentheses in you last print: print(func_guessdude(15))
You just need to re-format this a bit:
def func_guessdude(x):
if user_input == x:
print("you got it")
elif user_input > x:
print("just a little less")
else:
print("just a little more")
user_input = 16
func_guessdude(15)
This returns "just a little less."
def func_guessdude(x):
global user_input
if user_input == x:
print("you got it")
elif user_input > x:
print("just a little less")
else:
print("just a little more")
user_input = 16
print func_guessdude(15)
Shouldn't your code be like:
user_input = 16
def func_guessdude(x):
if user_input == x:
return "you got it"
elif user_input > x:
return "just a little less"
else:
return "just a little more"
print (func_guessdude(15))
You initialized user_input after your if else, and also your method is not returning anything
Alright so I finally fixed it up to work fine, thanks to kfazi for clearing the main issue out. I am not completely sure what a global var is yet, have to google it. Thanks for the responses. This code should return "you got it"
def func_guessdude(x):
user_input = 16
if user_input == x:
return("you got it")
elif user_input > x:
return("just a little less")
else:
return("just a little more")
print(func_guessdude(16))
Why wont this stop when 'n' is entered?
I've tried using break on the bottom else but I get errors doing that. That's a common problem I have with break. I have no idea why I'm thrown off with break.
import random
def game():
secret_num = random.randint(1, 10)
guesses = []
while len(guesses) < 5:
try:
guess = int(input("Guess a number between 1 and 10: "))
except ValueError:
print("{} isn't a number".format(guess))
else:
if guess == secret_num:
print("You got it! The number was {}.".format(secret_num))
break
elif guess < secret_num:
print("My number is higher than {}".format(guess))
else:
print("My number is lower than {}".format(guess))
guesses.append(guess)
else:
print("You didn't get it! My number was {}".format(secret_num))
play_again = input("Do you want to play again? Y/n ")
if play_again.lower() != 'Y':
game()
else:
print("Bye!")
game()
You convert play_again to a lower-case letter but compare it to an upper-case letter.
You could simply change it to:
if play_again.lower() != 'n': # 'y' was wrong, right?
game()
else:
print("Bye!")
return # works also without the explicit return but it makes the intention clearer.
It doesn't tell you if the question is correct or not (when it should) and it doesn't do what it is supposed to when all of the questions have been asked. It should say this at the end: "You scored " + str(correctQuestions) + "/10 questions."
Here is the code:
import random
name = input("What is your name: ")
finish = False
questionNumber = 0
correctQuestions = 0
while finish == False:
op = ['+','-','*']
choice = random.choice(op)
if questionNumber < 10 and questionNumber >= 0:
number1 = random.randrange(1,10)
number2 = random.randrange(1,10)
print((number1),(choice),(number2))
answer=int(input("What is the answer?"))
questionNumber = questionNumber + 1
if choice==("+"):
realAnswer = number1+number2
elif answer==realAnswer:
print("That's the correct answer")
correctQuestions = correctQuestions + 1
else:
print("Wrong answer")
if choice==("*"):
realAnswer = number1*number2
elif answer==realAnswer:
print("That's the correct answer")
correctQuestions = correctQuestions + 1
else:
print("Wrong answer")
if choice==("-"):
realAnswer = number1-number2
elif answer==realAnswer:
print("That's the correct answer")
correctQuestions = correctQuestions + 1
else:
print("Wrong answer")
if finish == True:
print("You scored " + str(correctQuestions) + "/10 questions.")
As this looks like a homework exercise i will not solve it for you take some time and think about it. However here are some hints:
The variable finish is always False, it never gets updated, so its no wonder the game is never finished. Do something about that.
Second at line if choice==("+"): it can be possible that the variable choice does not exist (nor number1 and number2). Think about what you put under the while loop and what you don't.
Also there is a variable realAnswer in an elif statement while you did not declared it before. As the variable does not even exist, it will give you a NameError if it gets evaluated.
Let's say choice is *. Python gets to if choice==("+"):. The result: False, so it checks the elif: elif answer==realAnswer: At this point realAnswer has not yet been defined. You define realAnswer in the if block, but the if block did not execute. You need to take out the elif and else blocks from each choice, and instead put them at the end:
if answer == realAnswer:
print("That's the correct answer")
correctQuestions = correctQuestions + 1
else:
print("Wrong answer")
Also, you never define finish as anything but False. You use if questionNumber < 10 and questionNumber >= 0:, but you don't say what to do if questionNumber is not between 0 and 10. You need an else block that will break out of the loop.