def total():
n = prompt()
answer = (n-2)*180
print ("The polygon has", answer, "sides.")
def prompt():
x = raw_input("Type number: ")
return x
I'm trying to get n which is equal to the output of prompt to be an integer so that math can be done on it. How would I do this?
raw_input returns a string, so you cannot use it for any calculations. If you want to have an integer instead, you can use the int function to convert the value. You can do that either within your prompt function, or later in the calling function (although it would make more sense to have a function that asks the user for a number return one):
def prompt ():
x = raw_input("Type a number: ")
return int(x)
Note, that int() may raise a ValueError for any user entered value that is not a valid integer. In that case, you should catch the exception and prompt the user again to correct the input. See this question on how that would work.
Related
So, I have a homework where I'm assigned to write multiple python codes to accomplish certain tasks.
one of them is: Prompt user to input a text and an integer value. Repeat the string n
times and assign the result to a variable.
It's also mentioned that the code should be written in a way to avoid any errors (inputting integer when asked for text...)
Keep in mind this is the first time in my life I've attempted to write any code (I've looked up instructions for guidance)
import string
allowed_chars = string.ascii_letters + "'" + "-" + " "
allowed_chars.isalpha()
x = int
y = str
z = x and y
while True:
try:
x = int(input("Enter an integer: "))
except ValueError:
print("Please enter a valid integer: ")
continue
else:
break
while True:
try:
answer = str
y = answer(input("Enter a text: "))
except ValueError:
print("Please enter a valid text")
continue
else:
print(x*y)
break
This is what I got, validating the integer is working, but I can't validate the input for the text, it completes the operation for whatever input. I tried using the ".isalpha()" but it always results in "str is not callable"
I'm also a bit confused on the assigning the result to a variable part.
Any help would be greatly appreciated.
Looks like you are on the right track, but you have a lot of extra confusing items. I believe your real question is: how do I enforce alpha character string inputs?
In that case input() in python always returns a string.
So in your first case if you put in a valid integer say number 1, it actually returns "1". But then you try to convert it to an integer and if it fails the conversion you ask the user to try again.
In the second case, you have a lot of extra stuff. You only need to get the returned user input string y and check if is has only alpha characters in it. See below.
while True:
x = input("Enter an integer: ")
try:
x = int(x)
except ValueError:
print("Please enter a valid integer: ")
continue
break
while True:
y = input("Enter a text: ")
if not y.isalpha():
print("Please enter a valid text")
continue
else:
print(x*y)
break
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I am making this game where the user has to choose from 5 options. So, he must type any number from 1 to 5 to choose an option. Now here is the problem I am facing, I just can't figure out a way in which the user cannot type in any other character except the int numbers from 1 to 5, and if he does type in a wrong character, how should I show his error and make him type in the input again? Here is what I've tried:
def validateOpt(v):
try:
x = int(v)
if int(v)<=0:
x=validateOpt(input("Please enter a valid number: "))
elif int(v)>5:
x=validateOpt(input("Please enter a valid number: "))
return x
except:
x=validateOpt(input("Please enter a valid number: "))
return x
Here validateOpt is to validate the number for the option, i.e., 1,2,3,4,5. It works fine, but whenever I type 33,22, 55, or any other int number from 1 to 5 twice (not thrice or even four times, but only twice), it doesn't show any error and moves on, and that, I suppose, is wrong. I am just a beginner.
You can do this with a while loop, something like this should be a good start:
def getValidInt(prompt, mini, maxi):
# Go forever if necessary, return will stop
while True:
# Output the prompt without newline.
print(prompt, end="")
# Get line input, try convert to int, make None if invalid.
try:
intVal = int(input())
except ValueError:
intVal = None
# If valid and within range, return it.
if intVal is not None and intVal >= mini and intVal <= maxi:
return intVal
Then call it with something like:
numOneToFive = getValidInt("Enter a number, 1 to 5 inclusive: ", 1, 5)
use a while loop instead of recursion, you can check the user data and return if its valid, although you might want to consider a break out clause should the user want to exit or quit without a valid input.
def get_input(minimum, maximum):
while True:
try:
x = int(input(f"please enter a valid number from {minimum} to {maximum}: "))
if minimum <= x <= maximum:
return x
except ValueError as ve:
print("Thats not a valid input")
value = get_input(1, 5)
Use for loop in the range between 1 and 5
Try this code, it will keep prompting user till he enters 5, note that this may cause stackoverflow if recursion is too deep:
def f():
x = input("Enter an integer between 1 and 5:")
try:
x = int(x)
if x<=0 or x>5:
f()
except:
f()
f()
I have worked on many projects (school projects, I'm not too advanced), and have found that in many programs where I require the user to input a value that is an integer, or decimal(float), I need to use a "try-except" statement, within a while loop, in order to make certain that the user inputs the required value type.
For example:
def main():
userValue = input("Please enter an integer: ")
while(True):
try:
userValue = int(userValue)
break
except:
userValue = input("That is not an integer, try again: ")
print("The integer you entered is: " + str(userValue))
main()
# Input: SADASD (A non-integer value)
# Output: "That is not an integer, try again: "
# Second-Input: 3
# Second-Output: "The integer you entered is: 3"
Understandably, typing out this entire section of code repeatedly, in a program that requires user input multiple times, is not really efficient. So understanding, that user-defined functions help when I need to perform one action, multiple times. With this in mind, I defined my own function with that same try-except statement in a while loop. However, now, when I use the function, instead of printing the same output previously, rather, it prints out the first value the user had input.
For example:
def valueCheck_Integer(userInput):
while(True):
try:
userInput= int(userInput)
break
except:
userInput = input("That is not an integer, try again: ")
def main():
userValue = input("Please enter an integer: ")
valueCheck_Integer(userValue)
print("The integer you entered is: " + str(userValue))
main()
# Input: SADASD (A non-integer value)
# Output: "That is not an integer, try again: "
# Second-Input: SASASD
# Second-Output: "That is not an integer, try again: "
# Third-Input: 3
# Third-Output: SADASD (The first value that the user Input, instead of 3)
Can someone please explain to me why this happens, and some suggestions on how to fix it?
Thank you!
It's probably going to be easier to expect the function to get/check/return the integer rather than check input you already have. You can pass it the string to use for asking for the value (you could also pass the error string). It will keep asking until it's successful and then return the number you want:
def get_integer(question):
while(True):
try:
return int(input(question))
except ValueError:
question = "That is not an integer, try again:"
def main():
userValue = get_integer("Please enter an integer: ")
print("The integer you entered is: " + str(userValue))
main()
It is because of you are printing userValue instead of userInput.
I used return make it easier. So the code will be like this
def valueCheck_Integer(userInput):
while(True):
try:
userInput= int(userInput)
break
except:
userInput = input("That is not an integer, try again: ")
return userInput
def main():
userValue = input("Please enter an integer: ")
print("The integer you entered is: " + str(valueCheck_Integer(userValue)))
main()
You can make your code smaller like this:
def valueCheck_Integer(userInput):
while not(userInput.isdigit()):
userInput = input("That is not an integer, try again: ")
return userInput
def main():
userValue = input("Please enter an integer: ")
print("The integer you entered is: " + str(valueCheck_Integer(userValue)))
main()
First off, Good Question.
To understand what is going on, we first have to talk about scope of a variable.
When you define a variable outside a function, it becomes something called a global variable. This basically means that you can access it from anywhere in your code. When you define the variable within a function, it becomes a local variable. This means that it is only accessible from within your function. Finally, when a function gets passed in a variable, it gets its own local copy of the variable to work with.
Now let's look at your code.
when you call valueCheck_Integer(userInput): the function gets its own copy of userInput to work with. thus all the changes that the function does modifies the local userInput while the global userInput stays the same. As such, when the user enters a correct answer, the global userInput is the one that gets printed and the changes the function makes to local userInput is lost.
So, how can we fix this?
There are two main methods:
1)Using the global keyword
def valueCheck_Integer(userInput):
global userInput
while(True):
try:
userInput= int(userInput)
break
except:
userInput = input("That is not an integer, try again: ")
This keyword asks the function to modify the global userInput
2)Returning a value
def valueCheck_Integer(userInput):
while(True):
try:
userInput= int(userInput)
break
except:
userInput = input("That is not an integer, try again: ")
return userInput
def main():
userValue = input("Please enter an integer: ")
print("The integer you entered is: " + str(valueCheck_Integer(userValue)))
main()
This works by returning the local copy of userInput and modifying global userInput to equal local userInput
The second code I used was from
Osadhi Virochana Jayasinghe Si's answer.
It's because, if you see your line of code where you print the final output -:
print("The integer you entered is: " + str(userValue))
you will realise that the value you are printing is the one you take the first time from the input function. But this is not the value you have been working on to achieve in your other function.
So for you to rather get that value, the function in some way has to return it back to you.
For this you should allow the function to return the value in the last line.
like so -:
return userInput
and then change the line where you call function so it saves the value returned.
like so -:
userValue = valueCheck_Integer(userValue)
Also as mentioned by others using the global keyword you can define the variable in global scope.
But this is really not a good practice until really needed as it can increase the amount of space that the var is taking, before the variable only took the space for a limited time for when the function is called, but now the variable takes space throughout the time the program runs.
While return will not do so as it will only return the value and once assigned to the already defined variable it will remove the returned value from space.
This should hopefully fix your problem.
I hope this helps.
And also hope that you're safe during the time of this ongoing pandemic.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 8 years ago.
user_input = float(input("Please enter a multiplier!")
if user_input == int:
print " Please enter a number"
else:
for multiplier in range (1,13,1):
print multiplier, "x", user_input, " = ", multiplier * user_input
The program will run effectively, as for any number entered by the user the result will be effective, yet I wish to know a function that allows the user to ask for a number when they enter a letter.
Use a try/except inside a while loop:
while True:
try:
user_input = float(raw_input("Please enter a multiplier!"))
except ValueError:
print "Invalid input, please enter a number"
continue # if we get here input is invalid so ask again
else: # else user entered correct input
for multiplier in range (1,13,1):
print multiplier, "x", user_input, " = ", multiplier * user_input
break
Something that's a float is not an int. They're separate types. You can have a float that represents an integral value, like 1.0, but it's still a float.
(Also, user_input == int isn't checking whether user_input is an int, it's checking whether user_input is actually the type int; you wanted isinstance(user_input, int). But since that still won't work, let's skim over this part…)
So, can you check that a float has an integral value? Well, you can do this:
if int(user_input) == user_input
Why? Because 1.0 and 1 are equal, even though they're not the same type, while 1.1 and 1 are not equal. So, truncating a float to an int changes the value into something not-equal if it's not an integral value.
But there's a problem with this. float is inherently a lossy type. For example, 10000000000000000.1 is equal to 10000000000000000 (on any platform with IEEE-854 double as the float type, which is almost all platforms), because a float can't handle enough precision to distinguish between the two. So, assuming you want to disallow the first one, you have to do it before you convert to float.
How can you do that? The easiest way to check whether something is possible in Python is to try it. You can get the user input as a string by calling raw_input instead of input, and you can try to convert it to an int with the int function. so:
user_input = raw_input("Please enter a multiplier!")
try:
user_input = int(user_input)
except ValueError:
print " Please enter a number"
If you need to ultimately convert the input to a float, you can always do that after converting it to an int:
user_input = raw_input("Please enter a multiplier!")
try:
user_input = int(user_input)
except ValueError:
print " Please enter a number"
else:
user_input = float(user_input)
You could use the assert-statment in python:
assert type(user_input) == int, 'Not a number'
This should raise an AssertionError if type is not int. The function controlling your interface could than handle the AssertionError e.g. by restarting the dialog-function
I've been banging my head against the wall with this task and I can't seem to figure it out for the life of me.
I want to write a script that would prompt a user to input a number and store that number in a list every time after they input the number. When the user would just press enter and not input anything, the script would then print out the highest number in the list.
This is what I wrote so far:
x = 0
mylist = []
while x != '':
x = input("enter a number:")
mylist.append(x)
if x == '':
print(max(mylist))
There are two problems with this code that I can see:
The user can input a string (I tried fixing that by saying x = int(input(...), but that only lead to a new error:
ValueError: invalid literal for int() with base 10: ''
print(max(mylist)) only prints out the number with the largest initial integer. For instance, if the user inputs 51 and 112, it would print out 51.
Thank you for taking your time in helping me out.
Use a different variable to test the While. Check isnumeric() for the input, and if it is numeric, convert it as you append it to your array:
keepMoving = True
mylist = []
while keepMoving:
x = input("enter a number:")
if x.isnumeric():
mylist.append(int(x))
else:
keepMoving = False
print(max(mylist))
I suggest you use a try statement to check if the input is an integer. The following is an implementation which attempts to convert the user input into an integer, and append that to the list. In the result of a ValueError (a non-int input), it will print the largest integer in the list. Using raw_input instead of input is also a good practice here, to prevent python from trying and failing to convert the input on its own.
x=0
mylist=[]
while x!='':
x = raw_input("enter a number:")
try:
x = int(x)
mylist.append(x)
except ValueError:
if x == '':
print(max(mylist))
This prevents the user from adding non-integers to the list, and is a better way to handle unexpected user input. As an added bonus, this method also makes it easy to add more conditions in the future.