I am trying to figure out how to change a for loop into a while loop for this function:
def sumIt():
A=1
number=int(input('Enter a number(integer):'))
total=0.0
for counter in range(number):
total+=A
A+=1
print('The sum from 1 to the number is:',total)
averageIt(total,number)
#average sum and number
def averageIt(total,number):
print('The average of the sum and the number is:',(total+number)/2)
sumIt()
would I just say:
while number>1:
You can increment the counter variable manually:
counter = 0
while counter < number:
total += A
A += 1
counter += 1
or you could decrement the counter starting at number:
counter = number
while counter:
total += A
A += 1
counter -= 1
where we use the fact that any non-zero number is True in a boolean context; the while loop will end once counter reaches 0.
You use counter instead of number here because you still need to use number later on for the averageIt() function.
You can by creating the counter yourself:
number=int(input('Enter a number(integer):'))
total = 0.0
counter = 0
while counter < number:
total += A
A += 1
counter += 17
The for block is still the more Pythonic and readable way however. Also try to avoid to cast the result of an user input without verification/try block: if he entered 'abc', your code will raise the exception ValueError, since it's impossible to convert abc into an integer.
Why even use a loop at all?
Instead of
for counter in range(number):
total+=A
A+=1
Just use
total += (number*(number+1) / 2) - (A*(A-1)/2) # account for different starting values of A
A += number
Related
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
I am trying to count the instances of "1" appearing in a list. When I used index to access the elements in the list and implement a counter, the total number of count is always 1.
However, when I used the normal "for" iterations, the count actually works. Could anyone enlighten me?
Here's a snippet of what DOES NOT work:
for entry in range(len(nums)):
count = counts = 0
if nums[entry] == 1:
count = count + 1
print(count)
Here's a snippet of what works:
for num in nums:
if num == 1:
counts = counts + 1
This is because you define the counter inside the for-loop and thus it gets reset to 0 in each iteration.
Just make sure to define the counter outside of the for loop
count = 0
for entry in range(len(nums)):
if nums[entry] == 1:
count = count + 1
print(count)
Im trying to have users enter numbers until it equals 999. For some reason the first number entered doesn't register and comes up at 0. I know I've set it as 0 but thats to push the program into a loop.
counter = 0
equals = 0
while equals < 999:
equals = equals + counter
print(equals)
if counter < 998:
counter = eval(input("Enter numbers to equal 999"))
else:
print("number entered is equal or over 999")
It prints 0 in the first iteration because you print(equals) before reading it from the input. So:
counter = 0
equals = 0
while equals < 999:
if counter < 998:
counter = int(input("Enter numbers to equal 999"))
else:
print("number entered is equal or over 999")
equals = equals + counter
print(equals)
The following code should be taking two numbers from the user and then state which number is higher, 9 times, thus "counter <10 " except it only takes the two numbers once, and then the loop is finished. I thought I could increment the loop by using "counter=counter +1" in my loop, but it doesnt seem to work. Any help would be appreciated, thanks!
counter = 0
for counter in range(counter < 10):
num1 = float(input("Enter number 1: "))
num2 = float(input("Enter number 2: "))
if num1 > num2:
print(num1)
else:
print(num2)
counter = counter + 1
counter < 10 returns True which is equal to 1:
>>> counter = 0
>>> counter < 10
True
>>> True == 1
True
In turn, range(1) yields 0 (single item):
>>> list(range(counter < 10))
[0]
That's why it loop once.
Instead of range(counter < 10), you should use range(9). You don't need to declare counter = 0 and to increment yourself counter = counter + 1. for statement take care of it:
>>> for i in range(3):
... print(i)
...
0
1
2
counter<10 is equivalent to 1. That is why, the loop runs just once ( range(1) = {0} ).
You can use either :
for counter in range(10):
...
or
counter = 0
while( counter<10 ):
...
counter+=1
for your purpose.
To make it more clear to you, the expression within the brackets are evaluated at first place. If you want to use for, then you need to pass a sequence, over which the for will loop through. The range() is used to generate the sequence . But here you are passing (count < 10) to range(), which is a condition. So while evaluated, it returns True since counter is 0 (initialized in the first line) and is less than 10. And this returned True is equivalent to 1, so the rest goes as described by falsetru
If you want to pass a condition, then you should use while loop, instead of for. In for, you don't even need to initialize the variable counter separately. If you write :-
for counter in range(9):
this will initialize counter variable and it would be incremented in each iteration.
For your question you can use either of the following:-
for counter in range(9):
# No need to initialize counter
do_stuff
or
# Initialize counter
counter = 0
while(counter <10):
do_stuff
Here is what I'm supposed to write:
a function, countDigits, which will take an integer as a parameter and return the sum of its digits (you must use a for loop). For instance, the number 123 would return 6 (1 + 2 + 3)
a main function which will count numbers starting at one, and ending when the total digits (for all the numbers) exceeds 1,000,000. So, if you want the total digits for the number 5, you would add:
1 = 1
2 = 2 + 1
3 = 3 + 3
4 = 6 + 4
5 = 10 + 5, so 15 would be the total digit count.
your program will print both the number and the digit count before it exceeds 1,000,000. This is easiest with a while loop.
I've written the code for the function countDigits, which is:
def countDigits():
value=int(input('Enter Integer: '))
str_num= str(value)
total = 0
for ch in str_num:
total += int(ch)
print(total)
However, I'm stuck as to how to write the main function. Can anyone point me in the right direction?
EDIT
Here is my revised countDigits function:
def countDigits(value):
str_num= str(value)
total = 0
for ch in str_num:
total += int(ch)
print(total)
a one-liner:
factorial_digit_sum = lambda x: sum( sum(map(int, str(a))) for a in range(1,x+1) )
If you EVER write real code like this, Guido will hunt you down. Was kind of a fun brain teaser to golf, though.
For a real answer:
def countDigits(number):
return sum(map(int, str(number)))
def main():
total = 0
count = 1
while total <= 1000000:
total += countDigits(count)
total -= countDigits(count) # you want the number BEFORE it hits 1000000
print("Summing the digits of {}! yields {}".format(count, total))
main()
The problem in your code is that your countDigits function requests user input. You should change that to accepting the integer as a parameter. It also prints the result instead of returning it.
As #Blorgbeard mentioned in the comments, change countDigits to accept an integer as input. Also, return the total from it.
In the main function, read input, call countDigits and add them in a while loop until the total is greater than 1,000,000
def countDigits(value):
str_num= str(value)
total = 0
for ch in str_num:
total += int(ch)
return total
grandTotal = 0
while ( grandTotal < 1000000 ):
value=int(input('Enter Integer: '))
grandTotal += countDigits(value)