Adding Numbers in a Range with for() Loop - python

I'm having trouble filling out a question on an online python tutorial. It seems really simple but for the life of me I can't figure it out. This is the problem "write a for loop that adds all the numbers 1 to 10 and returns the sum." And this is the code I have been trying:
def run():
sum = 0
for i in range(11):
sum += i
return sum
What am I doing wrong? Thanks for any help.

You're returning within the loop, after one iteration. You need to dedent the return statement so that it falls outside the loop:
def run():
sum_ = 0
for i in range(11):
sum_ += i
return sum_

if anyone want to know how to add 0 + 1 count until 100. There is it!
x = 0
while x<100:
x += 1
print(x)

You are returning the sum from within the for loop. Indent it outside. Keep it at the same level of indentation as for.

You need to dedent the return statement so that it falls outside the loop:
def addNumbers(num)
sum=0
for i in range(0,num+1)
sum=sum+i
return sum

def run(n):
total = 0
for item in range(n):
total = total + item
return total
print(run(11))

Related

How to use a while loop to print every number in a range in Python

I'm working on a practice problem that says, "Make a function that receives an integer as an argument (step) and that prints the numbers from 0 to 100 (included), but leaving step between each one.
Two versions: for loop and a while loop.
I can do it using a foor loop:
def function(x):
count = 0
for x in range(0, 100, x):
print(x)
I can't seem to make it work with a while loop. I've tried this:
def function(x):
count = 0
while count <= 100:
count += x
print(count)
so please, help. Thank you!
You need to increment count after printing.
def function(x):
count = 1
while count <= 100:
print(count)
count += x

Add all numbers from 1 through n and print their sum

I am new to python and trying to write a program to add all the numbers starting from 1 through n and print their sum. Can anyone please tell me what is wrong with my code. I am getting 1 as an output.
def problem1_3(num):
sum_= 0
num = int(num)
for i in range(1,num):
sum_ = sum_ + i
print(sum_)
i+=1
return(sum_)
You are returning the sum_ on the first iteration of the function. You want to finish the for loop, and only then return it. Read more about loops in python, they are based on indentation, unlike some other languages.
Two mistakes that you are making in your code:
1- You are incrementing i by +1 but you don't have to do this because python will automatically increment loop variable.
2- You are returning your sum_ variable inside for loop that's why you got 1 as an output.
def problem1_3(num):
sum_= 0
num = int(num)
for i in range(1,num+1):
sum_ = sum_ + i
#print(sum_)
# i+=1
return(sum_)
ans = problem1_3(5)
print(ans)
Output:
15
So you are returning inside your for loop, so it does not go to completion.
but if you would like an easier more concise way to write that function,
def problem1_3(num):
return sum(range(num)) #for up to, but not including num
or
def problem1_3(num):
return sum(range(num+1)) #for up to, AND including num
Since you already have the range function, range produces a list of numbers. So range(5) is [0,1,2,3,4]
and summing them will get you 1+2+3+4
it's just a shorter way of doing the same thing.
If you don't have to use for loop, it's better to use recursion.
def problem1_3(num : int) -> int:
if num == 1:
return 1
else:
return num + problem1_3(num-1)
# 5 + problem1_3(4)
# 5 + 4 + problem1_3(3)
# 5 + 4 + 3 + problem1_3(2)
# 5 + 4 + 3 + 2 + problem1_3(1)
# 5 + 4 + 3 + 2 + 1
.
if you have to use loops.
your problem is when you are returning sum_. you should to finish your loop and after all, Outside the loop, return the sum:
def problem1_3(num : int) -> int:
sum_ = 0
for i in range(1, num+1):
sum_ += i
return (sum_)

infinite loop started , Why?

I am using following code to find sum of digits in Python but infinite loop gets started as I run program
def digit_sum(n):
k=str(n)
i=0
while i<range(len(k)):
l=int(i)
j=0
j=j+i
print j
i+=1
digit_sum(1234)
You have an indentation error.
So, for getting correct output try this way . You can check this code here .
def digit_sum(n):
k = str(n)
i = 0
j = 0
while i < len(k):
l = int(k[i])
j = j + l
i += 1
print j
digit_sum(1234)
The indentation is wrong. The while loop is outside of your function. Indent it to stay inside the function. Also give more meaningful names to your variables.
Its looks like you are new to python So i m going to help you out i have seen you code it seems like you have indentation problem and some logic problem also so i have updated it see it here
def digit_sum(n):
k = str(n)
j = 0 #sum for digits
i = 0
while i in range(len(k)):
#Add convert string to the int and add to the sum
j = j + int(k[i]);
#increment Counter
i = i+1
print j # print Sum
digit_sum(1234)
For more info about indentation you can See Here

What is wrong with this code for an even-number fibonacci sequence in Python?

def fibonacci(n):
first = 0
second = 1
count = 0
while count <= n:
if (second % 2 == 0):
first, second = second, first + second
count += 1
return first, second
print (fibonacci(4000000))
Can somebody please explain what is wrong with this code? In IDLE the page restarts but returns no answer. By the way, I'm a beginner programmer, only just finished the CodeAcademy course.
Since this is for Problem 2 of Project Euler, you're computing the wrong values. It asks for the sum of all even Fibonacci numbers up to a value of four million, not the four millionth value. That would be too large.
Since we want to keep generating values, we'll use a generator and combine it with itertools.takewhile(). Then we'll filter() it down to the even values, and find the sum().
import itertools
def fibonacci_gen():
first = 0
second = 1
while 1:
first, second = second, first + second
yield second
>>> a = fibonacci_gen()
>>> sum(filter(lambda y: not y%2, itertools.takewhile(lambda x: x<=4e6, a)))
4613732
For a solution that doesn't use these features:
def fibonacci_4m():
result = 0
first = 0
second = 1
while second <= 4e6:
first, second = second, first + second
if not second%2:
result += second
return result
>>> fibonacci_4m()
4613732
second % 2 starts off as 1, which is not odd. Consequently your while loop doesn't run anything in the body, so the loop runs forever.
You probably want to always compute the next Fibonacci number, but only increment the count if the second is even.
Your problem is that you have your count variable inside the if statement. You have created an infinite while loop. Move it outside of the if statement:
if(second % 2 == 0):
first, second = second, first + second
count +=1
Also you will have to add more code to make this work properly.
In your while loop, nothing changes when the if statement fails to execute its conditional code. Try the following instead:
def main():
for index in range(1, 41):
print('even_fibonacci({}) = {}'.format(index, even_fibonacci(index)))
def even_fibonacci(index):
for number in all_fibonacci():
if not number & 1:
index -= 1
if not index:
return number
def all_fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
if __name__ == '__main__':
main()

Return outside function error in Python

This is the problem:
Given the following program in Python, suppose that the user enters the number 4 from the keyboard. What will be the value returned?
N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
counter = counter * N
N = N - 1
return counter
Yet I keep getting a outside function error when I run the system
what am I doing wrong?
Thanks!
You can only return from inside a function and not from a loop.
It seems like your return should be outside the while loop, and your complete code should be inside a function.
def func():
N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
counter = counter * N
N -= 1
return counter # de-indent this 4 spaces to the left.
print func()
And if those codes are not inside a function, then you don't need a return at all. Just print the value of counter outside the while loop.
You have a return statement that isn't in a function. Functions are started by the def keyword:
def function(argument):
return "something"
print function("foo") #prints "something"
return has no meaning outside of a function, and so python raises an error.
You are not writing your code inside any function, you can return from functions only. Remove return statement and just print the value you want.
As already explained by the other contributers, you could print out the counter and then replace the return with a break statement.
N = int(input("enter a positive integer:"))
counter = 1
while (N > 0):
counter = counter * N
N = N - 1
print(counter)
break
It basically occours when you return from a loop you can only return from function

Categories

Resources