Try, except and input - python-3.x

Two programs seperated by -------------------------------------------------------------------------------------------
The program above the line is called program1
The program below the line is called program2
The only differens between the programs are int(input()) in program1 and input in program2
PS: I dont know what its called but in the text where I wrote "okd" (okayed) maybe I should write true?
The question/my line of thought:
In program1 if number: will be "okd" when number == integer and number != 0
In program2 if number: will be "okd" when number == string and number != 0
Does if number: check if number is what its trying to be in Try:
For example in program1 its trying to be an integer and in program2 its trying to be a string and in either program if number is what it tried to be it will be "okd" and the programs will return number and break?
def limit(question):
while True:
try:
number = int(input(question))
except:
number = 0
if number:
return number
break
question = "type an integer expressed with digits and press enter: "
number = limit(question)
print(number)
def limit(question):
while True:
try:
number = input(question)
except:
number = 0
if number:
return number
break
question = "type an integer expressed with digits and press enter: "
number = limit(question)
print(number)

The body of the if statement will NOT be evaluated if the expression given to it is False, 0, None, '', [], etc. The if statement will not try to detect if number is trying to be a string/int.
So if the user enters 0, then number = int(input(question)) will run just fine, but number will be zero, so the body of the if statement will not be evaluated.
The purpose of the try/except is to check if the statements in the try body will run in to errors. So if a user enters some numbers, then number = int(input(question)) will run without any problems. If a user enters something that is not an integer, then number = int(input(question)) will give you a ValueError, and the except block will catch the error and be evaluated.

Related

Python, How do I ignore a string such as 'done' amongst numbers to sum the total from a list

while True:
numbers = input('> ')
if numbers == 'done':
break
total = 0
for number in numbers:
if numbers == int:
total = total + numbers
print(total)
I've had a hard time understanding exactley what u want to do with this code, please use a proper code block next time, with proper indentation. My guess is that u want to get a input number like 345 and add 3+4+5 as a output. If the input is not a int it should break the loop. Ive come up with 2 diffrent solutions, depending on what you need.
This code will simply take the input and check if it is "done", if it is not "done" it will try to add. This is a easy to understand solution but it will produce a error if the input is any diffrent string than "done".
while True:
numbers = input(">")
if numbers == "done":
break
else:
total = 0
for number in numbers:
total += int(number)
print(total)
This approach will test for the "done" string again, but afterwards will also check if the input can be converted into a int. if not the error is captured and it will return "invalid input". If u want the programm to terminate at any string u can just put break in the except section.
while True:
numbers = input(">")
if numbers == "done":
break
else:
try:
testing = int(numbers)
total = 0
for number in numbers:
total += int(number)
except:
total = "invalid input"
print(total)
im a Beginner myself and if a experiencend person can show me a better way to do this i would be very interested
while True:
numbers = input('> ')
if numbers == 'done':
break
total = 0
for number in numbers:
if numbers == int:
total = total + numbers
print(total)
Assuming this as your code:
Here's a solution to your problem-->
numbers=[]
while True:
a=input('>')
if a=='done':
break
else:
numbers.append(a)
total=0
for number in numbers:
total = total + int(number)
print(total)
By default everything gets accepted as string so we convert it to integer to find total.
Also we use list to store all the values we accept.
Another Solution is-->
numbers=[]
while True:
a=input('>')
if a=='done':
break
else:
numbers.append(a)
p=map(int,numbers)
print(sum(p))
Hope you understand the solution :-)
total = 0
average = 0
count = 0
while True:
numbers = input('> ')
if numbers == 'done': break
try:
total = int(numbers) + total
count = count + 1
except:
print('nope')
try:
average = total / count
except:
print('error')
print(total)
print(average)
print(count)
Try this:
total = 0
number_of_inputs = 0
while True:
number_string = input('Enter a number: ')
try:
total += float(number_string)
number_of_inputs += 1
except ValueError:
break # we weren't given a number, so exit the loop
# Now that we're outside of the loop, print out the total:
print('The total is:', total)
if number_of_inputs > 0:
average = total / number_of_inputs
print('The average is:', average)
else:
print('The average cannot be calculated, as no inputs were given.')
Do you see what's happening? The while loop keeps ask for and adding integers to total until a non-integer (like "done") is given. Once it gets that non-integer, the int() function will fail, and the exception it throws will get caught, and the code will immediately break out of the while loop.
And once out of the loop, the total and the average are printed out.
A few things you should be aware of:
If the user gave no inputs (which is possible here), the total will correctly print out as 0, but if you try to calculate the average, you will error, due to diving by number_of_inputs (which is also 0). That is why I check that number_of_inputs is greater than zero before I even attempt to calculate the average.
Originally I used int() to convert the string to a number, but I changed it to use float() instead. I figure that since you want to calculate an average, averages are not necessarily integers (even if all the inputs are), so there's no point in enforcing integer input. That is why I changed the int() to float(), but whether or not you want to use it is up to you.
ValueError isn't a function; it's an Exception. At this point you probably don't know what Exceptions are, so just know that they are special cases that can happen, and they're often used for catching errors, such as bad input values.
In the code I posted above, the loop is always expecting numerical input. But as soon as we have input that can't be converted to a number, the program then says, "Hey, I have an exception to what we're expecting! The exception is that there's an error in the value!" Then the program, instead of continuing to the next line of code (which is number_of_inputs += 1) will then execute the block of code under the except ValueError: section. And in the code above, all it does is call break, which exits the loop.
Once out of the loop, the code prints out the total and the average.
If it weren't for the try: and except ValueError: lines in the code, then the program would abruptly end (with a lengthy error message) once someone gave a non-numerical input. That happens because the call to float() wouldn't know how to convert a value like "done" to a number, so it does nothing more than just quitting.
However, by using try: and except ValueError:, we are anticipating that someone might give non-numerical input. When that happens (which it will, when the user is finished giving inputs) -- instead of quitting -- we want an alternate action to take. And we specify that alternate action to be a simple break out of the loop -- which will allow the program to continue with whatever is after the loop.
I hope this makes sense. If it doesn't, it will make more sense once you start learning about Exceptions in Python.

What is the best way to deal with negative integers inputs in a python calculator?

Hello Fellow Developer's and Eng's:
How can I handle these two type's of input 1) when user enter "-0" and 2) When user enter minus symbol "-", within my while loop for adding nonnegative integers.
The program developed functions in the overall design, which is to add non negative integers, but it has a flaw when a user input -0 or -(minus) sign. I want to print('you have entered a negative int or a negative/minus - symbol') when these entries are made by the user.
Currently, the program continues without adding when user submit -0 in the input and there is ValueError when user just submit - symbol.
Please provide feedback.
entry = 0
sum = 0
# Request input from the user
print('This is nonnegative integer addition program. \n',)
while entry >= 0:
entry=int(input('Please enter numbers to add: '))
if entry >=0:
sum+=entry
elif entry<0 or str(entry[0])=='-' or str(entry)=='-0': # -0 nor (first index -(minus) does not work
print('You have entered a negative integer or symbol:', \
entry, ', therefore you have been exited out of the program')
print('total integer input sum =',sum)
As mentioned in the other answer. You convert your value to an int and you can no longer access the characters. I've made the program store the user_input and check that.
entry = 0
sum = 0
# Request input from the user
print('This is nonnegative integer addition program. \n',)
while entry >= 0:
user_input = input('Please enter numbers to add: ')
if '-' in user_input:
print(
'You have entered a negative integer or symbol:',
user_input,
', therefore you have been exited out of the program'
)
break
entry = int(user_input)
sum+=entry
print('total integer input sum =',sum)
In this version I store the input string as user_input and check it for a '-' symbol. I use '-' in instead of user_input[0]=='-' because input that starts with a space can still work with int.
Another thing to note, your if/elif was over specified.
if entry >=0:
sum+=entry
elif entry<0 or str(entry[0])=='-' or str(entry)=='-0':
break
In your second clause entry is guaranteed to be less than zero. So the str(entry[0]) never gets called. Thankfully because it was an error. Your if statement is equivalent to.
if entry>=0:
...
else:
...
Lastly a small point. When you have a set of brackets like in your print statment. You don't need a \ to indicate a line continuation.
print(
"one",
"two"
)
Python recognizes the open (. If you wanted to continue a string you would need it.
print("one \
two")
When you are storing the input as int entry=int(input('Please enter numbers to add: ')) the entry value is 0 because on int the is no -0 so if you want to check if the user input -0 you need to keep it as str.
You can try
entry = 0
sum = 0
print('This is nonnegative integer addition program. \n',)
while int(entry) >= 0:
entry=input('Please enter numbers to add: ')
if entry[0] !='-':
if int(entry) >= 0:
sum+=int(entry)
elif entry[0]=='-' or entry=='-0':
print('You have entered a negative integer or symbol:', \
entry, ', therefore you have been exited out of the program')
entry = -1
print('total integer input sum =',sum)

Python string comparison function with input, while loop, and if/else statment

I'm trying to create a program that takes input from the user, -1 or 1 to play or quit, number of characters (n), two words for comparison (s1,s2), and calls this function: def strNcompare (s1,s2,n) and then prints the result. The function should return 0,-1,1 if n-character portion of s1 is equal to, less than, or greater than the corresponding n-character of s2, respectively. So for example is the first string is equal to the second string, it should return a 0.
The loop should end when the user enters, -1.
I'm just starting out in Python so the code I have is pretty rough. I know I need an if/else statement to print the results using the return value of the function and a while loop to make the program run.
This is what I have so far, it by no means works but my knowledge ends here. I don't know how to integrate the character (n) piece at all either.
com = input ("String comparison [1(play), -1(quit)]: ")
while (com=='1'):
s1 = input ("enter first string: ")
s2 = input ("enter second string: ")
n = int(input("number of characters: ")
s1 = s1[:n]
s1 = s2[:n]
if com==-1:
break
def strNcompare(s1,s2,n):
return s1==s2
elif s1==s2:
print(f'{s1} is equal to {s2}')
elif s1>s2:
print (f'{s1} is greater than {s2}')
elif s1<s2:
print (f'{s1} is less than {s2}')
else:
print ("QUIT")
break
com = input ("String comparison [1(play), -1(quit)]: ")
As of 10/05/2019 - I revised the code and now I am getting a syntax error at "s1 = s1[:n]"
it did not made much sense and especially the variable 'n' is not completely clear to me. I would not code it like that but I tried to be as close to your logic as possible.
com = input ("String comparison [1(play), -1(quit)]: ")
while (com=='1'):
s1 = input ("enter first string: ")
s2 = input ("enter second string: ")
n = input ("number of characters: ") #what is the purpose of this?
if s1==s2:
print(f'{s1} is equal than {s2}')
elif s1>s2:
print (f'{s1} is greater than {s2}')
elif s1<s2:
print (f'{s1} is less than {s2}')
else:
print ("Error")

How to not include character or string input in the array (Python)

I'm trying to write a simple program where a variable will store the input type in by a user until the word "done" is seen. After that, the program will print out the maximum and minimum value store in the variable. However, I would like to prevent the variable from storing characters or strings where the user may accidentally type in. What are ways that I can use? Try and except?
a=0
store1=''
store2=''
while store1 !='done':
store1 = input('Enter a number: ')
store2=store2+' '+store1
a =a+1
store3=store2.split()
store4=store3[:a-1]
print('Maximum: %s'%(max(store4)))
print('Minimum: %s'%(min(store4)))
I tried another way and I got this problem. Does anyone know what is wrong?
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
a=0
store1=''
store2=''
while store1 !='done':
store1 = input('Enter a number: ')
b = RepresentsInt(store1)
if(b==True):
store2=store2+' '+store1
# a =a+1
store3=store2.split()
#store4=store3[:a-1]
print(store3)
print('Maximum: %s'%(max(store3)))
print('Minimum: %s'%(min(store3)))
#print(len(store3))
The stored value seems to contain only numbers in string-format. However, when it prints out the max and min values, it doesn't print out the correct max and min as the picture shown below.
Using your current implementation (number of issues), here's how you'd perform the check:
a=0
store1=''
store2=''
while store1 !='done':
store1 = input('Enter a number: ')
if store1 == 'done':
break;
try:
int(store1)
except ValueError:
continue
store2=store2+' '+store1
a =a+1
store3=store2.split()
store4=store3[:a-1]
print('Maximum: %s'%(max(store4)))
print('Minimum: %s'%(min(store4)))
I added in an immediate check for the input value (otherwise it executes the with the 'done' value, causing the Maximum: d output).
For the input checking, the approach is trying to convert the string to an integer and returning to the start of the loop if a ValueError is caught.
Using this looks like:
$ python3 input.py
Enter a number: 1
Enter a number: 2
Enter a number: what
Ivalid input.
Enter a number: 3
Enter a number: 4
Enter a number: done
Maximum: 3
Minimum: 1
So, we still have a problem with actually finding the maximum value. Which begs the question, why all the string manipulation?
Here's a simpler implementation using an array instead:
numbers = []
while True:
input_value = input('Enter a number: ')
if input_value == 'done':
break
try:
int_value = int(input_value)
except ValueError:
print("Ivalid input.")
continue
numbers.append(int_value)
print('Maximum: %s'%(max(numbers)))
print('Minimum: %s'%(min(numbers)))
Usage:
$ python3 input.py
Enter a number: 1
Enter a number: 2
Enter a number: what
Ivalid input.
Enter a number: 3
Enter a number: 4
Enter a number: done
Maximum: 4
Minimum: 1
EDIT: The problem with your second attempt is that you are performing a lexicographic sort, instead of a numerical one. This is due to fact that the array is storing string values.
# sorting strings, lexicographically
>>> [x for x in sorted(['1000', '80', '10'])]
['10', '1000', '80']
# sorting numbers, numerically
>>> [x for x in sorted([1000, 80, 10])]
[10, 80, 1000]
In my fixed example above, the strings are converted to integer values before they get stored in the array, so they end up being sorted numerically.

why is this not printing

This is from Ken Lambert's "Fundamentals of Python":
{
sum=0
while True:
data = input('enter a number or just enter to quit: ')
if data == "":
break
number = float(data)
sum += number
print("the sum is", sum)
}
error message:
data = input('enter a number or just enter to quit: ')
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
Process finished with exit code 1
Use raw_input rather than input. The description of input begins with:
Equivalent to eval(raw_input(prompt))
You're getting an error because eval("") reports a syntax error, because there's no expression there; it gets EOF immediately.
On the other hand, the description of raw_input says:
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
Since you want the string that the user typed, rather than the evaluation of an expression, this is the function you should use.
The error you provided is because you used input, which tries to execute the text from stdin as python code https://docs.python.org/2/library/functions.html#input. I've provided some fixes below.
sum=0
while True:
data = raw_input('enter a number or just enter to quit: ')
if len(data) < 1:
break
number = float(data)
sum += number
print("the sum is %f" % sum)
I found that you have a syntax problem with your code. If you want to to put data in a variable you should use that:
variable = raw_input("Please enter ____")
Therefore you should replace line 4 to:
data = raw_input('enter a number or just enter to quit: ')

Resources