`I'm trying to get this exception to trigger so I can see if python can handle when I input a string instead of an int.
I've tried changing the ValueError statement to a different type of exception such as TypeError instead of Value Error. I've also checked for syntax issues.
try:
u_list.append(userInput)
if userInput % 2 == 0:
list_sum += userInput
except ValueError: #this is supposed to be thrown when I put
# a string character instead of an int. Why is this
#not being invoked
#when I put a str character in?!?!
print("da fuq!?!. That ain't no int!")
I'm trying to get the program to print my last line shown when I input a string character, such as a (k) or something, instead it's throwing an error message.
Here's the full code that someone asked for:
u_list = []
list_sum = 0
for i in range(10):
userInput = int(input("Gimme a number: "))
try:
u_list.append(userInput)
if userInput % 2 == 0:
list_sum += userInput
except ValueError: #this is supposed to be thrown when I put
# a string character instead of an int. Why is this not being invoked
#when I put a str character in?!?!
print("da fuq!?!. That ain't no int!")
print("u_list: {}".format(u_list))
print("The sum of tha even numbers in u_list is: {}.".format(list_sum))
ValueError will be thrown when failing to convert a string to an int. input() (or raw_input() in Python 2) will always return a string, even if that string contains digits, and trying to treat it like an integer will not implicitly convert it for you. Try something like this:
try:
userInput = int(userInput)
except ValueError:
...
else:
# Runs if there's no ValueError
u_list.append(userInput)
...
Add the userInput in the try-except block and check it for ValueError. If its an integer then append it to the list.
Here's the Code:
u_list = []
list_sum = 0
for i in range(10):
try:
userInput = int(input("Gimme a number: "))
except ValueError:
print("da fuq!?!. That ain't no int!")
u_list.append(userInput)
if userInput % 2 == 0:
list_sum += userInput
print("u_list: {}".format(u_list))
print("The sum of tha even numbers in u_list is: {}.".format(list_sum))
I hope it helps!
Related
I am a beginner in python and I am currently working on a calculator not like this:
Enter Something: add
"Enter 1 number : 1"
"Enter 2 number : 3"
The answer is 5
not like that or using eval()
I Want to create a calculator where they input something like this: "add 1 3" and output should be 4.
but I have to check that the first word is a string 2nd is a integer or float and 3rd is also number
I have created a script but I have one problem that I don't know how to check if the input is a integer or string or float I have used isdigit() it works but it doesn't count negative numbers and float as a number I have also used isinstance() but it doesn't work and thinks that the input is a integer even when its a string and I don't know how to use the try and except method on this script
while True:
exitcond = ["exit","close","quit"]
operators =["add","subtract","multiply","divide"]
uinput = str(input())
lowereduin = uinput.lower()
splited = lowereduin.split(" ")
if lowereduin in exitcond:
break
if splited[0] == operators[0]:
if isinstance(splited[1],int) == True:
if isinstance(splited[2] , int) == True:
result = int(splited[1]) + int(splited[2])
print(result)
else:
print("enter a number")
else:
print("enter a number")
and when I run this script and type add 1 3 its says enter a number and when I only type add its give this error
Traceback (most recent call last):
File "C:\Users\Tyagiji\Documents\Python Projects\TRyinrg differet\experiments.py", line 11, in <module>
if isinstance(splited[1],int) == True:
IndexError: list index out of range
Can someone tell me what's this error and if this doesn't work can you tell me how to use try: method on this script.
You can try the following approach and play with type checking
import operator
while True:
exitcond = ["exit","close","quit"]
operators ={"add": operator.add,"subtract":operator.sub,"multiply": operator.mul,"divide":operator.truediv}
uinput = str(input())
lowereduin = uinput.lower()
splited = lowereduin.split(" ")
if lowereduin in exitcond or (len(splited) !=3):
break
try:
if splited[0] not in operators.keys():
raise ValueError(f"{splited[0]} not in {list(operators.keys())}")
op = operators.get(splited[0])
val = op(
*map(int, splited[1:])
)
print(val)
except (ValueError, ZeroDivisionError) as err:
print(err)
break
Building on Deepak's answer. A dictionary of operator names to functions is a good approach. And you can add to splits until you have enough numbers to proceed.
import operator as op
while True:
exitcond = ["exit","close","quit"]
operators = {"add": op.add,"subtract": op.sub, "multiply": op.mul, "divide": op.truediv}
splits = str(input()).lower().split()
if any(part in exitcond for part in splits):
break
while len(splits) < 3:
splits.append(input('Enter number: '))
try:
print(operators[splits[0]](*map(lambda x: float(x.replace(',','')), splits[1:3])))
except ZeroDivisionError:
print("Can't divide by 0")
except:
print('Expected input: add|subtract|multiply|divide [number1] [number2] -- or -- exit|quit|close')
Things to note, the lambda function removes all commas , as they fail for floats, and then converts the all number strings to floats. So, the answer will always be a float, which opens the can of worms that add 1.1 2.2 won't be exactly 3.3 due to the well documented issues with floating point arithmatic and computers
I've been trying to work on this assignment but for some reason the function I wrote won't return the list I specified and throws a name 'numbers' is not defined error at me when printing the list outside the function.
def inputNumbers():
try:
initial_number_input = int(input("Please enter the first number: "))
except ValueError:
print("This is not a number.")
return inputNumbers()
else:
numbers = []
numbers.append(initial_number_input)
if initial_number_input == 0:
return numbers
else:
i = 0
while True:
try:
number_input = int(input("Please enter the next number: "))
except ValueError:
print("This is not a number.")
continue
else:
numbers.append(number_input)
i += 1
if number_input == 0:
break
return numbers
inputNumbers()
print(numbers)
I'm still very new to programming so I am open to whatever suggestions you may have :D
Note that if I print(numbers) above return numbers at the end of the function, it does print the list.
Thanks
When you return a value from a function it needs to be assigned to something. At the moment you are returning numbers but nothing is using it.
To actually use the returned value your last 2 lines should be
numbers = inputNumbers()
print(numbers)
You can also just print the returned value without assigning it to a variable with
print(inputNumbers())
This question already has answers here:
How can I check if string input is a number?
(30 answers)
Closed 3 years ago.
I am working my way through Python for Everyone and I am stuck at this junction. To my eye I have stated that the ValueError is only to be raised if 'num' is anything other than a integer. However when I run the code the error is raised everytime regardless of input. Can anyone nudge me in the right direction?
Extensively googled but I'm not entirely too sure what specifically I should google for...
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num != int : raise ValueError
elif num == "done" : break
except ValueError:
print("Error. Please enter an integer or type 'done' to run the program.")
quit()
print("Maximum", largest)
print("Minimum", smallest)
The code always raises ValueError even when the input is an integer.
This line checks if the inputted string is literally equal to the builtin type int:
if num != int : raise ValueError
Other problem is that the input() function always returns a string. So if you want to raise a ValueError when the user inputs anything but a number, simply do:
inputted = input("Enter a number: ")
num = int(inputted) # raises ValueError when cannot be converted to int
If you want to check if the string entered can be converted into an int, just try it:
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
num = int(num)
except ValueError:
continue
I am trying to validate user input to check that, when they enter their name, it is more than 2 characters and is alphabetic. I am attempting to do this using try/except as I have been told that it is the best loop for user validation. Unfortunately if the user enters characters that are not alphabetic, nothing happens, and the program proceeds like normal. I also do not know how to check if the input is longer than 2 characters in the try/except loop as it is very new to me. Any help is much appreciated.
list = []
def users_name():
while True:
try:
name = str(input("Please enter your first name: "))
list.append(name)
break
except TypeError:
print("Letters only please.")
continue
except EOFError:
print("Please input something....")
continue
users_name()
You program will continue to run because of the continue clause in the catch block.
You can also check to see if the length of what they entered is longer than two characters.
list = []
def users_name():
while True: # Never ending loop
try:
name = str(input("Please enter your first name: "))
if (len(name) > 2)
list.append(name)
break
except TypeError:
print("Letters only please.")
continue # This causes it to continue
except EOFError:
print("Please input something....")
continue # This causes it to continue
users_name()
Also, you might want to stop the loop somehow. Maybe put in a break clause when you insert into the array?
if(len(name) > 2)
list.append(name)
break
...
To check if the input is a digit or an alphabet character use isdigit() or isalpha()
if a.isalpha():
#do something
elif a.isdigit():
#do something
Your code will then look like this:
list = []
def users_name():
while True: # Never ending loop
try:
name = str(input("Please enter your first name: "))
if (len(name) > 2 && name.isalpha()):
list.append(name)
break
else:
raise TypeError
except TypeError:
print("Letters only please.")
continue # This causes it to continue
except EOFError:
print("Please input something....")
continue # This causes it to continue
users_name()
Also if you are using Python < 3 consider using raw_input(). input() will actually evaluate the input as Python code.
To check the length of your String you can use the method len() to obtain its character length. You can then select those that are greater than 2 or your desired length.
To check if you string has only alphabetic characters you can use the str.isalpha() method to check so.
Therefore, if you check len(name) > 2 and name.isalpha() will help you filter those string that do not match what you want:
>>> name = "MyName"
>>> len(name) > 2 and name.isalpha()
True
>>> wrong_name = "My42Name"
>>> len(wrong_name) > 2 and wrong_name.isalpha()
False
>>> short_name = "A"
>>> len(short_name) > 2 and short_name.isalpha()
False
I have a question concerning int(). Part of my Python codes looks like this
string = input('Enter your number:')
n = int(string)
print n
So if the input string of int() is not a number, Python will report ValueError and stop running the remaining codes.
I wonder if there is a way to make the program re-ask for a valid string? So that the program won't just stop there.
Thanks!
You can use try except
while True:
try:
string = input('Enter your number:')
n = int(string)
print n
break
except ValueError:
pass
Put the whole thing in an infinite loop. You should catch and ignore ValueErrors but break out of the loop when you get a valid integer.
What you're looking for isTry / Except
How it works:
try:
# Code to "try".
except:
# If there's an error, trap the exception and continue.
continue
For your scenario:
def GetInput():
try:
string = input('Enter your number:')
n = int(string)
print n
except:
# Try to get input again.
GetInput()
n = None
while not isinstance(n, int):
try:
n = int(input('Enter your number:'))
except:
print('NAN')
While the others have mentioned that you can use the following method,
try :
except :
This is another way to do the same thing.
while True :
string = input('Enter your number:')
if string.isdigit() :
n = int(string)
print n
break
else :
print("You have not entered a valid number. Re-enter the number")
You can learn more about
Built-in String Functions from here.