For example, if user keys in 6, the output is 21 (1+2+3+4+5+6)
sum = 0
num = int(input("Enter number: "))
…..
….
This is my code below:
x=0
sum = 0
nums = int(input("enter num "))
while sum <= nums:
sum+=1
x= x + sum
y = x - nums -1
print(y)
First of all, I suggest not to use sum as variable name, this will shadow the built-in sum() function.
There are two ways to do it using while loop, the first one is close to yours but turn <= to < in the condition so you don't need extra - num - 1 at the end.
n = 0
total = 0
num = int(input("enter num "))
while n < num:
n += 1
total += n
print(total)
Second one adds number in descending order, it also change the value of num. If you need num for later use, use the first one.
total = 0
num = int(input("enter num "))
while num:
total += num
num -= 1
print(total)
If loop is not needed, as you are going to obtain a triangular number, just use the formula.
num = int(input("enter num "))
print(num * (num + 1) // 2)
If you don't have use a loop you could do it in a single line:
print(sum(range(1, int(input('Enter a number: ')) + 1)))
Test:
Enter a number: 6
21
Related
Just a simple example of what i want to do:
numberOfcalculations = 3
count = 1
while contador <= numberOfcalculations:
num = int(input(' number:'))
num2 = int(input(' other number:'))
calculate = num * num2
print(calculate)
count = count + 1
How do i store the 3 different values that "calculate" will be worth in a list []?
When you initialize calculate as list type you can append values with + operator:
numberOfcalculations = 3
count = 1
calculate = []
while count <= numberOfcalculations:
num = int(input(' number:'))
num2 = int(input(' other number:'))
calculate += [ num * num2 ]
print(calculate)
count = count + 1
Also you have to change contador somehow or you will end up in an infinite loop maybe. I used count here instead to give the user the ability to input 3 different calculations.
I need help with this Python program.
With the input below:
Enter number: 1
Enter number: 2
Enter number: 3
Enter number: 4
Enter number: 5
the program must output:
Output: 54321
My code is:
n = 0
t = 1
rev = 0
while(t <= 5):
n = int(input("Enter a number:"))
t+=1
a = n % 10
rev = rev * 10 + a
n = n // 10
print(rev)
Its output is "12345" instead of "54321".
What should I change?
try this:
t = 1
rev = ""
while(t <= 5):
n = input("Enter a number:")
t+=1
rev = n + rev
print(rev)
Try:
x = [int(input("Enter a number")) for t in range(0,5)]
print(x[::-1])
There could be an easier way if you create a list and append all the values in it, then print it backwards like that:
my_list = []
while(t <= 5):
n = int(input("Enter a number:"))
t+=1
my_list.append(n)
my_list.reverse()
for i in range(len(my_list)):
print(my_list[i])
You can try this:
n = 0
t = 1
rev = []
while(t <= 5):
n = int(input("Enter a number:"))
t+=1
rev.append(n)
rev.reverse()
rev = ''.join(str(i) for i in rev)
print(rev)
Maintaining a numerical context: use "10 raised to t" (10^t)
This code is not very different from your solution because it continues to work on integer numbers and return rev as an integer:
t = 0
rev = 0
while (t < 5):
n = int(input("Enter a number:"))
# ** is the Python operator for 'mathematical raised to'
rev += n * (10 ** t)
t += 1
print(rev)
(10 ** t) is the Python form to do 10^t (10 raised to t); in this context it works as a positional shift to left.
Defect
With this program happens that: if you insert integer 0 as last value, this isn't present in the output.
Example: with input numeric 12340 the output is the number 4321.
How to solve the defect with zfill() method
If you want manage the result as a string and not as a integer we can add zeroes at the start of the string with the string method zfill().
In this context the zfill() method fills the string with zeros until it is 5 characters long.
The program with this modification is showed below:
NUM_OF_INTEGER = 5
t = 0
rev = 0
while (t < NUM_OF_INTEGER):
n = int(input("Enter a number: "))
rev += n * (10 ** t)
t += 1
# here I convert the number 'rev' to string and apply the method 'zfill'
print(str(rev).zfill(NUM_OF_INTEGER))
With previous code with input "12340" the output is the string "04321".
n = int(input("How many number do you want to get in order? "))
list1 = []
for i in range(n):
num = int(input("Enter the number: "))
thislist = [num]
list1.extend (thislist)
list1.sort()
print ("The ascending order of the entered numbers, is: " ,list1)
list1.sort (reverse = True)
print ("The descending order of the entered numbers, is: " ,list1)
This question already has answers here:
Sum of the integers from 1 to n
(11 answers)
Closed 6 months ago.
The question was tp :write a program to find the sum of n natural numbers using while loop in python.
n = int(input("Enter a number: "))
i = 1
while i<n:
print(i)
i = i + 1
this is what I have done s far...
can not understand what to do next.
n = int(input("enter a number: "))
i = 1
sum = 0
while (i <= n):
sum = sum + i
i = i + 1
print("The sum is: ", sum)
with a while loop the sum of natural numbers up to num
num = 20
sum_of_numbers = 0
while(num > 0):
sum_of_numbers += num
num -= 1
print("The sum is", sum_of_numbers)
You can either follow Alasgar's answer, or you can define a function with the formula for this particular problem.
The code's gonna be something like this:
def natural(n):
sumOfn = (n * (n + 1))/2
terms = int(input("Enter number of terms: "))
natural(terms)
number = int(int(input("Enter the number: "))
if number < 0:
print("Enter a positive number: ")
else:
totalSum = 0
while (number > 0):
totalSum += number
number -= 1
print ("The sum is" , totalSum)
num = int(input('Enter the number : '))
sum = 0
while 0<num:
sum += num
num -= 1
print(f'The sum of the number is {sum}')
I have this Python assigment to complete where I need to write a program that reads in X whole numbers and outputs (1) the sum of all positive numbers, (2) the sum of all negative numbers, and (3) the sum of all positive and negative numbers. The user can enter the X numbers in any different order every time, and can repeat the program if desired. This is what I've got so far:
x = int(input('How many numbers would you like to enter?: '))
sumAll = 0
sumNeg = 0
sumPos = 0
for k in range (0,x,1):
num = int(input("please enter number %i :" %(k+1)))
sumAll = sumAll + num
if num < 0:
sumNeg += num
if num > 0:
sumPos += num
if k == 0:
smallest = num
largest = num
else:
if num < smallest:
smallest = num
if num > largest:
largest = num
print("The sum of negative numbers is: " , sumNeg)
print("The sum of positive numbers is: " , sumPos)
print("The sum of all numbers is: " , sumAll)
count = 0
repeat = input('Would you like to repeat? y/n: ')
repeat = 'y'
while y == 'y':
I'm just a little stuck after this point. Any ideas on what I should do?
A simple while loop would suffice.
run = True
while run is True:
x = int(input('How many numbers would you like to enter?: '))
sumAll = 0
sumNeg = 0
sumPos = 0
for k in range (0,x,1):
num = int(input("please enter number %i :" %(k+1)))
sumAll = sumAll + num
if num < 0:
sumNeg += num
if num > 0:
sumPos += num
if k == 0:
smallest = num
largest = num
else:
if num < smallest:
smallest = num
if num > largest:
largest = num
print("The sum of negative numbers is: " , sumNeg)
print("The sum of positive numbers is: " , sumPos)
print("The sum of all numbers is: " , sumAll)
repeat = input('Would you like to repeat? y/n: ')
if repeat != 'y':
run = False
Example of the output:
How many numbers would you like to enter?: 4
please enter number 1 : 3
please enter number 2 : 2
please enter number 3 : 4
please enter number 4 : 5
The sum of negative numbers is: 0
The sum of positive numbers is: 14
The sum of all numbers is: 14
Would you like to repeat? y/n: y
How many numbers would you like to enter?: 3
please enter number 1 : 2
please enter number 2 : 4
please enter number 3 : 3
The sum of negative numbers is: 0
The sum of positive numbers is: 9
The sum of all numbers is: 9
Would you like to repeat? y/n: n
You just need to place your code inside an outer loop, that might start it all over again if the user wants to repeat.
while True:
# all your current code until the prints
repeat = input('Would you like to repeat? y/n: ')
if repeat is not 'y':
break
Prompt: Write a program that adds all the digits in an integer. If the resulting sum is more than one digit, keep repeating until the sum is one digit. For example, the number 2345 has the sum 2+3+4+5 = 14 which is not a single digit so repeat with 1+4 = 5 which is a single digit.
This is the code I have so far. It works out for the first part, but I can't figure out how to make it repeat until the sum is a single digit. I'm pretty sure I'm supposed to nest the code I already have with another while statement
n = int(input("Input an integer:"))
sum_int=0
while float(n)/10 >= .1:
r= n%10
sum_int += r
n= n//10
if float(n)/10 > .1: print(r, end= " + ")
else: print(r,"=",sum_int)
this is a sample output of the code
Input an integer: 98765678912398
8 + 9 + 3 + 2 + 1 + 9 + 8 + 7 + 6 + 5 + 6 + 7 + 8 + 9 = 88
8 + 8 = 16
1 + 6 = 7
This should work, no division involved.
n = int(input("Input an integer:"))
while n > 9:
n = sum(map(int, str(n)))
print(n)
It basically converts the integer to a string, then sums over the digits using a list comprehension and continues until the number is no greater than 9.
You could utilize recursion.
Try this:
def sum_of_digits(n):
s = 0
while n:
s += n % 10
n //= 10
if s > 9:
return sum_of_digits(s)
return s
n = int(input("Enter an integer: "))
print(sum_of_digits(n))
you can try this solution,
if n=98 then your output will be 8
def repitative_sum(n):
j=2
while j!=1:
n=str(n)
j=len(n)
n=list(map(int,n))
n=sum(n)
print(n)
You don't need to convert your integer to a float here; just use the divmod() function in a loop:
def sum_digits(n):
newnum = 0
while n:
n, digit = divmod(n, 10)
newnum += digit
return newnum
By making it a function you can more easily use it to repeatedly apply this to a number until it is smaller than 10:
n = int(input("Input an integer:"))
while n > 9:
n = sum_digits(n)
print(n)
def add_digits(num):
return (num - 1) % 9 + 1 if num > 0 else 0
A simple, elegant solution.
I'm not sure if it's anti-practice in Python because I know nothing about the language, but here is my solution.
n = int(input("Input an integer:"))
def sum_int(num):
numArr = map(int,str(num))
number = sum(numArr)
if number < 10:
print(number)
else:
sum_int(number)
sum_int(n)
Again I am unsure about the recursion within a function in Python, but hey, it works :)
If you like recursion, and you must:
>>> def sum_digits_rec(integ):
if integ <= 9:
return integ
res = sum(divmod(integ, 10))
return sum_digits(res)
>>> print(sum_digits_rec(98765678912398))
7
def digit_sum(num):
if num < 10:
return num
last_digit = num % 10
num = num / 10
return digit_sum(last_digit + digit_sum(num))
input_num = int(input("Enter an integer: "))
print("result : ",digit_sum(input_num))
This may help you..!
Try with strings comprehension:
new = input("insert your number: ")
new = new.replace(" ","")
new =sum([int(i) for i in new])
if new not in range (10):
new = str(new)
new = sum ([int(i) for i in new])
print (new)
Note that the answers which convert int to str are relying on the python conversion logic to do internally the divmod calculations that we can do explicitly as follows, without introducing the non-numeric string type into an intrinsically numerical calculation:
def boilItDown(n):
while n >= 10:
t = 0
while n:
d, m = divmod(n, 10)
n, t = d, t + m
n = t
return n
n = 98765678912398
print(boilItDown(n))
Output:
7