Can't catch EOFError - python

What I expect from making this code is, I input some numbers, then when I input strings the output is 'Not Valid', but when I press enter without putting some value to input, the output is the sum of numbers that we input before. But when I run it on VSCode, whenever I press enter, the result always 'Not Valid', and can't get out of the loop.
For example, I input: 1 2 3 a z then the output I expect is: Not valid Not valid 6
I don't know what is wrong, I just learned python 2 months ago.
sum = 0
while True:
try:
sum += int(input())
except ValueError:
print('Not Valid')
except EOFError:
print(sum)
break

When you don't input anything, input() will return the empty string. Converting it to an integer is invalid, so you get the ValueError:
>>> input() # next line is empty because I just pressed Enter
'' # `input()` returned the empty string
>>> int('') # can't convert it to an integer
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''
To trigger EOFError, send the EOF signal with Ctrl + D:
>>> input()
^DTraceback (most recent call last):
File "<stdin>", line 1, in <module>
EOFError
Here the ^D represents me pressing Ctrl + D on the keyboard (not literally typing "^D").

Related

TypeError: not all arguments converted during string formatting.(Armstrong number)

n=input("enter the number: ")
num=n
digit,sum=0,0
length=len(str(n))
for i in range(length):
digit=int(num%10)
num=num/10
sum+=pow(digit,length)
if sum==n:
print("armstrong")
else:
print("Not armstrong")
when I run this code, it show error in line 6:
Traceback (most recent call last):
File "<string>", line 6, in <module>
TypeError: not all arguments converted during string formatting>
the question is find the number is Armstrong or not.
You need to first convert the string into an integer before performing any mathematical operation.
Here is the revised code.
n=input("enter the number: ")
num=n
digit,sum=0,0
length=len(str(n))
for i in range(length):
digit=int(num)%10
num=int(num)/10
sum+=pow(digit,length)
if sum==n:
print("armstrong")
else:
print("Not armstrong")
Before using the num variable convert it to an int to avoid any error.

Is a there exception if you ask for a integer and do not get an integer?

I am trying to make a program where you enter an integer, but if you do not enter an integer, handle it with an exception. However I can not find any exceptions for integers on the internet.
### TECH SUPPORT ###
while True:
try:
i = int(input('Enter an INTEGER: '))
except [INT EXCEPTION HERE]:
print("You must enter an INTEGER, not any other format of data")
-
Does anyone know an exception if you ask for an integer input and do not get an integer?
You can always try it in interpreter to see which error gets raised:
>>> int('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'a'
Now that you know that it is ValueError, just change your code:
while True:
try:
i = int(input('Enter an INTEGER: '))
except ValueError:
print("You must enter an INTEGER, not any other format of data")
else:
break # to exit the while loop
Yes, use ValueError
More about python try except. Go through the builtin exceptions list, which will help you.
Also, when an builtin exception is raised like so -
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'a'
You can see
ValueError: invalid literal for int() with base 10: 'a'
So python raisesValueError and this is the exception you need to use.
You can use "ValueError" exception
while True:
try:
i = int(input('Enter an INTEGER: '))
except ValueError:
print("You must enter an INTEGER, not any other format of data")

Can´t convert string to integer in python

I´m getting this error while trying to convert string to integer:
Traceback (most recent call last):
File "main.py", line 9, in <module>
n = int(input())
ValueError: invalid literal for int() with base 10: 'python3 main.py'
This is the code:
n = int(input())
if num>0:
cantPos = cantPos+1
You're probably not realizing that the interpreter is prompting you for input. The input() function takes a string argument which will be the prompt. The common pattern to do here is something like:
n = None
while n is None:
try:
n = int(input('Please enter an integer: '))
except ValueError:
print('That was not an integer!')

What does " 'int' object has no attribute '_getitem_' " mean for my code?

I just started Python and as a starter I'm trying to make a calculator (just four functions)
So this is the code:
input_start = input("press 1 to perform addition press 2 to perform subtraction press 3 to perform multiplication press 4 to perform division press 5 to quit")
if input_start == 1:
input_a = input("put your first number here:")
print input_a
if int(input_a[0]) == (1,2,3,4,5,6,7,8,9,0):
input_b = input("put your second number here:")
print input_b
if int(input_b[0]) == (1,2,3,4,5,6,7,8,9,0):
print input_a + input_b
else:
print "invalid"
else:
print "invalid"
print input_start
It's like this for other functions. When I run it, this error comes up:
Traceback (most recent call last):
File "C:\Users\Baik\Desktop\python projects\calculator.py", line 6, in <module>
if int(input_a[0]) == (1,2,3,4,5,6,7,8,9,0):
TypeError: 'int' object has no attribute '__getitem__'
What does the error mean and how can I fix this? I know this sounds like I'm asking you guys to fix my code, but I don't know what the error means.
input_a[0] equals to input_a.__getitem__(0), here your input_a is a int, and it don't hava such a method.
I think you are using python2.x, the input function will parse the input automaically if it is a number.
input_start = input("press 1 to perform addition press 2 to perform subtraction press 3 to perform multiplication press 4 to perform division press 5 to quit")
if input_start == 1:
input_a = input("put your first number here:")
print input_a
if isinstance(input_a, int):
input_b = input("put your second number here:")
print input_b
if isinstance(input_b, int):
print input_a + input_b
else:
print "invalid"
else:
print "invalid"
print input_start
The problem is input_a[0] - this tries to get the first index of input_a. The square brackets are really short for the __getitem__ method. However, input returns a plain int, which doesn't have a __getitem__ method.
This error means that you can't do [0] on an integer:
>>> 5[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'
Since you are using input, any code that is valid type will be converted automatically. This means that if the user types 5 when you prompt with "put your first number here:", python will take it as the number 5, not the string '5'.
You also have a lot of other issues, the major one being this line:
if int(input_a[0]) == (1,2,3,4,5,6,7,8,9,0)
This isn't doing what you think it is. I suspect you want to say "if input_a is either 1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9 or 0, but what its actually doing is "if the integer value of the item at index 0 pointed to by the name input_a is the same as the tuple (1,2,3,4,5,6,7,8,9,0)"
If you want to say is if the input is between 0 and 9, so you can do that with:
if 0 < input_a < 9:
# do something
If you want to check if the input is a number, you can try converting it:
input_a = int(input_a)
But this will raise a ValueError exception if input_a can't be converted into a number, like this:
>>> input_a = 'hello'
>>> int(input_a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'hello'
Another way to check if input is a number is to use the the isdigit() method of strings:
>>> input_a = '5'
>>> input_a.isdigit()
True
Keep in mind that this won't work if the value is already a number, because numbers don't have a isdigit() method:
>>> input_a = 5
>>> input_a.isdigit()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'isdigit'
So, to make your life easy, you need to first convert the input to a string. To do that, replace input( with raw_input(.
For the rest, as this looks like homework, I leave it up to you.

Calculator exception handling, why does this example work but mine does not?

For a bit of python practice, I decided to work on a calculator tutorial. It was very basic, so I decided to give it exception handling in the event a user enters in garbage. While proper use of the program still works, punching in crap still causes it to crash, and entering
Here is my code:
loop = 1
choice = 0
while loop == 1:
#print out the options you have
print "Welcome to calculator.py"
print "your options are:"
print " "
print "1) Addition"
print "2) Subtraction"
print "3) Multiplication"
print "4) Division"
print "5) Quit calculator.py"
print " "
choice = input("choose your option: ")
try:
if choice == 1:
add1 = input("add this: ")
add2= input("to this: ")
print add1, "+", add2, "=", add1+ add2
elif choice == 2:
sub1 = input("Subtract this ")
sub2 = input("from this")
print sub1, "-", sub2, "=", sub1 - sub2
elif choice == 3:
mul1 = input("Multiply this: ")
mul2 = input("with this: ")
print mul1, "x", mul2, "=", mul1 * mul2
elif choice == 4:
div1 = input("Divide this: ")
div2 = input("by this: ")
if div2 == 0:
print "Error! Cannot divide by zero! You'll destroy the universe! ;)"
else:
print div1, "/", div2, "=", div1 * div2
elif choice == 5:
loop = 0
else:
print "%d is not valid input. Please enter 1, 2 ,3 ,4 or 5." % choice
except ValueError:
print "%r is not valid input. Please enter 1, 2, 3, 4 or 5." % choice
print "Thank you for using calculator.py!"
Now while I found an useable answer here: Error Handling Variables in a calculator program, Error handling numbers are fine
I was wondering why my code didn't work. Does python want the exception handling in a function? That's the vibe I'm getting from it.
In Python 2 (which is what you are using) input evaluates as Python code whatever the user enters. Because of this input can raise many different exceptions, but rarely a ValueError.
Better would be to accept your input with the raw_input which returns a string, and then cast to the expected type. If the input is invalid it will then raise a ValueError:
>>> x = int(raw_input("enter something: "))
enter something: sdjf
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'sdjf'
Note: In Python 3 input assumes the semantics of Python 2's raw_input and raw_input goes away.
You're catching ValueError, which is the wrong thing to catch.
Take a look how input() works:
>>> print input.__doc__
input([prompt]) -> value
Equivalent to eval(raw_input(prompt)).
So what it's doing is evaluating what you type in at that point, in the same way it evaluates anything you type in an interactive Python session. For example, I get a NameError if I try to enter garbagestring at a prompt, for the same reason I get a NameError if I try to enter garbagestring at the interactive prompt:
>>> garbagestring
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'garbagestring' is not defined
The correct way to do this is to use raw_input() in place of input(), then convert the string that returns into an integer:
>>> raw_input('Prompt: ')
Prompt: garbagestring
'garbagestring'
>>> int(raw_input('Prompt: '))
Prompt: garbagestring
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'garbagestring'
>>> int(raw_input('Prompt: '))
Prompt: 45
45
This will catch the error as you use it.
Note in general you should avoid doing anything that looks vaguely like an eval(). Generally you can achieve anything you need to without it, and eval() is potentially a security risk if using a string you don't trust. For example, if I add import os (a pretty damn common import) at the top of your script, I can do this:
Multiply this: os.listdir('/')
with this: 0
['bin', 'cygdrive', 'dev', 'etc', 'home', 'lib', 'tmp', 'usr', 'var', 'proc'] x 0 = []
Thank you for using calculator.py!
I could just as easily read files, delete vital folders, etc etc.
input does an eval() on user's input, input basically does a eval(raw_input(prompt))
So if you input loop, it won't fail, it actually will set choice to 1.
If you input a, it will eval and raise a NameError exception.
If you input 1 + 1 it will substract.
I hope you get the idea.

Categories

Resources