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.
Related
optionone = 0 #DEFINING BOTH VARIABLES
optiontwo = 0
class first_day_morning: #WORKING
optionone = input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ")
def first_choice(optionone): #NOT WORKING DOING ELSE COMMAND FOR 1 INPUT
if optionone == 1:
time.sleep(1)
print('')
print("You have chosen to get out of the house for once")
elif optionone == 2:
time.sleep(1)
print('')
print("DO LATER")
else:
time.sleep(1)
print('')
print("please choose a valid option")
first_choice(int(input()))
I am trying to make it so that the user input decides the outcome of the if statement, if user inputs 1, then something happens, if user inputs 2 then something else happens, if user inputs anything else, than the if statement runs again as only 1 or 2 are valid inputs. However, the problem is that no matter what the user inputs, the if statement does not run, and no error is shown either. I tried a try/except in case an error just isn't showing for some reason (try except ValueError:) and nothing seemed to work I have also tried to specify the input as str, int, float, no specification, raw_input etc. and nothing really works, can someone help?
ps. I am using Visual Studio Code
As you can see, the if statement does not run as no error is shown even after user input.
When the program runs, the class body will be evaluated, meaning the input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ") will prompt for input. That value will then be kept in first_day_morning.optionone, however first_choice's optionone is different. It is equal to the parameter supplied on the final line, int(input()), which will silently prompt for another input, and then convert it to an integer. From what I think you're trying to achieve, I'd recommend you remove the class and change the final line to:
first_choice(int(input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ")))
def first_choice():
print('')
print("You have chosen to get out of the house for once")
def second_choice():
print('')
print("DO LATER")
def third_choice():
print('')
print("please choose a valid option")
while True:
print("""Select a choice""")
c = int(input('enter your choice:'))
if c == 1:
first_choice()
elif c == 2:
second_choice()
elif c == 3:
third_choice()
elif c == 4:
break
i dont really understand what u r trying to acomplish here, but the code works for me, some tips from a beginer:
-you define optiontwo and never use it
-you you are filling optionone with input inside a class, dont know why, cause is never used
not sure what do u want, but try this:
import time
def first_choice(optionone): #NOT WORKING DOING ELSE COMMAND FOR 1 INPUT
if optionone == 1:
time.sleep(1)
print('')
print("You have chosen to get out of the house for once")
elif optionone == 2:
time.sleep(1)
print('')
print("DO LATER")
else:
time.sleep(1)
print('')
print("please choose a valid option")
first_choice(int(input("It is now morning, would you like to (1) Leave your house or (2) Do some chores? ")))
although, test it in console, not sure about vscode but running inside sublime does not ask for input
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
I am stuck on a problem that I am trying to solve. I am only suppose to take int (1-4) from user's input and not take any string/float/etc. I have figured out what to do if a user chooses any integer other than 1-4. However, I am stuck on the part where a user chooses anything other than an integer (i.e string, float, etc).
this is what I have done so far:
def menu():
my code
menu()
# keeps on looping till user have selected a proper selection (1-4)
selection = int(input("> "))
if selection == 1:
my code
elif selection == 2:
my code
elif selection == 3:
my code
elif selection == 4:
my code
else:
print("I'm sorry, that's not a valid selection. Please enter a
selection from 1-4. ")
menu()
Any help would be appriciated. I've been trying to find a solution for hours but got stuck on the last part.
Seeing as you don't appear to be doing any integer operations on the value coming from input - I would personally just leave it as a string.
selection = input("> ")
if selection == "1":
pass
elif selection == "2":
pass
#...
else:
print("I'm sorry...")
By doing this you don't have to deal with that edge case at all.
If you must (for some reason) cast this to an int (like, you're using the value later) then you could consider using exception handling.
try:
selection = int(input("> "))
except ValueError:
selection = "INVALID VALUE"
and the continue you on, as your current else statement will catch this and correctly handle it.
try this If you make sure that your code allows the user to input only numbers in python:
def numInput():
try:
number = int(input("Tell me a number"))
except:
print "You must enter a number"
numInput()
return number
You can use an infinite loop to keep asking the user for an integer within the desired range until the user enters one:
while True:
try:
selection = int(input("> "))
if 1 <= selection <= 4:
break
raise RuntimeError()
except ValueError, RuntimeError:
print("Please enter a valid integer between 1 and 4.")
I am just starting out and can't figure this one out.
I am writing a program to do some simple calculations for me at school.
Different calculations will be accessible through input of simple numbers from 1 to X. Every number will call a function just for that calculation.
My problem is this:
I want that if the user enters an empty string when prompted for a number, the program will ask the user to re enter a number for a certain amount of times before closing. Here's my code:
def pick_procedure():
procedure = raw_input("> ")
if not procedure:
counter = 0
print "Enter a value. "
while counter <4:
counter = counter + 1
main()
if counter == 4:
break
def main():
print "\nStudy helper 1.0.\n"
print """Procedure list:
1.Area of circle.
2. Circumference of a circle.
Please pick a procedure: """
pick_procedure()
main()
No matter how many times an empty string is entered, the program does not close.
How to do it correctly and cleaner?
As you say, you need to reorganise your code:
def pick_procedure(valid_choices):
print "Enter a value. "
for _ in range(4): # prompt for a choice up to 4 times
choice = raw_input("> ")
if choice in valid_choices:
return choice
return None # A valid choice was not entered
def main():
print "\nStudy helper 1.0.\n"
choice = 1
while choice:
print """Procedure list:
1. Area of circle.
2. Circumference of a circle.
Please pick a procedure: """
choice = pick_procedure(["1", "2"])
if choice:
print "Doing choice", choice
main()
The following approach makes use of a while choice loop to keep prompting if a valid choice is entered. If no choice is entered 4 times, the pick_procedure() function returns None causing the while loop to exit cleanly. If a valid choice is entered, it returns that choice.
I also pass the list of valid responses to the function, that way the function can be used for other questions simply by passing a different list of valid responses.
You created a vicious circle.
First time that procedure is false, pick_procedure calls main and then main calls again pick_procedure. It continues recursively.
If you just want to finish the program when an event is fired, you can use sys.exit(0) and your problems are solved.
# 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")
I have updated my code with the changes made. I am still getting incorrect results...
# Import statements
import random
# Define main function that will ask for input, generate computer choice,
# determine winner and show output when finished.
def main():
# Initialize Accumulators
tie = 0
win = 0
lose = 0
score = 0
# initialize variables
user = 0
computer = 0
# Initialize loop control variable
again = 'y'
while again == 'y':
userInput()
computerInput()
if score == win:
print('You won this round, good job!')
win += 1
elif score == tie:
print('You tied this round, please try again!')
tie += 1
else:
print('You lost this round, please try again!')
lose += 1
again = input('Would you like to play another round (y/n)? ')
#determine winning average
average = (win / (win + lose + tie))
print('You won ', win, 'games against the computer!')
print('You lost ', lose, 'games against the computer.')
print('You tied with the computer for', tie)
print('Your winning average is', average)
print('Thanks for playing!!')
# get user input for calculation
def userInput():
print('Welcome to Rock, Paper, Scissor!')
print('Please make your selection and and Good Luck!')
print('1) Rock')
print('2) Paper')
print('3) Scissor')
user = int(input('Please enter your selection here: '))
print('You selected', user)
# get compter input for calculation
def computerInput():
computer = random.randint(1, 3)
print('The computer chose', computer)
def getScore():
if user == 1 and computer == 3:
score = win
return score
elif user == 2 and computer == 1:
score = win
return score
elif user == 3 and computer == 2:
score = win
return score
elif user == computer:
score = tie
return score
else:
score = lose
return score
# Call Main
main()
In Python:
>>> print("3" == 3)
False
Strings and integers are values of different data types, and will not compare equal. Try changing your input to:
userInput = int(input('Please enter your selection here: '))
This will convert the string typed by the user to a number for later comparison. (Note that I have assumed you are using Python 3.x, because input() behaves slightly differently in Python 2.x.)
Note that this will throw an error if you type anything other than a number.
Update: As pointed out by #FelipeFG in the comments below, you are also overwriting the function userInput with the value typed by the user. You'll need to change the name of one or the other, for example:
def getUserInput():
...
Also don't forget to change the place where you call the function. Do the same for computerInput (change to getComputerInput).
Later on, you can change those to actual functions that return values.
userInput() calls the function "userInput", but you discard the result. The same remark applies to computerInput().
userInput == 1 asks whether the function userInput itself is equal to 1. It isn't. The same remark applies to computerInput == 3 and the others.
In the function "userInput", userInput = ... binds the name "userInput" to the result of the expression. This makes "userInput" a local variable of the function. The function doesn't explcitly return anything, therefore it returns None.
If you're using Python 3, input returns a string, and you should convert its result to an int. If you're using Python 2, input evaluates whatever is entered, which isn't safe; you should use raw_input instead and convert its result to an int.
You need to compare against the return value of your function, not the function itself.
Also:
again = input('Would you like to play another round (y/n)? ')
This will throw an exception if you enter y or n, because there is no defined identifier of that name! What you want to use instead is raw_input()
Edit: As pointed out by Greg, this only applies to Python 2.x. You seem to be using Python3 though.