My Guessing game isn't able to print out the dialogue - python

beginner here!
My question is, why doesn't the terminal say the prints?
import random
print(" Guess number between 1-5")
def Guessinggame(Number = int(random.randint(1, 5))):
if input == Number:
return "YOU'RE AWESOME!"
else:
return "Not correct"
while():
Guessinggame()
It's a guessing game where you have to guess between the number 1 and 5.

You can try this:
import random
def Guessinggame(inp):
Number = random.randint(1, 5)
print(inp,Number)
if inp == Number:
return "YOU'RE AWESOME!"
else:
return "Not correct"
while True:
inp=int(input("Guess number between 1-5"))
print(Guessinggame(inp))
Here what we are doing is, program starts from while loop. The correct way to use while loop is while <condition>, if you are doing while() then it is calling while function. After infinitely while loop start, we are asking user to input number and we are saving that number in inp variable. Now we are sending inp variable into Guessinggame function. Inside this we are creating new variable number which is random number. And now we are checking if user input number same to random number or not. And return YOU'RE AWESOME is true and return Not correct if false. And that return will be printed because we are calling function inside print.

return will only return the value, not print it. You need to call the print function to print the value.
print(Guessinggame())
Also, your program has some logical error it should be
import random
print(" Guess number between 1-5")
def Guessinggame(guess,Number):
if guess== Number:
return "YOU'RE AWESOME!"
else:
return "Not correct"
while True:
y=int(input("enter a number: "))
x= int(random.randint(1, 5))
print(Guessinggame(y,x))

Your guessing game function is returning either "YOU'RE AWESOME" or "Not correct", but there is no print statement included. To demonstrate what's going on, we could include an extra variable in your code:
import random
def Guessinggame():
# I've added in an input function to get the user input
user_input = input(" Guess number between 1-5")
Number = int(random.randint(1, 5)) # more readable here
if user_input == Number:
return "YOU'RE AWESOME!"
else:
return "Not correct"
while True:
outcome = Guessinggame()
print(outcome)
Now "YOU'RE AWESOME!" or "Not correct" gets stored inside of the outcome variable. Printing outcome will show the result. Note that you can cut out the outcome variable completely by printing Guessinggame(), I just wanted to show you what's happening.
Note that you'll also need to convert Number from an integer to string-type to compare it with the user input (user input is stored as string):
import random
def Guessinggame():
# I've added in an input function to get the user input
user_input = input(" Guess number between 1-5")
Number = str(random.randint(1, 5)) # convert to string-type
if user_input == Number:
return "YOU'RE AWESOME!"
else:
return "Not correct"
while True:
outcome = Guessinggame()
print(outcome)
For more on type conversion, you check out this article I posted on LearnDataSci:
https://www.learndatasci.com/solutions/python-typeerror-list-indices-must-be-integers-or-slices-not-str/

Related

How to know if any python function is asking for input or not and if asking then enter input? [duplicate]

This question already has answers here:
How can I mock user input (from "input" in 3.x, or "raw_input" in 2.x) for a unit test?
(7 answers)
Closed last month.
Suppose I have a function like this:
import random
def randomfunc():
x = random.randint(0,10)
# some code here which generates a name/text randomly and stores it in a .txt file locally/cloud
if x%2 == 0:
y=input("Enter your name:") # I need to enter that name/text exact here
print("Your name is ",y)
else:
print("You got an odd number")
Now, whenever I run this function then I want it to detect if it is asking for any input or not.
If it's asking for input then enter the input else do nothing.
Remember I can't change anything inside the function.
I tried this:
import builtins
from unittest.mock import patch
with patch('builtins.input') as input_mock:
input_mock.side_effect = [
'My Name',
]
print(input('Enter your name:'))
But the problem here is that the input is predetermined before the execution of the input statement.
In my case, my input value will be decided while the execution of randomfunc() as my input value is dynamic/it changes with time.
Also, when using wexpect module, it gives me OSError: [WinError 6] The handle is invalid.
Please suggest me some solution.
I believe that is what you want
def randomfunc():
x = random.randint(0, 10)
if x % 2 == 0:
y = input("Enter your name:")
print("Your name is ", y)
else:
print("You got an odd number")
def better_randomfunc(user_input):
with mock.patch('builtins.input') as MockClass:
MockClass.return_value = user_input
randomfunc()
This will replace every input() in randomfunc with your own one that'll return user_input. So if there's no input function it's going to do nothing like you asked.
To use this just call the better_randomfunc
better_randomfunc("My name")
And expect double space, if you want to get rid of that do print("Your name is", y) instead of print("Your name is ", y)
Edit: I improved it a little bit so that you can modify it based on prompt
import random
from unittest import mock
def randomfunc():
x = random.randint(0, 10)
if x % 2 == 0:
y = input("Enter your name: ")
print("Your name is", y)
else:
print("You got an odd number")
def better_input(prompt, user_input):
print(prompt + user_input)
return user_input
def better_randomfunc(user_input):
with mock.patch('builtins.input') as MockClass:
MockClass.side_effect = lambda prompt: better_input(prompt, user_input)
randomfunc()
better_randomfunc("My name")
You can replace the builtin input function
import random
input_values = [1,2,3,4]
input_iterator = iter(input_values)
def randomfunc():
x = random.randint(0,10)
if x%2 == 0:
y=input("Enter your name:")
print("Your name is ",y)
else:
print("You got an odd number")
def custom_input(v):
global input_iterator
print('custom input called')
# input(*args, **kwargs)
return next(input_iterator)
setattr(__builtins__, 'input', custom_input)
while(True):
try:
randomfunc()
except StopIteration:
print('done')
break
You got an odd number
custom input called
Your name is 1
custom input called
Your name is 2
custom input called
Your name is 3
You got an odd number
You got an odd number
You got an odd number
custom input called
Your name is 4
You got an odd number
custom input called
done

How to end a try loop in a dice game at the correct place?

I am trying to make a program where the player enters a number (1-6) to guess what a fair randomised dice lands on.
Then it should stimulate the dice throw, and informs the player whether it was correct or not.
It should continue to ask the player to guess by entering a number until the guess is correct.
If it is correct the game should end.
If it is not correct the game continues to ask the player to select a number.
I have tried:
from random import randint
def validateNumber():
valid = False
if 1 <= number_in <=6:
valid = True
return valid
game_1 = randint(1,6)
while True:
try:
number_in = int(input("Enter a number between 1-6: "))
is_valid = validateNumber()
if not is_valid:
number_in = int(input("Enter a number between 1-6: "))
if number_in == game_1:
print(f"The result was {game_1}. Your guess was correct!")
else:
print(f"The result was {game_1}. Your guess was NOT correct. Please try again")
except ValueError:
break
However, now it does not end when the guess is correct.
Does anyone know how to fix this?
I have tried many variants, but this is the closest I got to the wanted result, but still it is not satisfactory. Also it does not seem to truly handle the user input?
(I am quite new to Python and trying to learn the most before starting college in January:)) All help appreciated!
Your main issue is that you should break out of the while loop when the user guess the number. You have a couple of other issues:
if the user inputs an invalid number twice, you accept it the second time
it would be better to pass number_in to validateNumber as a parameter rather than relying on a global
if the user inputs something which is not an integer, the game terminates
Note also you can simplify validateNumber as follows:
def validateNumber(number):
return 1 <= number <= 6
Overall I would rewrite the code as:
from random import randint
def validateNumber(number):
return 1 <= number <= 6
game_1 = randint(1, 6)
while True:
# play game
is_valid = False
while not is_valid:
# read an input
try:
number_in = int(input("Enter a number between 1-6: "))
is_valid = validateNumber(number_in)
except ValueError:
pass
# check the input
if number_in == game_1:
print(f"The result was {game_1}. Your guess was correct!")
# all done
break
else:
print(f"The result was {game_1}. Your guess was NOT correct. Please try again")
# get another number for them to guess
game_1 = randint(1, 6)
After you get correct answer (number_in == game_1), you should break the while.
I think, this is what you want:
from random import randint
def validateNumber():
valid = False
if 1 <= number_in <= 6:
valid = True
return valid
game_1 = randint(1, 6)
guess_was_correct = False
while not guess_was_correct:
is_valid = False
while not is_valid:
try:
number_in = int(input("Enter a number between 1-6: "))
is_valid = validateNumber()
if not is_valid:
print("You entered a number outside of the 1-6 range. Please enter a number between 1 and 6!")
except ValueError:
print("You did not enter a number. Please enter a number.")
if number_in == game_1:
print(f"The result was {game_1}. Your guess was correct!")
guess_was_correct = True
else:
print(f"The result was {game_1}. Your guess was NOT correct. Please try again")
You need an inner loop to check the validity of the input, and the exception handling needs to go there too.
Checking the correctness of the guess is done in the outer loop. It's a separate thing and needs to be done only once we have a valid input.

Name Error in python from function

I have a code here that uses functions to draw outputs. I keep getting "prompt" is not defined but isn't it already stated in the function filterer?
[enter image description here][1]
def menu():
print ("[1] Compute Area of a Circle")
print ("[2] Compute Perimeter of a Rectangle")
print ("[3] Compute Volume of a Cone")
print ("[4] Compute Slope of a Straight Line")
print ("[5] Exit")
#Determining the input of the user
choice = filterer("Choose from the menu:")
#function for the filter
def filterer(prompt):
while True:
choice = float(input(prompt))
if choice > 5 or choice < 1:
print ("Must input integer between 1 and 5. Input again")
elif choice.is_integer == False:
print ("Must put an integer. Input again.")
else:
return prompt
filterer(choice)
#Hamms and #stybl both answered this in the comments, however, just to be clear, you need to change
filterer(prompt)
into
filterer("do some amazing thing or something")
Except with the quote you want to use as a prompt instead of "do some amazing thing or something."
The key to this is to think about the scope of the code. filterer(prompt) assumes prompt is defined by the time it's called. But you're calling it without ever defining a prompt. You could define the prompt if you wanted to, for example,
prompt = "do something super groovy"
filterer(prompt)
Others have pointed out the main issue, which is that you're trying to reference a variable (prompt) which doesn't exist in that scope.
That said, I don't think you want to call filterer twice, and I don't think you want it to return the prompt, but rather the choice made. Also, your integer testing wasn't right.
Here's full working code:
def filterer(prompt):
while True:
try:
choice = int(input(prompt))
except ValueError:
# Value couldn't be parsed as an integer
print("You must enter an integer. Try again.")
else:
# Value was successfully parsed
if choice > 5 or choice < 1:
print("Must input integer between 1 and 5. Input again")
else:
return choice # <-- changed from prompt
def menu():
print("[1] Compute Area of a Circle")
print("[2] Compute Perimeter of a Rectangle")
print("[3] Compute Volume of a Cone")
print("[4] Compute Slope of a Straight Line")
print("[5] Exit")
# Determining the input of the user
choice = filterer("Choose from the menu: ")
print("You chose: {}".format(choice))
menu()
prompt is defined within the scope of the function filterer, so it cannot be accessed outside the function. The line:
filterer(prompt)
Should be changed to something like:
foo=filterer(bar)
The variable bar has to be defined before doing this.

Python does not accept my input as a real number

# Math Quizzes
import random
import math
import operator
def questions():
# Gets the name of the user
name= ("Alz")## input("What is your name")
for i in range(10):
#Generates the questions
number1 = random.randint(0,100)
number2 = random.randint(1,10)
#Creates a Dictionary containg the Opernads
Operands ={'+':operator.add,
'-':operator.sub,
'*':operator.mul,
'/':operator.truediv}
#Creast a list containing a dictionary with the Operands
Ops= random.choice(list(Operands.keys()))
# Makes the Answer variable avialabe to the whole program
global answer
# Gets the answer
answer= Operands.get(Ops)(number1,number2)
# Makes the Sum variable avialbe to the whole program
global Sum
# Ask the user the question
Sum = ('What is {} {} {} {}?'.format(number1,Ops,number2,name))
print (Sum)
global UserAnswer
UserAnswer= input()
if UserAnswer == input():
UserAnswer= float(input())
elif UserAnswer != float() :
print("Please enter a correct input")
def score(Sum,answer):
score = 0
for i in range(10):
correct= answer
if UserAnswer == correct:
score +=1
print("You got it right")
else:
return("You got it wrong")
print ("You got",score,"out of 10")
questions()
score(Sum,answer)
When I enter a float number into the console the console prints out this:
What is 95 * 10 Alz?
950
Please enter a correct input
I'm just curious on how I would make the console not print out the message and the proper number.
this is a way to make sure you get something that can be interpreted as a float from the user:
while True:
try:
user_input = float(input('number? '))
break
except ValueError:
print('that was not a float; try again...')
print(user_input)
the idea is to try to cast the string entered by the user to a float and ask again as long as that fails. if it checks out, break from the (infinite) loop.
You could structure the conditional if statement such that it cause number types more than just float
if UserAnswer == input():
UserAnswer= float(input())
elif UserAnswer != float() :
print("Please enter a correct input")
Trace through your code to understand why it doesn't work:
UserAnswer= input()
This line offers no prompt to the user. Then it will read characters from standard input until it reaches the end of a line. The characters read are assigned to the variable UserAnswer (as type str).
if UserAnswer == input():
Again offer no prompt to the user before reading input. The new input is compared to the value in UserAnswer (which was just entered on the previous line). If this new input is equal to the previous input then execute the next block.
UserAnswer= float(input())
For a third time in a row, read input without presenting a prompt. Try to parse this third input as a floating point number. An exception will be raised if this new input can not be parsed. If it is parsed it is assigned to UserAnswer.
elif UserAnswer != float() :
This expression is evaluated only when the second input does not equal the first. If this is confusing, then that is because the code is equally confusing (and probably not what you want). The first input (which is a string) is compared to a newly created float object with the default value returned by the float() function.
Since a string is never equal to a float this not-equals test will always be true.
print("Please enter a correct input")
and thus this message is printed.
Change this entire section of code to something like this (but this is only a representative example, you may, in fact, want some different behavior):
while True:
try:
raw_UserAnswer = input("Please enter an answer:")
UserAnswer = float(raw_UserAnswer)
break
except ValueError:
print("Please enter a correct input")

Number Guessing Game in Python

I was trying to create a simple random number guessing game. The problem is even if I type the correct number it replies with a 'The number is less than'. Can somebody provide me a solution for this one ?
Thanks in advance
import random
import sys
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
user = raw_input('Guess The Number\n Pick between 1 - 10\n >>> ')
try:
int(user)
except:
print "Numbers Only !"
sys.exit(0)
number = random.choice(numbers)
int(number)
for i in range(0, 4):
if number == user:
print 'You Won!'
if user > number:
print 'The number is less than', user
user = raw_input('>>> ')
try:
int(user)
except:
print "Numbers Only !"
if user < number:
print 'The number is bigger than', user
user = raw_input('>>> ')
int(user)
print "The Number was", number
The biggest problem is that you're not saving the conversion to int so you're using the guess as the string the user entered. You need to save it by doing user = int(raw_input('>>>'))
There are other ways you can improve this code, however. You repeat yourself a bit, and you don't need random.choice, you can use random.randrange(1, 10)
You shouldn't just say except:. You wanna only catch the exceptions you are looking for. The particular exception you are looking for is a ValueError
Additionally, I suggest you let the user try again when they enter something that's not a number. You can wrap up the whole thing in it's own function.
import random
def get_user_num(msg='>>> '):
"""Print the msg parameter as a prompt for the user to enter a number. If
they enter an invalid string, reprompt them until they enter a number.
"""
while True:
try:
return int(raw_input(msg)) # save the conversion to int
except ValueError: # only except the error you're actually looking for
print 'Numbers Only!'
# 'from 1-9' is probably better than 'between 1-10'
user = get_user_num('Guess The Number\n Pick from 1-9\n>>> ')
number = random.randrange(1, 10) # <- numbers list is unnecessary
#int(number) # this conversion was never needed, it was already a number
for _ in range(4): # you don't need (0, 4), 0 is assumed
if number == user:
print 'You Won!' # the correct number has been guessed
break # exit the loop once the number has been correctly guessed
elif user > number:
print 'The number is less than', user
elif user < number:
print 'The number is bigger than', user
# Don't repeat yourself, put this outside the `if`s
user = get_user_num()
else:
#only print the answer when it wasn't guessed correctly
print "The Number was", number
When you convert to int(user), you aren't saving a new int to user. So user still remains a string.
What you need to do is
user = int(user)
By the way, this is for all of the places where you use int(user)
This could be done with a much simpler implementation:
import random
number = random.randrange(10)
for i in xrange(4):
try:
user = int(raw_input('guess: '))
except ValueError:
print 'must be int'
continue
if user == number:
print 'bravo'
break
elif user < number:
print 'greater'
else:
print 'lesser'
print 'it was: %d' % number

Categories