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))
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.
import random
def diceroll():
x = random.randrange(1, 6)
print(x)
repeatroll()
def repeatRoll():
roll = input(print("Would you like to roll again?"))
if roll.upper()=="Y":
return diceroll()
elif roll.upper()=="N":
return print("You have chosen not to roll again")
else:
return print("Invalid input")
return roll
repeatRoll()
Can anyone explain to me why this returns None after the code asks for an input?
I always thought that it would be due to not having a return function.
I'm completely confused, I feel like the answer is obvious but i'm not quite getting it.
Help would be appreciated, thank you.
print() always return None
It doesn't return any value; returns None.
Since you called print() inside input().The print() returns none which is take as input by input()
Use :
print("Would you like to roll again?")
roll = input()
It can be because print statements do not return anything in python or simply saying print statements have a None type as return.
Your code required small modifications:
Try using this snippet
Calling repeatRoll() inside diceroll() wont work because it is not in the same scope. And your inputting format was also invalid
import random
def repeatRoll():
roll='Y'
while(roll=='Y'):
print("Would you like to roll again?")
roll = input()
if roll.upper()=="Y":
diceroll()
elif roll.upper()=="N":
return print("You have chosen not to roll again")
else:
return print("Invalid input")
def diceroll():
x = random.randrange(1, 6)
print(x)
repeatRoll()
Hope it helps:")
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
Ok, I am creating a memory game. I have developed where the programme asks the user what word was removed, and have successfully developed the part that moves on if they get it right. However, I am struggling to find how to get it to only fail the user if they get it wrong three times. Here's what I have so far:
def q1():
qone + 1
print("\n"*2)
while qone <= 3:
question1 = input("Which word has been removed? ")
if question1 == removed:
print("\n"*1)
print("Correct")
print("\n"*2)
q2()
else:
print("Incorrect")
q1()
else:
print("You're all out of guesses!")
input("Press enter to return to the menu")
menu()
return
`
My approach is to remove recursion and simply increase the counter of failed tries.
def q1():
qone = 0
print("\n"*2)
while qone < 3:
question1 = input("Which word has been removed? ")
if question1 == removed:
print("\n"*1)
print("Correct")
print("\n"*2)
q2()
return
else:
print("Incorrect")
qone += 1
print("You're all out of guesses!")
input("Press enter to return to the menu")
menu()
return
When you do qone + 1, you need to assign it to something (so perhaps qone += 1)
What is the else outside the while loop linked to?
You seem to have a recursive definition going. Think carefully about the chain of calls that would be made and what your base case should be. Once you know these things, it would be easier for you to write the code. Also, think about whether you need recursion at all: in this case, it doesn't seem like you would.
You should not have the function calling itself, use range for the loop, if the user gets the question correct go to the next question, if they get it wrong print the output:
def q1(removed):
print("\n"*2)
for i in range(3):
question1 = input("Which word has been removed? ")
if question1 == removed:
print("\nCorrect")
return q2()
print("\n\nIncorrect")
input("You're all out of guesses!\nPress enter to return to the menu")
return menu()
If the user has three bad guesses the loop will end and you will hit the "You're all out of guesses!\nPress enter to return to the menu"
I am trying to write a code for a text based chat-bot as my first full scale project and I am having a weird problem with while loops that I can't figure out. My primary loop is dependent on text input, what is supposed to happen is when the user types "bye" the program ends. The only problem is when I run it, no matter what I say to it, it just prints out the same response over and over until I hit cntrl.+c or close the window. Here is the code:
import datetime
print("Hi I am ChatBot V 0.0.1. I am here to converse. ")
user_name=raw_input("What is your name?")
print("Hello " + user_name + "!")
user_input=raw_input().lower().replace(" ","").replace("?","")
is_user_finished=0
while (is_user_finished == 0):
if user_input == "hi" or "hello":
print("Hello. How are you?")
elif user_input == "whatisyourname":
print("I do not have a name at the moment. What do you think I should be named?")
user_input=raw_input().lower().replace(" ","").replace("?","")
print("Good choice! I like that name!")
elif "where" and "you" in user_input:
print("I was typed up by some kid in California")
else:
print("I do not currently understand what you said. Sorry.")
if user_input == "bye":
print("Good bye. It was nice talking to you!")
is_user_finished = 1
What happens is that the line
if user_input == "hi" or "hello":
don't do what you think. Instead, you should do
if user_input == "hi" or user_input == "hello":
or even, in a more compact way:
if user_input in ["hi","hello"]:
Something similar happens with the line
elif "where" and "you" in user_input:
which should be
elif "where" in user_input and "you" in user_input:
syntax issue.
the correct form should be : if A == B or A == C, instead of A == B or C, which is incorrect.
You should change the line
if user_input == "hi" or "hello": to if user_input == "hi" or user_input == "hello":
and
"where" and "you" in user_input: to "where" in user_input and "you" in user_input:,
because "hello" and "where" is always True .
Besides you should put user_input=raw_input().lower().replace(" ","").replace("?","") into the while loop.
Provided you have proper indentation, which if the loop keeps running I assume you do, the problem, besides the things pointed out above about proper use of compound if statements is you need to add a "break" to the "bye" case.
if user_input == "bye":
print("Good bye. It was nice talking to you!")
is_user_finished = 1
break