Coverting an input string into an interger - python-3.x

#This program calculates the average of integer entered
#Once the use press "S".
#"S" is the sentinel
COUNT= 0
SUM= 0
INT=1
Sentinel = "S"
print('Enter test scores as integers, or enter S to get average.')
INT=input('Enter integer: ') # input received as a string to allow for the entry of "S"
#Continue processing as long as the user
#does not enter S
while INT!= Sentinel:
INT=input('Enter integer: ')
I=int(INT) #attempting to format the input(INT) as an integer
COUNT= + 1
SUM = COUNT + I
if INT == Sentinel:
AVRG= SUM/(COUNT-1)
I keep getting this error message :
Traceback (most recent call last):
File "C:\Users\joshu\Documents\COP100 Python\practice examples\program4-13.py", line 16, in
I=int(INT)
ValueError: invalid literal for int() with base 10: 'S'

Your code is assuming that the user will always enter a numeric value.
This line will accept any data entered by the user. It could be numeric or non-numeric.
INT=input('Enter integer: ') # input received as a string to allow for the entry of "S"
Before you convert the data into integer, check if the value is numeric. If it is not, then you may want to send an error message back to the user.
I=int(INT) #attempting to format the input(INT) as an integer
You can do that by doing:
if INT.isnumeric():
I = int(INT)
else:
print ('not a numeric value')
I am assuming that users will enter only integers. The above code will work only for integers. If you want to check for floats, then use a try: except statement.
Also, your computation of SUM to get the average is incorrect. You shouldn't add COUNT to SUM. You should only add I to SUM while incrementing COUNT.
Also don't try to use variable names as sum, int (even if it is uppercase).
Here's a working code for you to try.
count = 0
total = 0
Sentinel = "S"
#Continue processing as long as the user does not enter S
while True:
test_score = input('Enter test score as integer or enter S to get average: ')
# input received as a string to allow for the entry of "S"
if test_score.isnumeric():
score = int(test_score) #attempting to format the input(INT) as an integer
count += 1
total += score
elif test_score.upper() == Sentinel:
break
else:
print ('Not an integer or S. Please re-enter the value')
if count > 0:
print (total, count)
average_score = total/count
print ('average score is : ', average_score)
else:
print ('No valid entries were made. Average score is N/A')

Related

Want to get input on same line for variables at different places in Python3. See the below code and text for clarification

I want to take input of how many inputs the user is going to give next and collect those inputs in a single line. For eg. if user enters '3' next he has to give 3 inputs like '4' '5' '6' on the same line.
N = int(input())
result = 0
randomlist = []
for number in range(N):
K = int(input())
for number2 in range(K):
a = int(input())
if number2 != K - 1:#Ignore these on below
result += a - 1
else:
result += a
randomlist.append(result)
result = 0
break
for num in range(N):
b = randomlist[num]
print(b)
Now I want the input for K and a (also looped inputs of a) to be on the same line. I have enclosed the whole code for the program here. Please give me a solution on how to get input in the same line with a space in between instead of hitting enter and giving inputs
Based on what I read from your question, you are trying to request input from the user and the desired format of the input is a series of numbers (both integers and floats) separated by spaces.
I see a couple of ways to accomplish this:
Use a single input statement to request the series of numbers including the count,
Just ask the user for a list of numbers separated by spaces and infer the count.
To perform these operations you can do one of the following:
#Request User to provide a count followed by the numbers
def getInputwithCount():
# Return a list Numbers entered by User
while True:
resp = input("Enter a count followed by a series of numbers: ").split(' ')
if len(resp) != int(resp[0]) + 1:
print("Your Input is incorrect, try again")
else:
break
rslt = []
for v in resp[1:]:
try:
rslt.append(int(v))
except:
rslt.append(float(v))
return rslt
or for the simpler solution just ask for the numbers as follows:
def getInput():
# Return the list of numbers entered by the user
resp = input("Enter a series of numbers: ").split(' ')
rslt = []
for v in resp:
try:
rslt.append(int(v))
except:
rslt.append(float(v))
return rslt

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)

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.

Finding the product of user input lines

Using Python 3.6.2 - Completely new to programming, and I need to find the product, sum, and average of user input. I have the sum and average down, but I can't seem to get the product to function right. This is what I have so far...
#Request input from user
sum = 0
while True:
try:
numVar = int(input("Specify number of variables to be entered: "))
break
except ValueError:
pass
while True:
try:
raw = input("Enter a number or press enter for results: ")
break
except ValueError:
pass
while raw != "":
raw = input("Enter a number or press enter for results: ")
numbers = int(raw)
sum += numbers
ave = round(sum / numVar, 1)
prd = 1
for count in range(numbers):
count = count + 1
prd *= count
#Print results
print("The sum is" , sum)
print("The average is", ave)
print ("The product is", prd)
Any help would be great!
You already got the sum, and you can calculate the product the same way you get the sum.
Changing your code as little as possible, but note that we need to change the variable name sum to instead something like total because sum overwrites the built-in python keyword sum function.
Also, I remove the duplicate line where you take user input: raw = input("Enter a number or press enter for results: ") which was losing the user input:
#Request input from user
total = 0
prd = 1
raw = 0
try:
numVar = int(input("Specify number of variables to be entered: "))
except ValueError:
pass
while raw != "":
raw = input("Enter a number or press enter for results: ")
try:
total += int(raw)
prd *= int(raw)
except ValueError:
pass
ave = round(total / numVar, 1)
print("The sum is" , total)
print("The average is", ave)
print ("The product is", prd)
Demo:
Specify number of variables to be entered: 4
Enter a number or press enter for results: 3
Enter a number or press enter for results: 4
Enter a number or press enter for results: 5
Enter a number or press enter for results: 6
Enter a number or press enter for results:
The sum is 18
The average is 4.5
The product is 360
I hope this helps.

Count iterations in a loop

New to programming. How to count and print iterations(attempts) I had on guessing the random number?` Let's say, I guessed the number from 3-rd attempt.
import random
from time import sleep
str = ("Guess the number between 1 to 100")
print(str.center(80))
sleep(2)
number = random.randint(0, 100)
user_input = []
while user_input != number:
while True:
try:
user_input = int(input("\nEnter a number: "))
if user_input > 100:
print("You exceeded the input parameter, but anyways,")
elif user_input < 0:
print("You exceeded the input parameter, but anyways,")
break
except ValueError:
print("Not valid")
if number > user_input:
print("The number is greater that that you entered ")
elif number < user_input:
print("The number is smaller than that you entered ")
else:
print("Congratulation. You made it!")
There are two questions being asked. First, how do you count the number of iterations? A simple way to do that is by creating a counter variable that increments (increases by 1) every time the while loop runs. Second, how do you print that number? Python has a number of ways to construct strings. One easy way is to simply add two strings together (i.e. concatenate them).
Here's an example:
counter = 0
while your_condition_here:
counter += 1 # Same as counter = counter + 1
### Your code here ###
print('Number of iterations: ' + str(counter))
The value printed will be the number of times the while loop ran. However, you will have to explicitly convert anything that isn't already a string into a string for the concatenation to work.
You can also use formatted strings to construct your print message, which frees you from having to do the conversion to string explicitly, and may help with readability as well. Here is an example:
print('The while loop ran {} times'.format(counter))
Calling the format function on a string allows you replace each instance of {} within the string with an argument.
Edit: Changed to reassignment operator

Resources