Hello everyone i am a new to programming and i have a small problem in the code, i need to get the average of the sum i already made the sum of digits and here is the code:
num = int(input("Enter a number\n"))
r = 0
m = 0
while num != 0:
m = num % 10
r = r + m
num = int(num / 10)
print(f"The sum of all digits is {result} and the average is")
i need the average but i dont know how to get it( for example in the num i added 5555, 5+5+5+5 = 20) how would i get the average and thanks
i tried to do r / m but also didnt work
This is the short solution:
num = input("Enter a number\n")
s = sum([int(x) for x in num])
a = s / len(num)
print(f"The sum of all digits is {s} and the average is {a}")
Also, this is the fixed version of your code:
num = int(input("Enter a number\n"))
r = 0
m = 0
t = 0
while num != 0:
m = num % 10
r = r + m
num = int(num / 10)
t = t + 1
print(f"The sum of all digits is {r} and the average is {r/t}")
n_str = input("Enter numbers by gaps: ")
n = [float(num) for num in n_str.split()]
summ = 0
for i in n:
summ = summ + i
print("Average of ", n, " is ", summ / len(n))
Related
So I could print out the odd numbers. However, the output isn't what i want. It should look like 1+3+5+7 = 16 but I could not make it into a single line.
I couldn't figure out how to extract the values from the while loop as with my method it only gives the latest odd number which is 7 while 1,3 and 5 could not be taken out
num = int(input("Insert a postive integer:")) #4
oddNum = 1
total = 0
count = 1
while count <= num:
odd = (str(oddNum))
print (odd)
total = total + oddNum
oddNum = oddNum + 2
count += 1
print (odd + "=" + str(total))
#output will be:
'''
1
3
5
7
7=16
but it should look like 1+3+5+7=16
'''
An alternative method would be the use of:
range() method to generate the list of odd numbers
.join() method to stitch the odd numbers together (eg. 1+3+5+7)
f-strings to print odds together with the total = sum(odd_nums)
Code:
num = int(input("Insert a postive integer:")) #4
odd_nums = range(1, num * 2, 2)
sum_nums = "+".join(map(str, odd_nums))
print(f"{sum_nums}={sum(odd_nums)}")
Output:
1+3+5+7=16
Note:
Same but using two lines of code:
num = int(input("Insert a postive integer:")) #4
print(f"{'+'.join(map(str, range(1, num * 2, 2)))}={sum(range(1, num * 2, 2))}")
Output:
1+3+5+7=16
You are not storing old oddNum values in odd. With minimal changes can be fixed like this:
num = int(input("Insert a positive integer:"))
oddNum = 1
total = 0
count = 1
odd = ""
while count <= num:
total = total + oddNum
odd += f"{oddNum}"
oddNum = oddNum + 2
count += 1
odd = "+".join(odd)
print(odd + "=" + str(total))
There are a few options, you can either create a string during the loop and print that at the end, or create a list and transform that into a string at the end, or python3 has the ability to modify the default end of line with print(oddNum, end='').
Using a string:
num = int(input("Insert a postive integer:")) #4
oddNum = 1
total = 0
count = 1
sequence = ''
while count <= num:
sequence += ("+" if sequence != "" else "") + str(oddNum)
total = total + oddNum
oddNum = oddNum + 2
count += 1
print (sequence + "=" + str(total))
Using print:
num = int(input("Insert a postive integer:")) #4
oddNum = 1
total = 0
count = 1
while count <= num:
if count != 1:
print('+', end='')
print (oddNum, end='')
total = total + oddNum
oddNum = oddNum + 2
count += 1
print ("=" + str(total))
Alternatively using walrus (:=), range,print, sep, and end:
print(*(odd:=[*range(1,int(input('Insert a postive integer:'))*2,2)]),sep='+',end='=');print(sum(odd))
# Insert a postive integer:4
# 1+3+5+7=16
I'm trying to add up all the number from 1 to N and print the result and then keep asking the user to enter number till the number zero is entered. I can make it sum the numbers and end the while but can't make it keep asking for more numbers like this: https://pastebin.com/9pWDT6su
num = int(input('N: '))
sum = 0
while num != 0:
while num < 0:
num = int(input('ERROR - N: '))
sum = sum + num
num = num - 1
print('Sum: ', sum)
# If I put this outside the WHILE it'll work but it won't allow me to
# keep adding numbers
num = int(input('N: '))
print('END')
Try this :
num = int(input('N: '))
while num != 0:
sum=0
while num > 0:
sum = sum + num
num = num - 1
print('Sum: ', sum)
num = int(input('N: '))
print('END')
If you want the sum of 1-n for all numbers remove sum=0 inside while
Try this:
num = int(input('N: '))
sum_ = 0
while True:
if num < 0:
num = int(input('ERROR - N: '))
elif num == 0:
break
else:
sum_ = sum_ + num
print('Sum: ', sum_)
num = int(input('N: '))
This is the question:
Write a Python program that reads a positive integer n and finds the
average of all odd numbers between 1 and n. Your program should not
accept a negative value for n.
And here is my code, which curiously doesn't work:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
while b <= k:
if b % 2 == 1:
sum1 = sum1+b
b += 1
avg = sum/k
print(avg)
Example: input: 8 and output: 2.5, while it should be 4. Any tips?
if we use while True, the program will run until it receives a positive number. and when we get a positive number, then we execute the instructions and turn off the loop using a break
1 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = [i for i in range(1, n + 1) if i % 2 == 1]
print(sum(numbers) / len(numbers))
break
2 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = []
for i in range(1, n+1):
if i % 2 == 1:
numbers.append(i)
break
print(sum(numbers)/len(numbers))
3 version with counter
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
summ = 0
c = 0
for i in range(1, n+1):
if i % 2 == 1:
summ += i
c += 1
print(summ/c)
break
You have used sum (builtin function name) instead of sum1 (your variable name) in the 2nd last line. Additionally, you need to count the total number of odd numbers and divide using that number instead of the input.
Okay I reviewed the question and here is the answer:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
c = 0
while b <= k:
if b % 2 == 1: #determines if odd
sum1 = sum1+b
c += 1 #variable which counts the odd elements
b += 1 #counter
avg = sum1/c
print(avg)
sum = int(input("Enter a positive integer: "))
Oddtotal = 0
for number in range(1, sum+1):
if(number % 2 != 0):
print("{0}".format(number))
Oddtotal = Oddtotal + number
n = int(input("Enter the binary number : "))
n_into_str = str(n)
lenf = len(n_into_str)
def calculate(n):
ans = 0
for i in range(lenf):
z = n%10
power = 2**i
k = z*power
value = z
ans = ans + z
print(ans)
calculate(n)
You are almost good, but you need ans = ans + k and ans = ans + z, and also divide n by 10, to remove the last digit
Version that uses math operation to select digit
def calculate(n: int):
ans = 0
for i in range(len(str(n))):
z = n % 10
n = n // 10
power = 2 ** i
k = z * power
ans = ans + k
print(ans)
n = int(input("Enter the binary number : "))
calculate(n)
Version that uses string indexing to select digit
def calculate(n: str):
ans = 0
for i, digit in enumerate(reversed(n)):
power = 2 ** i
k = int(digit) * power
ans = ans + k
print(ans)
n = input("Enter the binary number : ")
calculate(n)
I set an algorithm which sum a number's digits but I couldn't make it till single digit. It only work for one step.
For example:
a=2, b=8
a^b=256 = 6+5+2 = 13
But I want to reach single digit, like:
a^b=256 = 6+5+2 = 13 = 3+1 = 4
Below you can see my codes.
a = int(input("Enter a value"))
b = int("Enter second value")
number = pow(a, b)
sum= 0
while float(number) / 10 >= .1:
m = number % 10
sum += m
number = number // 10
if float(number) / 10 > .1:
print(m, end=" + ")
else:
print(m, "=", sum)
Here you go:
n = 256
while n > 9:
n = sum(int(i) for i in str(n))
print(n)
So whats going on? str(n) converts n to a string, strings in python can be iterated over so we can access digit by digit. We do this in a generator, converting each digit back to a integer, int(i) for i in str(n), we use sum to sum the elements in the generator. We repeat this process until n is a single digit.
Added a solution that gives the calculation explicitly:
def sum_dig(n):
_sum = sum(int(i) for i in str(n))
explained = "+".join(list(str(n)))
return _sum, explained
n = 256
s = ""
while n > 10:
n, e = sum_dig(n)
s+= f'{e}='
s += str(n)
print(s)
yields:
2+5+6=1+3=4
you can try this.
a = int(input("Enter a value"))
b = int(input("Enter second value"))
number = pow(a, b)
result = str(a)+'^'+str(b) + ' = ' + str(number)
while number > 9:
digit_sum = sum(map(int, str(number)))
result += ' = ' + '+'.join(str(number)) + ' = ' + str(digit_sum)
number = digit_sum
print ( result )
for a=2, b=8 result:
2^8 = 256 = 2+5+6 = 13 = 1+3 = 4
This produces the output in the format OP asked for:
a = int(input("Enter a value: "))
b = int(input("Enter second value: "))
n = pow(a, b)
while n >= 10:
nums = [i for i in str(n)]
op = "+".join(nums)
n = eval(op)
print("{}={}".format(op, n))
Logic:
Store the input in an array of individual numbers as strings.
Create the summation string using "+".join(nums) - for the output print.
Calculate the sum using eval(op) which works on strings (a built-in function) - store in n.
Print the summation string and what it equals.
Output:
Enter a value: 2
Enter second value: 8
2+5+6=13
1+3=4
Enter a value: 2
Enter second value: 6
6+4=10
1+0=1
Enter a value: 2
Enter second value: 50
1+1+2+5+8+9+9+9+0+6+8+4+2+6+2+4=76
7+6=13
1+3=4
sol = 0
if (a^b)%9==0:
sol = 9
else:
sol = (a^b)%9