Finding the product of user input lines - python-3.x

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.

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

Coverting an input string into an interger

#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')

Reject letters and only allow number inputs # enter first and second number in Python 3.x

Trying to only allow number inputs in python 3.x no letters and ask user to input a number if they enter a letter. I have two numbers that need to be entered and need it to reject singlarily as they are entered.
print ('Hello There, what is your name?') # String asks the user for their name
myname = input() #string
print ('Nice to meet you, '+ myname)# String responds "Nice to meet you" and input the users name that was entered
print() #adds a space
print ('We want to some math today!') # String tells user we want to do some math today
print() # adds a space
num1,num2 = float(input("Enter first number")), float(input("Enter second number"))
sum = num1+num2
if sum >100 : # Determines if users inputs when added together are > 100
print('They add up to a "Big Number" ') # If inputs are > 100 prints "They add up to a big number"
# and the users name
elif sum <=100 : # Determines if the users inputs when added are = to or <100
print ('They add up to' ,(sum))
You need a while loop to continuously accept a valid input which in your case is a numerical one.
Another thing is that you need to check if the entered input is numerical or not, in that case you can use Python's inbuilt isdigit() function to do it.
Lastly, type cast your input to float or int while you add the both to avoid str related errors.
print ('Hello there, what is your name?') # String asks the user for their name
myname = input() #string
print ('Nice to meet you, '+ myname) # String responds "Nice to meet you" and input the users name that was entered
print() #adds a space
print ('We want to some math today!') # String tells user we want to do some math today
print() # adds a space
i = False
while i == False:
num1 = input("Enter first number: ")
if num1.isdigit():
i = True
else:
i = False
print() # adds a space
j = False
while j == False:
num2 = input("Enter Second number: ")
if num2.isdigit():
j = True
else:
j = False
sum = float(num1) + float(num2)
if sum > 100 : # Determines if users inputs when added together are > 100
print('They add up to a "Big Number" ') # If inputs are > 100 prints "They add up to a big number"
# and the users name
elif sum <= 100 : # Determines if the users inputs when added are = to or <100
print ('They add up to' ,(sum))
Let me know, if that worked for you!
When you are validating multiple inputs, I usually make a separate function to do so. While it may not be necessary here, it is a good habit to factor out repeated code. It will exit if either of the inputs are not floats. Here's how I would do it, using a try block with a ValueError exception. By the way, newlines can be achieved by putting '\n' at the end of the desired strings. Using print() is a sloppy way of doing it.
import sys
def checkNum(number):
try:
number = float(number)
except ValueError:
print("That is not a float.")
sys.exit()
return number
Then, you can use the original code like so:
print ('Hello There, what is your name?') #String asks the user for their name
myname = input() #string
print ('Nice to meet you, '+ myname + '\n')#String responds "Nice to meet you" and input the users name that was entered
print ('We want to some math today!\n') #String tells user we want to do some math today
num1 = checkNum(input("Enter first number"))
num2 = checkNum(input("Enter second number"))
sum = num1+num2
if sum >100 : # Determines if users inputs when added together are > 100
print('They add up to a "Big Number" ') #If inputs are > 100 prints "They add up to a big number" and the users name
elif sum <=100 : #Determines if the users inputs when added are = to or <100
print ('They add up to' ,(sum))

How to print an array without brackets, commas, and apostrophes

https://i.imgur.com/i4KBnkA.png is an image of the code working and the output.
I have a homework assignment to create a high score list from inputted names and scores. It is supposed to display them in order, and I have it working, I just cannot for the life of me figure out how to remove the unnecessary formatting from my code. I've tried doing join stuff, can't really figure out the converting to String options... I will probably get full credit for this solution, but I really want to know how to make it more easily readable.
Scores = []
count = 0
question = True
while question == True:
name = str(input("Whose score are you inputting?"))
if name != "Done":
score = int(input("What did " + name + " score?"))
entry = score, name
Scores.append(entry)
count = count + 1
elif name == "Done" and count < 5:
print("You haven't input 5 scores yet!")
else:
question = False
Scores.sort(reverse=True)
print(*Scores, sep='\n')
input("")

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.

Resources