How do i create a number of inputs from an input - python

I'm brand new to this, 10 days in.
I've been thinking how I could solve this for 30 min. Please help.
Find Average
You need to calculate the average of a collection of values. Every value will be valid number. The average must be printed with two digits after the decimal point.
Input-
On the first line, you will receive N - the number of the values you must read
On the next N lines you will receive numbers.
Output-
On the only line of output, print the average with two digits after the decimal point.
Input
4
1
1
1
1
Output
1.00
Input
3
2.5
1.25
3
Output
2.25
From what I see, I figure I need to create as much inputs as the N of the first one is and then input the numbers Id like to average and then create a formula to average them. I may be completely wrong in my logic, in any case Id be happy for some advice.
So far I tried creating a while loop to create inputs from the first input. But have no clue about the proper syntax and continue with making the new inputs into variables I can use
a=int(input())
x=1
while x<a or x==a:
float(input())
x=x+1

a=int(input('Total number of input: '))
total = 0.0
for i in range(a):
total += float(input(f'Input #{i+1}: '))
print('average: ', round(total/a,2))
Modified a bit on your version to make it work

There were few things that you were doing wrong. when the numbers are decimals use float not int.
If you are looking for a single line input this should be how it's done.
When writing the code please use proper variables and add a string that's asking for the input.
total = 0
first_num=int(input("Number of inputs: "))
number = input("Enter numbers: ")
input_nums = number.split()
for i in range(first_num):
total = total + int(input_nums[i])
average = total/first_num
print(average)
If you are looking for a multiline output This should be how it's done.
first_num=int(input("Number of inputs: "))
x=1
total = 0
while x<first_num or x==first_num:
number = float(input("Enter numbers: "))
total = total + number
x=x+1
avg = total/first_num
print(avg)

Related

Python - script counts wrong, but why?

I'm just at the beginning to learn Python.
As an exercise I wrote this little script:
Write a program which repeatedly reads numbers until the user enters "done". Once "done" is entered, print out the total, count, and average of the numbers. If the user enters anything other than a number,
detect their mistake using try and except and print an error message and skip to the next number.
It does what it should in general, but: When I played with it a little I noticed one strange behavior: As it takes several (int) numbers after the prompt it won't - and shouldn't - take characters. So far so good, but then I tried a float as input. The script won't take it as valid input but would count it and put the truncated number into the total.
Code:
total = float(0) # sum of items
count = int(0) # number of items
avrg = float(0) # average of items
input_in = True
while input_in:
try:
line = input('Enter a number: ')
if line == 'done':
print('total:', str(total),' count:', str(count),' average:', str(avrg))
break
print(line)
for itervar in line:
total = total + float(itervar)
count = count+1
avrg = total / count
except:
print('Invalid input')
Output:
Enter a number: 1.5
1.5
Invalid input
Enter a number: 5
5
Enter a number: 5
5
Enter a number: 5
5
Enter a number: done
total: 16.0 count: 4 average: 4.0
What I tried - and didn't work: Assign the variables line and/or itervar as float().
I tried the included Debugger but I'm not able to understand it.
I have no clue how this could work.
Your line:
for itervar in line:
Is walking over each character of the input, which for your first input (1.5) results in three iterations:
1
.
5
So for the first iteration, your total is increased by 1, and for the second iteration, you're trying to use . as a number, and failing. (Hence why your final value, after adding 5 + 5 + 5, is 16)
Instead of using a for loop to iterate over your input, you should look into converting the entire input string into a number.
And as an added bonus...
Consider whether you actually need to be recalculating your average each loop. Since you have the total, and the count, I'd recommend instead calculating your average value on-demand, as a result of those two numbers.
As you've already figured out, input() returns a string.
When you iterate through a string with a for loop, you iterate over each character individually. This means that, when you enter '1.5', you get three iterations:
itervar = '1'
itervar = '.'
itervar = '5'
Due to how you wrote your code, the first one goes correctly, but then when it tries to convert '.' to a float, it produces an error.
Why not just consider the entire input as a whole, instead of character-by-character?
line = input('Enter a number: ')
if line == 'done':
print('total:', str(total),' count:', str(count),' average:', str(avrg))
break
print(line)
total = total + float(line)
count = count+1
avrg = total / count

Doubling amount per day, need to convert number of pennies to dollars + cents

This program starts with 1 cent and doubles each day. However, I'm stuck on trying to find a way to convert the number of pennies into a dollar and cent amount. For example, converting 1020 pennies to $10.20.
I'm also attempting to make it so if user input is not a positive number, the user will be continously prompted until they enter a positive number. This isn't working, however.
I also feel I've messed up by using range, as I want to enter a set number of days, say 16 days, and when I enter 16, I receive the days 1-17, as range should be doing, and I'm not sure how to go about fixing that.
b = int(input("Input number of days "))
if b > 0:
print(b)
else:
b = int(input("Days must be positive "))
print("Day 1:","1")
days = 1
aIncrement = 2
penny = 1
for i in range(b):
pAmount = int(penny*2)
addAmount = int(2**aIncrement -1)
aIncrement +=1
days +=1
penny *= 2
print("Day " + str(days) + ":",pAmount)
Your question has multiple parts, which is not ideal for stackoverflow, but I will try to hit them all.
Fixing the numeric values to show dollars and cents.
As noted in comments to other answers, division can often run into snags due to floating point notation. But in this case, since all we really care about is the number of times 100 will go into the penny count and the remainder, we can probably safely get away with using divmod() which is included with Python and calculates the number of times a number is divisible in another number and the remainder in whole numbers.
For clarity, divmod() returns a tuple and in the sample below, I unpack the two values stored in the tuple and assign each individual value to one of two variables: dollars and cents.
dollars, cents = divmod(pAmount, 100) # unpack values (ints)
# from divmod() function
output = '$' + str(dollars) + '.' + str(cents) # create a string from
# each int
Fixing the range issue
The range() function produces a number and you can set it to start and end where you want, keeping in mind that the ending number must be set at one value higher than you want to go to... i.e. to get the numbers from one to ten, you must use a range of 1 to 11. In your code, you use i as a placeholder and you separately use days to keep track of the value of the current day. Since your user will tell you that they want b days, you would need to increment that value immediately. I suggest combining these to simplify things and potentially using slightly more self-documenting variable names. An additional note since this starts off on day one, we can remove some of the setup code that we were using to manually process day one before the loop started (more on that in a later section).
days = int(input("Input number of days "))
for day in range(1, days + 1):
# anywhere in your code, you can now refer to day
# and it will be able to tell you the current day
Continuous input
If we ask the user for an initial input, they can put in:
a negative number
a zero
a positive number
So our while loop should check for any condition that is not positive (i.e. days <= 0). If the first request is a positive number, then the while loop is effectively skipped entirely and the script continues, otherwise it keeps asking for additional inputs. Notice... I edited the string in the second input() function to show the user both the problem and to tell them what to do next.
days = int(input("Input number of days "))
while days <= 0:
days = int(input("Days must be positive, input positive number of days: "))
Putting all this together, the code might look something like this:
I put the items above together AND cleaned up a few additional things.
days = int(input("Input number of days "))
while days <= 0:
days = int(input("Days must be positive, input number of days: "))
# aIncrement = 2 # this line not needed
penny = 1
for day in range(1, days + 1):
pAmount = int(penny) # this line was cleaned up
# because we don't need to manually
# handle day one
dollars, cents = divmod(pAmount, 100)
output = '$' + str(dollars) + '.' + str(cents)
# addAmount = int(2**aIncrement -1) # this line not needed
# aIncrement +=1 # this line not needed
penny *= 2
print("Day " + str(day) + ":", output)
For the continuous prompting, you can use a while loop.
while True:
user_input = int(input("Enter the number"))
if user_input > 0:
break
else:
continue
Or alternatively:
user_input = int(input("Enter the number"))
while user_input <= 0:
user_input = int(input("Enter the number"))
For the range issue, you can add -1 to the parameter you're passing range.
for i in range(b - 1):

How can I make this calculate the running total in Python?

I'm trying to create a program that lets me calculate x(i)=1/i^2 for i=1,2,⋯,N
Here is my code so far:
end = int(input("How many times do you want to calculate it?: "))
x = 0.0
for i in range (0, end):
x = x + (1 / end **2)
print ("The sum is", x)
I seem to have a problem with it adding the different values of X together.
How would I do it if i need it to work?
You aren't using your increment i.
You are also dividing by zero.
Try:
end = int(input("How many times do you want to calculate it?: "))
x = 0.0
for i in range (1, end+1):
x = x + (1 / (i**2))
print ("The sum is", x)
That should provide the result you are looking for. Enjoy!
Even in this little bit of code, there are a number of things to do better.
end = int(input("How many times do you want to calculate it?: "))
print(sum([1/i*2 for i in range(1, end+1)]))
Use built-in functions like sum. They're a major strength of python.
Be careful with range. Ranges start at 0 by default, and you don't want to divide by 0, of course. Also, I take it that you want end to be the last value of i. In that case, you have to add 1 to end to get it included in the range.
Hope this helps.
Accounting for divide by zero problems and using sum feature and list comprehension (more compact):
end = int(input("How many times do you want to calculate it?: "))
x = 0
x = sum([x + (1.0/(i**2)) for i in range(1, end+1)])
print ("The sum is", x)
Emphasis on 1.0 so you're not dividing by 0

Python: How to use a Variable Integer to Call a Specific Part of a String

Ok, so I've got a couple issues with a program (for school again) that I'm using to add up all the digits of a number. I've got some of the program down, except 2 things. First, how to use a variable (thelength below) in replacement of a number to call a specific digit of the input (I'm not sure if this is even possible, but it would be helpful). And second, how to add up different numbers in a string. Any ideas?
Here's what I have so far:
number = str(int(input("Please type a number to add up: ")))
length = len(number)
thelength = 0
total = 0
thenumbers = []
while thelength < length:
#The issue is me trying to use thelength in the next two lines, and the fact that number is now a string
total += number[thelength]
thenumbers.append(number[thelength])
thelength += 1
for num in thenumbers:
print(num[0])
print("+")
print("___")
print(total)
Thanks for any help I can get!
I don't know what "call a specific digit of the input" means, but the error in your code is here:
total += number[thelength]
total is an int, and you're trying to add a string to it, convert the digit to an integer first.
total += int(number[thelength])
Result:
1
2
3
+
___
6
import re
import sys
INPUT_VALIDATOR = re.compile("^[0-9]+$")
input_str = input("Please type a natural number to add up: ")
if INPUT_VALIDATOR.match(input_str) is None:
print ("Your input was not a natural number (a positive whole number greater or equal to zero)!")
print ("This displeases me, goodbye puny human.")
sys.exit(1)
total = 0
for digit_str in input_str:
print(digit_str)
total += int(digit_str)
print("+")
print("___")
print(total)
If you don't need to print the digits as you go, it's even easier:
# (Add the same code as above to get and validate the input string)
print(sum(int(digit_str) for digit_str in input_str))
number = int(input("Please type a number to add up: "))
total = 0
while number > 0:
total += number % 10
total /= 10
print(total)
num % 10 pretty much gets the last digit of a number
then we divide it by 10 to truncate the number by its last digit
we can loop through the number as long as it's above 0 and take the digital sum by using the method outlined above
Every thing that you need is convert the digits to int and sum them :
>>> s='1247'
>>> sum(map(int,s))
14
But as you get the number from input it could cause a ValueErorr , for refuse that you can use a try-except :
try :
print sum(map(int,s))
except ValueErorr :
print 'please write a valin number :'
Also if you are using python 2 use raw_input for get the number or if you are using python 3 just use input because the result of both is string !

Comparing digits in a list to an integer, then returning the digits

I am using python version 3.
For homework, I am trying to allow five digits of input from the user, then find the average of those digits. I have figured that part out (spent an hour learning about the map function, very cool).
The second part of the problem is to compare each individual element of the list to the average, then return the ones greater than the average.
I think the "if any" at the bottom will compare the numbers in the list to the Average, but I have no idea how to pull that value out to print it. You guys rock for all the help.
#Creating a list
my_numbers = [input("Enter a number: ") for i in range(5)]
#Finding sum
Total = sum(map(int, my_numbers))
#Finding the average
Average = Total/5
print ("The average is: ")
print (Average)
print ("The numbers greater than the average are: ")
if any in my_numbers > Average:
#Creating a list
my_numbers = []
r = range(5)
for i in r:
try:
my_numbers.append(int(input("Enter a number: ")))
except:
print( 'You must enter an integer' )
r.append(i)
#Finding sum
Total = sum(my_numbers)
#Finding the average
Average = Total/5
print ("The average is: ")
print (Average)
print ("The numbers greater than the average are: ")
print ([x for x in my_numbers if x>Average])
I'm sure that you would finally have succeeded in your code even if nobody hadn't answered.
My code is in fact to point out that you should foresee that entries could be non-integer and then to put instruction managing errors of entry.
The basic manner here is to use try except
Note the way I add i to r each time an error occurs in order to make up for the element of r that has been consumed.
Unfortunately, "if any" doesn't work. Take a look at the docs for the any function to se what it does. It doesn't do what you want even if your syntax had been correct. What you want is only the numbers greater than the average. You could use a list comprehension: [number for number in my_numbers if number > Average]. Or you could use a loop.
What you need to do is iterate through the list and print out the numbers above the average:
for i in my_numbers:
if int(i) > Average:
print(i)
To make things easier, you might also want to have the my_numbers list actually start out as a list of integers:
my_numbers = [int(input("Enter a number: ")) for i in range(5)]
Now we can get rid of the map function (don't worry, the hour did not go to waste, you'll find it very useful in other situations as well). You could also go straight to calculating the average without calculating the total, since you won't need the total again.
Average = sum(my_numbers) / 5
This means you can change the for loop so that you can replace int(i) with i.
You could also create a list with a list comprehension, and then print out the values in that list.
aboveAverage = [i for i in my_numbers if i > Average]
for i in aboveAverage:
print i

Categories

Resources