Python 3 - Only numeric input - python

I have trouble finishing a Python assignment. I'm using Python 3.0
So the program asks the user to input a set of 20 numbers, store them into a list, and perform calculation on it to output the largest number, the smallest, the sum, and the average.
Right now, everything is working, except one thing! In the event of a non numeric input from the user, I would like the program to ask for the input again.
I have trouble doing that, I thought of a Boolean variable, I'm not sure.
Thanks a lot for your help.
Here's my code :
import time
#Defining the main function
def main():
numbers = get_values()
get_analysis(numbers)
#Defining the function that will store the values
def get_values():
print('Welcome to the Number Analysis Program!')
print('Please Enter A Series Of 20 Random Numbers')
values =[]
for i in range(20):
value =(int(input("Enter A Random Number " + str(i + 1) + ": ")))
values.append(value)
#Here we store the data into a list called "values"
return values
#Defining the function which will output the numbers.
def get_analysis (numbers):
print(".................................")
print("The Lowest Number Is:", min(numbers))
time.sleep(1)
print("The Highest Number Is:", max(numbers))
time.sleep(1)
print("The Sum The Numbers Is:", sum(numbers))
time.sleep(1)
print("The Average The Numbers Is:", sum(numbers)/len(numbers))
print(".................................")
main()
Vince

A couple of changes:
added a get_int() function which prompts repeatedly until an integer is entered
used this to simplify your get_values() function
added a how_many parameter. Follows the "don't repeat yourself" principle - if you want to change the number of items, you can do it in one place
moved the "welcome to the program" message out of get_values to main where it belongs
Don't Capitalize Every Word Or Chuck Norris Will Get You
I renamed get_analysis() to show_analysis() because it prints the result rather than returning it; accurate function names are important!
I reduced the analysis to a data-driven loop; this is more a matter of taste than anything else, but I think it is cleaner and easier to understand, especially as the number of tests increases, and also contributes to Don't Repeat Yourself
and the final result:
import time
def get_int(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
# couldn't parse as int
pass
def get_values(how_many):
return [get_int("Enter #{}: ".format(i)) for i in range(1, how_many+1)]
def average(lst):
return sum(lst) / len(lst)
def show_analysis(numbers):
tests = [
("The lowest value is", min),
("The highest value is", max),
("The sum is", sum),
("The average is", average)
]
print(".................................")
for label,fn in tests:
print("{} {}".format(label, fn(numbers)))
time.sleep(.5)
print(".................................")
def main():
how_many = 20
print("Welcome to the Number Analysis program!")
print("Please enter {} integers".format(how_many))
numbers = get_values(how_many)
show_analysis(numbers)
main()

I ran it on my Python 3 and got this
$ python3 so.py
Welcome to the Number Analysis Program!
Please Enter A Series Of 20 Random Numbers
Enter A Random Number 1: 3
Enter A Random Number 2: 4
Enter A Random Number 3: 2
Enter A Random Number 4: 6
Enter A Random Number 5: 4
Enter A Random Number 6: 3
Enter A Random Number 7: 5
Enter A Random Number 8: 6
Enter A Random Number 9: 8
Enter A Random Number 10: 9
Enter A Random Number 11: 7
Enter A Random Number 12: 6
Enter A Random Number 13: 5
Enter A Random Number 14: 4
Enter A Random Number 15: 3
Enter A Random Number 16: 2
Enter A Random Number 17: 4
Enter A Random Number 18: 6
Enter A Random Number 19: 7
Enter A Random Number 20: 1
.................................
The Lowest Number Is: 1
The Highest Number Is: 9
The Sum The Numbers Is: 95
The Average The Numbers Is: 4.75
.................................
This works fine. Now make a function like this one
import re
def isInteger(x):
seeker = re.compile("-?[0-9]+")
return bool(seeker.search(x))
You can use a loop with header
while not isInnteger(x):
##get number
to repeat until a number is actually entered.

Related

Mathmatical Average Calculation

Edit the program provided so that it receives a series of numbers from the user and allows the user to press the enter key to indicate that he or she is finished providing inputs. After the user presses the enter key, the program should print:
The Average and The Sum
I've been able to get it to print the sum of the numbers put in but I think it is messing up when trying to calculate the average. I really need some help with this. try inputting 100 59 37 21 and you will see what I mean
data = input("Enter a number: ")
number = float(data)
while data != "":
number = float(data)
theSum += number
data = input("Enter the next number: ")
print("The sum is", theSum)
average = theSum // number
print("The average is", average)```
As Mat and Nagyl have pointed out in the comments you need to keep track of how many numbers were given and divide the sum by that to get the average
data = input("Enter a number: ")
number = float(data)
numbersGiven = 0
theSum = 0
while data != "":
number = float(data)
theSum += number
numbersGiven += 1
data = input("Enter the next number: ")
print("The sum is", theSum)
average = theSum / numbersGiven
print("The average is", average)
Notice that the first input isn't counted (I start with numbersGiven = 0) but the empty input at the end is counted so it gives the correct count.
you can use these code too!
instead of writing the formula for average you can use statistics module
import statistics
the code below asks you the numbers how many times you wrote in the number of datas
number_of_datas=int(input("number of inputs asking: "))
datas=[]
The following code takes the number from the number of times you wrote in the number of inputs
also you can write a Specified number instead of getting an input
for i in range(number_of_datas):
data = float(input("Enter a number: "))
datas.append(data)
fmean is float average
average=statistics.fmean(datas)
print(average)

How would I go about comparing lists with the highest length in Python?

I'm trying to create a program that has 4 features. The 2nd feature (selection =2) is supposed to ask the user for the amount of numbers they want. It then randomly generates the amount the user requested between the range 100-200.
The program then finds the divisors of that number, puts it into a list, counts the number of divisors in that list and then display it. The final line will display the number along with the number of divisors.
I'm not sure what I'm doing wrong but everytime I try something, it somehow breaks the code worse.
I'm stuck on the part where I compare the divisors to see which number has the most divisors/factors. I'm not sure how to pick out the number along with the highest divisor count.
Any input would be appreaciated, thank you!
if selection == 2:
numberinput = int(input("How many numbers do you want to calculate? >> "))
while True:
if numberinput < 0:
print("You have entered a negative number")
print("Please try again with a positive number")
numberinput = int(input("How many numbers do you want to calculate? >> "))
else:
break
for randomizer in range(1,numberinput+1):
import random
divisorRandom = random.randrange(100,201)
divisorList=[]
for i in range(1,divisorRandom+1):
if divisorRandom % i == 0:
divisorList.append(i)
divisorCount = len(divisorList)
print ("Number:", divisorRandom ,"\tDisivors:", divisorCount ,)
I think that you just want the divisor count to be stored somewhere and for that purpose you can use the dictionary,
dictionary1={} #declaring dictionary
for randomizer in range(1,numberinput+1):
import random
divisorRandom = random.randrange(100,201)
divisorList=[]
for i in range(1,divisorRandom+1):
if divisorRandom % i == 0:
divisorList.append(i)
divisorCount = len(divisorList)
dictionary1[divisorRandom]=divisorCount #storing respective number as key and its divisor count as value
print ("Number:", divisorRandom ,"\tDisivors:", divisorCount ,)
print(dictionary1)
Output:
How many numbers do you want to calculate? >> 3
Number: 145 Disivors: 4
Number: 133 Disivors: 4
Number: 152 Disivors: 8
{145: 4, 133: 4, 152: 8}

Can't make this random number generator to work properly

I'm trying to make a random number generator and return the random generated number, but this code returns all the numbers before the random number. How can I return only the last string printed?
import random
from_num = int(input('Generate a random number:\nFrom:'))
to_num = int(input('To:'))
for num in range(random.randrange(from_num,to_num+1)):
if True:
print(f'Random number: {num}')
else:
print('You did not entered valid min/max numbers')
Output for from_num = 0 and to_num = 20 by exemple, instead of '11' can return any number between these two given.
Random number: 0
Random number: 1
Random number: 2
Random number: 3
Random number: 4
Random number: 5
Random number: 6
Random number: 7
Random number: 8
Random number: 9
Random number: 10
Random number: 11
Following to the comments above, just print the random value, without iterating on anything:
import random
from_num = int(input('Generate a random number:\nFrom:'))
to_num = int(input('To:'))
if from_num > to_num:
print('You did not entered valid min/max numbers')
return
random_num = random.randrange(from_num,to_num+1):
print(f'Random number: {random_num}')
Replace this :
for num in range(random.randrange(from_num,to_num+1)):
if True:
print(f'Random number: {num}')
else:
print('You did not entered valid min/max numbers')
with :
ran_num = random.randint(from_num,to_num)
print("Random number is " + str(ran_num))
Why do you have a loop?
import random
from_num = int(input('Generate a random number:\nFrom:'))
to_num = int(input('To:'))
if to_num > from_num:
ran_number = random.randrange(from_num,to_num+1)
print(f'Random number: {ran_number}')
else:
print('You did not entered valid min/max numbers')
If you're trying to make it so the user can pick the range then i don't know but if you want it random on a button click then heres the code first do this
int Rnumber;
then
TextView RandomNumber;
The "RandomNumber" You must make a textview that has the id RandomNumber
Oh! And before i forget you need a button with the id GenRan.
Then put in this code
Button GenRan;
Insert this code
Random Number;
Then this code
Number = new Random();
Rnumber = Number.nextInt(1000);
RandomNumber.setText(Integer.toString(Rnumber));
and you're good to go and btw the "(1000)" is the max number it can generate so its from 1-1000 you can change that if you want

Figuring out Sum, Product, and Average from User Inputs

I'm working on some homework which requires me to do the following:
Write a program that receives a series of numbers from the user and allows the user to press the enter key to indicate that he or she is finished providing input. After the user presses the enter key, the program should print the sum of the numbers, the product of the numbers, and the average of the numbers.
Run your program with the following inputs:
1, 2, 3, 4, 5, 6, 7, 8
2, 24, 11, 1, 4, 10
Enter no number
Here is what I have so far, but my numbers are not coming out correctly. Can someone tell me what I'm doing wrong. I'm a beginner so, if you could speak in the simplest terms possible, that would be great.
Take numbers from user until the user presses "Enter"
calculate the sum, product, and average of the numbers entered
display the results
#main program start
def main():
#initialize variables
count = 0
sum = 0.0
product = 1.0
data = input("Enter a number or press Enter to quit: ")
while True:
#request input from user
data = input("Enter a number or press Enter to quit: ")
#set up the termination condition
if data == "":
break
#convert inputs into floats
number = float(data)
#calculate sum, product, and average
sum += number
product *= number
average = sum / number
#display results
print("The sum is", sum)
print("The product is", product)
print("The average is", average)
#main program end
main()
Not sure what you mean the values are wrong. Nothing seems off except the average.
If you want the average, you need a list to collect the values. Try writing your algorithm by hand, and you'll see what I mean.
data = input("Enter a number or press Enter to quit: ")
numbers = []
while True:
#request input from user
data = input("Enter a number or press Enter to quit: ")
#set up the termination condition
if data == "":
break
#convert inputs into floats
numbers.append(float(data))
# these can all be done outside and after the while loop
count = len(numbers)
if count > 0:
_sum = sum(numbers)
product = 1.0
for n in numbers:
product *= n
average = _sum / float(count)
#display results
print("The sum is", _sum)
print("The product is", product)
print("The average is", average)
else:
print("Nothing was entered")
You don't have all the numbers since you are entering the numbers one at a time. It would be best to have the user enter a list like this:
def main():
average = 0
sum_nums = 0
product = 1
nums = []
while True:
data = input("Enter a number or press Enter to quit: ")
if data == ""
sum_nums = sum(nums)
for num in nums:
num *= product
average = sum_nums/len(nums)
print("The sum is {},".format(sum_nums))
print("The product is {}.".format(product))
print("The average is {}.".format(average))
else:
nums.append(data)
continue
It works by entering all the inputs into a list. The only way to exit an input is by using enter so if the input is nothing then it can only be the Enter key. Once the enter key was hit, I got all the values and printed them.
numbers = []
print("enter key to stop")
while(True):
num = input("enter a number :")
if num:
numbers.append(int(num))
elif(num == ''):
break
sum_num =0
for num in numbers:
sum_num += num
avg = sum_num / len(numbers)
print(sum_num)
print(avg)

Python Help, Max Number of Entries

Created a program for an assignment that requests we make a program that has the user input 20 numbers, and gives the highest, lowest etc. I have the main portion of the program working. I feel like an idiot asking this but I've tried everything setting the max number of entries and everything I've tried still lets the user submit more than 20. any help would be great! I tried max_numbers = 20 and then doing for _ in range(max_numbers) etc, but still no dice.
Code:
numbers = []
while True:
user_input = input("Enter a number: ")
if user_input == "":
break
try:
number = float(user_input)
except:
print('You have inputted a bad number')
else:
numbers.append(number)
for i in numbers:
print(i, end=" ")
total = sum(numbers)
print ("\n")
print("The total amount is {0}".format(str(total)))
print("The lowest number is {0}".format(min(numbers)))
print("The highest number is {0}".format(max(numbers)))
mean = total / len(numbers)
print("The mean number is {0}".format(str(mean)))
Your question could be presented better, but from what you've said it looks like you need to modify the while condition.
while len(numbers) < 20:
user_input = input("Enter a number:" )
....
Now once you've appending 20 items to the numbers list, the script will break out of the while loop and you can print the max, min, mean etc.
Each time the user enters input, add 1 to a variable, as such:
numbers = []
entered = 0
while entered < 20:
user_input = input("Enter a number: ")
if user_input == "":
break
else:
numbers.append(number)
try:
number = float(user_input)
except:
print('You have inputted a bad number')
continue
for i in numbers:
print(i, end=" ")
total = sum(numbers)
print ("\n")
print("The total amount is {0}".format(str(total)))
print("The lowest number is {0}".format(min(numbers)))
print("The highest number is {0}".format(max(numbers)))
mean = total / len(numbers)
print("The mean number is {0}".format(str(mean)))
entered+=1
Every time the while loop completes, 1 is added to the variable entered. Once entered = 20, the while loop breaks, and you can carry on with your program. Another way to do this is to check the length of the list numbers, since each time the loop completes you add a value to the list. You can call the length with the built-in function len(), which returns the length of a list or string:
>>> numbers = [1, 3, 5, 1, 23, 1, 532, 64, 84, 8]
>>> len(numbers)
10
NOTE: My observations were conducted from what I ascertained of your indenting, so there might be some misunderstandings. Next time, please try to indent appropriately.

Categories