I need some help regarding calculating averages and ranges. I am using built-in functions such as sum(), len(), etc. and cannot seem to calculate the average or range. I am using it to write a small piece of code for fun but cannot seem to get it to work. any help is much appreciated. Thank you!
x = 1
number_list = []
while x == 1:
input_number = input("PLease input an integer")
if str.isdigit(input_number) == True:
number_list.append(input_number)
else:
print("Please input a valid integer only.")
continueornot = input("Would you like to continue adding data? PLease input 'Yes' to continue, and anything else to quit.")
if continueornot == 'Yes':
x = 1
else:
print("Here is the maximum number:", max(number_list))
print("Here is the minimum number:", min(number_list))
print("Here is the count:", len(number_list))
print("Here is the average:" + sum(number_list) / len(number_list))
print("Here is the range:", range(number_list))
quit()
Change
if str.isdigit(input_number) == True:
number_list.append(input_number)
to
if input_number.isdigit():
number_list.append(int(input_number))
The error is because you're trying to do those operations on a list of strings.
You can also remove the check against True since that is implicitly checking the truthiness and since input_number is already a str, you can call the isdigit() method directly.
The problem is that you are appending strings to the list rather than integers and then you are applying arithmetic operations on it. So first you should convert the input number to int type.
Secondly range function will not give you the range of a list rather then it returns a sequence.
x = 1
number_list = []
while x == 1:
input_number = input("PLease input an integer")
if str.isdigit(input_number) == True:
input_number=int(input_number)
number_list.append(input_number)
else:
print("Please input a valid integer only.")
continueornot = input("Would you like to continue adding data? PLease input 'Yes' to continue, and anything else to quit.")
if continueornot == 'Yes':
x = 1
else:
print("Here is the maximum number:", max(number_list))
print("Here is the minimum number:", min(number_list))
print("Here is the count:", len(number_list))
print("Here is the average:" , sum(number_list) / len(number_list))
print("Here is the range:", max(number_list)-min(number_list))
Related
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 8 months ago.
I don't understand why the code is causing errors. For example, the error says that you can't add an integer and a string together, but I've already converted the string to an Integer. Could you help me fix it? The code is attached. Thanks.
# In this program I will collect data
# values from the user and use python built-in functions
# to display various info about the data set
# Giving user directions
print("In this programme, you can enter")
print("some numbers and it will display the")
print("minimum, maximum, range and average")
print("of the data set you entered.")
# Setup
list = []
loop = True
# Creating function for process of entering number
def enterNumber():
print()
x = input("Enter an integer: ")
y = str.isdigit(x)
if y == True:
list.append(x)
print()
print("Successfully added to list")
print()
print("Here is your list so far")
print(list)
elif y == False:
print()
print("Sorry, this is not an integer")
else:
print("Error. Kill and start again")
while loop == True:
enterNumber()
print()
print("Would you like to add another value?")
print()
a = input("Enter 1 for Yes, enter 0 for No: ")
if a == "0":
loop = False
print()
print()
print("------------------------------------------------")
print()
print("Count:", len(list))
print()
print("Minimum:", min(list))
print()
print("Maximum:", max(list))
print()
print("Range:", int(max(list)) - int(min(list)))
print()
print("Average:", int(sum(list)) / int(len(list)))
It seems like this last line is the problem.
You need to use int() function after checking if y value is True. If not you will be appending an string value always to your list:
def enterNumber():
print()
x = input("Enter an integer: ")
y = str.isdigit(x)
if y == True:
list.append(int(x)) #int(x) converts x to integer
...
The reason for the issue is that you have string values in your list, which doesn't work.
Simple test:
l = ['1', '2']
sum(l)
results in the same error.
Easiest fix is mentioned by Cardstdani.
You have not asked for it. But there is a serious issue in your code:
You should avoid at all cost to name your list list as this overwrites the built-in list() function.
# In this program I will collect data
# values from the user and use python built-in functions
# to display various info about the data set
# Giving user directions
print("In this programme, you can enter")
print("some numbers and it will display the")
print("minimum, maximum, range and average")
print("of the data set you entered.")
# Setup
list1 = []
loop = True
# Creating function for process of entering number
def enterNumber():
print()
x = input("Enter an integer: ")
y = str.isdigit(x)
if y == True:
list1.append(x)
print()
print("Successfully added to list")
print()
print("Here is your list so far")
print(list)
elif y == False:
print()
print("Sorry, this is not an integer")
else:
print("Error. Kill and start again")
while loop == True:
enterNumber()
print()
print("Would you like to add another value?")
print()
a = input("Enter 1 for Yes, enter 0 for No: ")
if a == "0":
loop = False
print()
print()
print("------------------------------------------------")
print()
print("Count:", len(list1))
print()
print("Minimum:", min(list1))
print()
print("Maximum:", max(list1))
print()
print("Range:", int(max(list1)) - int(min(list1)))
print()
list1 = list(map(int, list1))
print("Average:", sum(list1) / len(list1))
Currently using 3.8.1.
I was wondering how I could make a while True: loop like in the example below, but using a number that the user inputted instead of a word (for example any number equal to or lower then 100 would print something different. I've looked on this website, but I couldn't understand the answers for questions similar to mine.
while True:
question = input("Would you like to save?")
if question.lower() in ('yes'):
print("Saved!")
print("Select another option to continue.")
break
if question.lower() in ('no'):
print ("Select another option to continue.")
break
else:
print("Invalid answer. Please try yes or no.")
How about including less than / great than clauses in your if statements?
while True:
# get user input:
user_input = input("Would you like to save? ")
# convert to int:
number = int(user_input)
if number <= 100:
print("Saved!")
print("Select another option to continue.")
break
elif number > 100:
print ("Select another option to continue.")
break
else:
print("Invalid answer. Please try yes or no.")
you need to extract the number from the input and then run your conditional evaluation of the inputed value.
while True:
input_val = input("Enter a #?")
try:
num=int(input_val)
except ValueError:
print("You have entered an invalid number. please try again")
continue
if num == 1:
print("bla bla")
elif num ==2:
print("bla bla 2")
else:
...
input takes the user's input and outputs a string. To do something with numbers, check if the string is numeric, cast it to an int and do whatever you want
while True:
answer = input("How many dogs do you have?")
if answer.isnumeric():
num_dogs = int(answer)
else:
print("Please input a valid number")
I think you maybe want a list instead of a tuple.
Could this work:
while True:
number = input("Enter a number?")
if int(number) in list(n for n in range(100)):
print("lower!")
elif int(number) in [100]:
print ("exact")
else:
print("higher")
I am trying to write a game that generates a random integer and the user has to guess it.
The problem is that if the user input is not a digit it crashes. So I tried to use isdigit, and it works at the beginning, but if the user decides to input not a number after the first input was a digit, it still crashes. I don't know how to make it check isdigit for every input.
import random
x =(random.randint(0,100))
print("The program draws a number from 0 to 100. Try to guess it!")
a = input("enter a number:")
while a.isdigit() == False :
print("It is not a digit")
a = input("enter a number:")
if a.isdigit() == True :
a = int(a)
while a != x :
if a <= x :
print("too less")
a = input("enter a number:")
elif a >= x :
print("too much")
a = input("enter a number")
if a == x :
print("good")
I would suggest doing the following:
completed = False
while not completed:
a = input("enter a number: ")
if a.isdigit():
a = int(a)
if a < x:
print("too little")
elif a > x:
print("too much")
else:
print("good")
completed = True
else:
print("It is not a digit")
If your code crashed because the user entered not a number, then either make sure the user enters a number, or handle an error while trying to compare it with a number.
You could go over all chars in the input and ensure that they are all digits.
Or you could use a try/except mechanism. That is, try to convert to the numerical type you wish the user to enter and handle any error throwen. Check this post:
How can I check if a string represents an int, without using try/except?
And also:
https://docs.python.org/3/tutorial/errors.html
The typical pythonic way to tackle that would be to "ask for forgiveness instead of looking before you leap". In concrete terms, try to parse the input as int, and catch any errors:
try:
a = int(input('Enter a number: '))
except ValueError:
print('Not a number')
Beyond that, the problem is obviously that you're doing the careful checking once at the start of the program, but not later on when asking for input again. Try to reduce the places where you ask for input and check it to one place, and write a loop to repeat it as often as necessary:
while True:
try:
a = int(input('Enter a number: '))
except ValueError: # goes here if int() raises an error
print('Not a number')
continue # try again by restarting the loop
if a == x:
break # end the loop
elif a < x:
print('Too low')
else:
print('Too high')
print('Congratulations')
# user vs randint
import random
computer = random.randint(0,100)
while True:
try:
user = int(input(" Enter a number : "))
except (ValueError,NameError):
print(" Please enter a valid number ")
else:
if user == computer:
print(" Wow .. You win the game ")
break
elif user > computer:
print(" Too High ")
else:
print(" Too low ")
I think this can solve the issues.
In your code you want to check whether the user has input no or string since your not using int() in your input it will take input as string and furthur in your code it wont be able to check for <= condition
for checking input no is string or no
code:-
a = input ("Enter no")
try:
val = int(a)
print("Yes input string is an Integer.")
print("Input number value is: ", a)
except ValueError:
print("It is not integer!")
print(" It's a string")
You probably will have to learn how to do functions and write your own input function.
def my_input(prompt):
val = input(prompt)
if val.isdigit():
return val
else:
print('not a number')
# return my_input(prompt)
I'm very new to python and trying to write some code so that the user enters something. If it's an integer it's sorted into the Numbers list, if it's a string it goes into the String list.
I want to be able to find the mean of all the numbers that are in the list and print out the result.
And in the String section I want to be able to print out everything within the string and its length.
User types 'save' to exit and if input is valid that's caught.
Numbers = []
String = []
while(True):
user_input = input("What's your input? ")
if user_input == "save":
break
elif user_input.isdigit():
Numbers.append(user_input)
for i in range(len(Numbers)):
Numbers[i] = int(Numbers[i])
print(sum(Numbers)/len(Numbers)
elif isinstance(user_input, str):
String.append(user_input)
print(String)
print (len(String)-1)
else:
print("Invalid input.")
break
#use isalpha to check enterted input is string or not
#isalpha returns a boolean value
Numbers = []
String = []
while(True):
user_input = input("input : ")
if user_input == "save":
break
elif user_input.isdigit():
Numbers.append(int(user_input))
print(sum(Numbers)/len(Numbers))
elif user_input.isalpha():
String.append(user_input)
print(String)
print (len(String))
else:
print("Invalid input.")
break
There is good thing called statistics.mean:
from statistics import mean
mean(your_list)
You are using Length, which has not been defined. I think what you wanted was
print(sum(Numbers)/len(Numbers))
and you probably don't want it inside the loop, but just after it (although that might be another typo).
I found other more convenient way to produce the mean: Use statistics model and output the mean.
#import useful packages
import statistics
#Create an empty list
user_list = []
#get user request
user_input = input("Welcome to the average game. The computer is clever enough to get the average of the list of numbers you give. Please press enter to have a try.")
#game start
while True:
#user will input their number into a the empty list
user_number = input("Type the number you want to input or type 'a' to get the average and quit the game:")
#help the user to get an average number
if user_number == 'a':
num_average = statistics.mean(user_list)
print("The mean is: {}.".format(num_average))
break #Game break
else:
user_list.append(int(user_number))
print(user_list)
This is the problem I have to solve : Write a program to sum a series of numbers entered by the user. The program should first prompt the user for how many numbers are to be summed. It should then input each of the numbers and print a total sum. This is what I have so far:
def excercise13():
print("Programming Excercise 13")
print("This program adds a series of numbers.")
while True:
try:
numberTimes = float(input("Enter how many numbers will be added: "))
except ValueError:
print("Invalid input.")
else:
break
numberTimes = int(numberTimes)
while True:
try:
for i in range(1,(numberTimes+1)):
("""I don't know what to put here""")
except ValueError:
print("Invalid input.")
else:
break
totalSum =
print("The sum of",nums,"is:",totalSum)
print()
excercise13()
I will go through the solution, based on your code, code block by code block.
def excercise13():
currentnumber = 0
Here we create the function excercise13() and set currentnumber to 0
print("Programming Excercise 13")
print("This program adds a series of numbers.")
while True:
try:
numberTimes = int(input("Enter how many numbers will be added: "))
except ValueError:
print("Invalid input.")
else:
break
You should use int instead of float. Can you imagine doing a process 3.5 times? This also reduces your previous repetition.
for x in range(numbertimes): #More pythonic way.
new_number = input ("Please enter a number to be added.")
currentnumber += new_number
The above code block makes the program ask for a new number numbertimes times. It then adds this number to currentnumber
totalSum = currentnumber
print("The sum of",nums,"is:",totalSum)
print()
This sets the totalSum to the final currentnumber
excercise13()
This starts your code.
Python has this functionality built in as the sum function.
def makesum():
try:
numbers = input('Enter the numbers to sum, comma seperated: ')
print 'The sum is {0}'.format(sum(numbers))
except:
print 'Input invalid. Try again.'
makesum()
makesum()