How to generate a series using While loop - python

n = int(input("Enter n: "))
sum = 0
i = 1
while i <= n:
sum = sum +1
i = i+1
print("The sum is" , sum)
I tried the above code but didn't got my answer.
The question is to generate a series that is: 1,4,7,10,13,16,19,22 using while loop.

To generate series you need to do two things:
Put the print inside the loop to output accumulator variable's value every iteration
Add 3 to sum every iteration and not 1 since it's the difference between series members
n = int(input("Enter n: ")) # n=8 should work
sum = 1
i = 1
while i <= n:
print(str(sum)+",")
sum = sum +3
i = i+1

I see two errors:
You should add i to sum,not 1 (this assumes you are interested in the sum as implied by the code)
You should be incrementing i by 3 not by 1

If I understand you correctly, you want this:
i = 1
while i <= 22:
print(i)
i += 3

n = int(input("Enter n: "))
count = 0
i = 1
sum = 0
while count <= n-1:
print(i)
sum += i
i += 3
count += 1
print("Sum is", sum)

You are going to want to increase the count by three every time with i += 3.
def createList():
user_input = input()
i = 1
list_of_vals = []
while i < int(user_input): # The max value:
list_of_vals.append(i)
i += 3
return list_of_vals
print (createList())

I think you want something like this:
n = int(input("Enter n: "))
series_sum = 0
i = 1
series = []
add = 3
while i <= n:
series.append(i)
series_sum = series_sum + i
i = i + add
print("series: ", series)
print("The sum is" , series_sum)
This would get you a series (and sum of elements) with the last element less than n, starting from i = 1 and increment add = 3

Related

Store Values generated in a while loop on a list in python

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.

Sum of n natural numbers using while loop in python [duplicate]

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}')

How to separate for loop from if

ok = 1
while ok==1:
sum = 0
count = 0
a = int(input("Ievadiet, cik skaitļu būs virknē: "))
for i in range( 0, a):
N = int(input("Ievadiet veselu skaitli: "))
if N%2 == 1:
count+= 1
sum += N
if count != 0:
average = sum / count
print("Virknes nepāra skaitļu vidējā artimētiskā vērtība ir: ", average)
else:
print("Nevar aprēķināt nepāra skaitļu vidējo aritmētisko.")
ok = int(input(" Vai turpināt (1) vai beigt (0)?"))
This program should ask to type how many numbers will be in chain and then calculate the existing between these numbers the arithmetic mean of the odd numbers. How to separate "if count != 0" from "if N%2 == 1" so the programm will stop calculating arithmetic mean of every number but will calculated only when all numbers of the chain will be written.
Please check this code and see if that if what you want to reach. I just de-indented the last if...else block so no it first gets all the numbers and then shows the mean.
ok = 1
while ok == 1:
sum = 0
count = 0
a = int(input("Ievadiet, cik skaitļu būs virknē: "))
for i in range(0, a):
N = int(input("Ievadiet veselu skaitli: "))
if N % 2 == 1:
count += 1
sum += N
if count != 0:
average = sum / count
print("Virknes nepāra skaitļu vidējā artimētiskā vērtība ir: ", average)
else:
print("Nevar aprēķināt nepāra skaitļu vidējo aritmētisko.")
ok = int(input(" Vai turpināt (1) vai beigt (0)?"))
Have Fun :)

How can you sum these outputs in Python?

I made this code about a number and it's power. It will ask a number and it's power and show the output like a horizontal list.. Like
Number = 2
Power = 3.... then output will be like=
1
2
4
Number and power can be +/-.
But I want to sum those numbers like Sum = 7 after it shows
1
2
4
I have no idea how to do it after the output. I am new to programming maybe that's why can't figure out this problem.
Here is the code in Python :
A =float(input("Number:"))
B =float(input("Power:"))
print("Result of Powers:")
i = 0
while i < B:
print(A**i)
i = i + 1
while i >= B:
print(A**i)
i = i - 1
You could simplify this with numpy as follows
import numpy as np
A =float(input("Number:"))
B =int(input("Power:"))
print("Result of Powers:")
power = np.arange(B)
power_result = A ** power
sum_result = np.sum(power_result)
print(power_result)
print(sum_result)
I made B into an int, since I guess it makes sense. Have a look into the numpy documentation to see, what individual functions do.
You can create another variable to store the sum
and to print values on the same line use end=" " argument in the print function
a = float(input("Number:"))
b = int(input("Power:"))
sum = 0.0
i = 0
while b < 0:
ans = a**i
i = i - 1
print(ans, end=" ")
sum = sum + ans
b += 1
while b >= 0:
ans = a**i
i = i + 1
print(ans, end=" ")
sum = sum + ans
b -= 1
print("\nSum = " + str(sum))
I'm not sure what you want to achieve with the second loop. This works:
A =float(input("Number:"))
B =float(input("Power:"))
print("Result of Powers:")
i = 0
n_sum = 0
while i < B:
n_sum += A**i
print(A**i)
i = i + 1
while i >= B:
n_sum += A**i
print(A**i)
i = i - 1
print(n_sum)

how to use while loop to determine the amount of numbers in a list that are greater the average

Hi I need to do this task in two ways: one way with for loop which I did and other with while loop but I don't secceed....The code I wrote is:
A = [5,8,9,1,2,4]
AV = sum(A) / float(len(A))
count = 0
for i in A :
if i > AV :
count = count + 1
print ("The number of elements bigger than the average is: " + str(count))
count = 0
while float in A > AV:
count += 1
print ("The number of elements bigger than the average is: " + str(count))
The problem is that you are using while float in A > AV: in your code. The while works until the condition is true. So as soon as it encounters some some number in list which is smaller than average, the loop exits. So, your code should be:
A = [5,8,9,1,2,4]
AV = sum(A) / float(len(A))
count = 0
for i in A : if i > AV :
count = count + 1
print ("The number of elements bigger than the average is: " + str(count))
count = 0
i = 0
while i < len(A):
if A[i] > AV: count += 1
i += 1
print ("The number of elements bigger than the average is: " + str(count))
i hope it helped :) and i believe you know why i added another variable i.
Your code is indeed unformatted. Generally:
for x in some_list:
... # Do stuff
is equivalent to:
i = 0
while i < len(some_list):
... # Do stuff with some_list[i]
i += 1
A = [5,8,9,1,2,4]
AV = sum(A) / float(len(A))
count = 0
for i in A:
if i > AV:
count = count + 1
print ("The number of elements bigger than the average is: " + str(count))
count = 0
i = 0
while i < len(A):
if A[i] > AV:
count += 1
i += 1
print ("The number of elements bigger than the average is: " + str(count))
You can use something like the code below. I have commented on each part, explaining the important parts. Note that your while float in A > AV is not valid in python. In your case, you should access elements of a list by indexing or using a for loop with the in keyword.
# In python, it is common to use lowercase variable names
# unless you are using global variables
a = [5, 8, 4, 1, 2, 9]
avg = sum(a)/len(a)
print(avg)
gt_avg = sum([1 for i in a if i > avg])
print(gt_avg)
# Start at index 0 and set initial number of elements > average to 0
idx = 0
count = 0
# Go through each element in the list and if
# the value is greater than the average, add 1 to the count
while idx < len(a):
if a[idx] > avg:
count += 1
idx += 1
print(count)
The code above will output the following:
4.833333333333333
3
3
Note: There are alternatives to the list comprehension that I've provided. You could also use this piece of code.
gt_avg = 0
for val in a:
if val > avg:
gt_avg += 1

Categories