Adding more variables to result every while loop - python-3.x

I started to learn python last week and I have to write a while loop where the user is repeatedly asked to input an even number. Then, as long as he inputs an even number, the program should put out the sum of all of the previously added numbers. As soon as an odd number is added, the loop should stop without putting out the odd-numbered result.
Do you have any tipps?
thank you!

total = 0
while True:
number = int(input("enter number:" ))
if number % 2 == 0:
total += number
print(f"Total: {total}")
else:
print(f"Final total: {total}")
break
total = 0 - First, we want to initialize our total variable so that we can use it within the loop to count up the sum of all entries.
The while True: line starts an infinite loop. These can be dangerous, but we're going to break out of it later when a condition is met (in this case, an odd number being entered).
number = int(input("enter number: ")) asks the user for input, converts that input into and int and stores it in the variable called number.
if number % 2 == 0: - This checks whether or not the number is even using the modulo operator. This returns the remainder from the division of the first number into the second. For a number to be even, it must have a remainder of 0 when divided by 2.
total += number is shorthand for total = total + number. This simply adds the user's input to the total.
print(f"Total: {total}") prints out the total using an f-string. See PEP 498 for more info. Essentially, creating an f-string is as easy as putting an f before the literal string creation. This allows you to plug variables directly into strings instead of having to rely on the .format() method.
The above print line would be written as print("Total: {}".format(total)) if not using f-strings.
The else statement catches any number that is not even, so therefore must be odd. It prints out the final total and then break will make us leave our infinite loop.

Related

Python, How do I ignore a string such as 'done' amongst numbers to sum the total from a list

while True:
numbers = input('> ')
if numbers == 'done':
break
total = 0
for number in numbers:
if numbers == int:
total = total + numbers
print(total)
I've had a hard time understanding exactley what u want to do with this code, please use a proper code block next time, with proper indentation. My guess is that u want to get a input number like 345 and add 3+4+5 as a output. If the input is not a int it should break the loop. Ive come up with 2 diffrent solutions, depending on what you need.
This code will simply take the input and check if it is "done", if it is not "done" it will try to add. This is a easy to understand solution but it will produce a error if the input is any diffrent string than "done".
while True:
numbers = input(">")
if numbers == "done":
break
else:
total = 0
for number in numbers:
total += int(number)
print(total)
This approach will test for the "done" string again, but afterwards will also check if the input can be converted into a int. if not the error is captured and it will return "invalid input". If u want the programm to terminate at any string u can just put break in the except section.
while True:
numbers = input(">")
if numbers == "done":
break
else:
try:
testing = int(numbers)
total = 0
for number in numbers:
total += int(number)
except:
total = "invalid input"
print(total)
im a Beginner myself and if a experiencend person can show me a better way to do this i would be very interested
while True:
numbers = input('> ')
if numbers == 'done':
break
total = 0
for number in numbers:
if numbers == int:
total = total + numbers
print(total)
Assuming this as your code:
Here's a solution to your problem-->
numbers=[]
while True:
a=input('>')
if a=='done':
break
else:
numbers.append(a)
total=0
for number in numbers:
total = total + int(number)
print(total)
By default everything gets accepted as string so we convert it to integer to find total.
Also we use list to store all the values we accept.
Another Solution is-->
numbers=[]
while True:
a=input('>')
if a=='done':
break
else:
numbers.append(a)
p=map(int,numbers)
print(sum(p))
Hope you understand the solution :-)
total = 0
average = 0
count = 0
while True:
numbers = input('> ')
if numbers == 'done': break
try:
total = int(numbers) + total
count = count + 1
except:
print('nope')
try:
average = total / count
except:
print('error')
print(total)
print(average)
print(count)
Try this:
total = 0
number_of_inputs = 0
while True:
number_string = input('Enter a number: ')
try:
total += float(number_string)
number_of_inputs += 1
except ValueError:
break # we weren't given a number, so exit the loop
# Now that we're outside of the loop, print out the total:
print('The total is:', total)
if number_of_inputs > 0:
average = total / number_of_inputs
print('The average is:', average)
else:
print('The average cannot be calculated, as no inputs were given.')
Do you see what's happening? The while loop keeps ask for and adding integers to total until a non-integer (like "done") is given. Once it gets that non-integer, the int() function will fail, and the exception it throws will get caught, and the code will immediately break out of the while loop.
And once out of the loop, the total and the average are printed out.
A few things you should be aware of:
If the user gave no inputs (which is possible here), the total will correctly print out as 0, but if you try to calculate the average, you will error, due to diving by number_of_inputs (which is also 0). That is why I check that number_of_inputs is greater than zero before I even attempt to calculate the average.
Originally I used int() to convert the string to a number, but I changed it to use float() instead. I figure that since you want to calculate an average, averages are not necessarily integers (even if all the inputs are), so there's no point in enforcing integer input. That is why I changed the int() to float(), but whether or not you want to use it is up to you.
ValueError isn't a function; it's an Exception. At this point you probably don't know what Exceptions are, so just know that they are special cases that can happen, and they're often used for catching errors, such as bad input values.
In the code I posted above, the loop is always expecting numerical input. But as soon as we have input that can't be converted to a number, the program then says, "Hey, I have an exception to what we're expecting! The exception is that there's an error in the value!" Then the program, instead of continuing to the next line of code (which is number_of_inputs += 1) will then execute the block of code under the except ValueError: section. And in the code above, all it does is call break, which exits the loop.
Once out of the loop, the code prints out the total and the average.
If it weren't for the try: and except ValueError: lines in the code, then the program would abruptly end (with a lengthy error message) once someone gave a non-numerical input. That happens because the call to float() wouldn't know how to convert a value like "done" to a number, so it does nothing more than just quitting.
However, by using try: and except ValueError:, we are anticipating that someone might give non-numerical input. When that happens (which it will, when the user is finished giving inputs) -- instead of quitting -- we want an alternate action to take. And we specify that alternate action to be a simple break out of the loop -- which will allow the program to continue with whatever is after the loop.
I hope this makes sense. If it doesn't, it will make more sense once you start learning about Exceptions in Python.

Find the sum of the digits using a loop and a function

I am using a function to get the number from user, and I am trying to use a while loop to separate the digits of a number. And I am trying to add the digits of the number. But my code runs infinitely.
Example : 2345 -> 15
def sumDigits(n):
sum=0
while len(str(n))>0:
a = n%10
n = n//10
sum += a
return sum
print(sumDigits(2345))
Expected: 15
Actual: I had to shut down the jupyter kernel to stop the while loop.
Edit 2: Removed the updated code as it was answered by the community.
This condition len(str(n))>0 can never be false as long as n is an integer, because str(0) is '0', which has a length of 1.
You need to change the looping condition to exit where there is no more digit to sum, which happens when n reaches 0:
def sum_digits(n):
total = 0
while n > 0:
a = n % 10
n = n // 10
total += a
return total
print(sum_digits(2345))
Note: sum is a built-in in python, so naming a variable sum is not advised. Also, method names usually are written in snake_case, so sum_digits is recommended.
def all_sum(number):
total = 0
if number > 0:
for e in str(number):
if e.isdigit():
total += int(e)
else:
pass
return total
a = all_sum(567897)
This should do your work. Instead of doing two arithmetic operations to 'fetch' the digits, better to change the argument to string and just use each digit. Its faster and saves memory (though it's not too memory consuming).

Multiplication table in Python with # on all even numbers

I am trying to create a python multiplication table from 2 - 10. If you enter an invalid number it will tell you that it is an invalid entry and ask you to input a number again. It is also supposed to put a # on all even numbers. I am having trouble continuing after an invalid entry and also putting a # on all even numbers. My current code is below
def main():
rows = int(input("What size multiplication table would you like (2-10): "))
if rows <=1 or rows >10:
print (" Invalid Entry - Enter a number between 2 - 10 ")
else:
counter = 0
multiplicationTable(rows,counter)
def multiplicationTable(rows,counter):
size = rows + 1
for i in range (1,size):
for nums in range (1,size):
value = i*nums
print(value,sep=' ',end="\t")
counter += 1
if counter%rows == 0:
print()
else:
counter
main()
I am typing this on my phone so bear with me.
Since you are trying to only get a certain input, you want to have a loop so that we can keep asking the user to enter a number if it is outside the range we want.
So in a generic example where we repeatedly ask a user for a certain input:
While True:
rows = int(input(“enter size: “))
if 1 <= rows < 10:
multiplicationTable(rows, 0)
break
else:
print(“Invalid”)
continue
While True: will run infinitely naturally. However, the magic is in the continue and break statements. continue will make it restart at the top of the loop and break will make it exit the loop after the process is done.
note:
Some programmers consider it bad practice to use the loops in this fashion because it could imply poor logic.
If you need help with an alternate solution I can try and help when I get to my computer.
Best of luck!

I am almost there but program can not recognize negatives

Program has to count positive and negative numbers and compute the average. I feel like i have the right code but maybe something is off. This was done on python idle 3.5. I would appreciate any and all help.
#Variables
total=0
pos=0
neg=0
avg=0
i=eval(input("Enter an integer, the input ends if it is 0:"))
#main
while (i!=0):
total=total+i
i=eval(input("Enter an integer, the input ends if it is 0:"))
if(i>0):
pos+=1
elif(i<0):
neg+=1
print("The number of positives is ", pos)
print("The number of negatives is ", neg)
print("The total is",total)
print("The average is ", avg)
avg=total/(pos+neg)
One Problem your code has is, that the first number you are entering does not count towards either the positive or negative counts in your loop because it is outside of it. As soon as you enter the loop you do add it to the total, but then you ask for the next number. This way your first number is never evaluated.
What you could do is a while loop that has the condition "True", so it runs every time you start the program. The evaluation on whether your input is a zero can be (and in this case must be) handled in your else/elif/else block.
If you don't include a break there you are getting an infinite loop.
You should not us eval(). The Documentation on python states this:
This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case pass a code object instead of a string. If the code object has been compiled with 'exec' as the mode argument, eval()’s return value will be None.
If you use int() the program knows if it is negative or not since you compare the input to zero in your if statements.
Maybe do something like this:
#Variables
total = 0
pos = 0
neg = 0
# avg = 0 (you don't have to declare this variable since you calculate it
# anyway later on)
# removed the input from here since it did not contribute to the pos/neg count
#main
while (True):
# maybe use a while loop with the condition "True" so it runs every time
i = int(input("Enter an integer, the input ends if it is 0: "))
total = total + i
if(i > 0):
# counts 1 up if integer is positive
pos += 1
elif(i < 0):
# counts 1 up if integer is negative
neg += 1
else:
# break out of the loop as soon as none of the above conditions is true
# (since it hits a 0 as input)
# else you get an infinite loop
break
avg = total / (pos + neg)
print("The number of positives is ", pos)
print("The number of negatives is ", neg)
print("The total is ", total)
print("The average is ", avg)

How to use calculated results in a repetitive algorithm

This is what I want to accomplish:
let the user type in a number with four digits
if this number is not equal to 6174 (Kaprekar’s constant) then sort the numbers in two ways:
a. from the biggest to the smallest number
b. from the smallest to the biggest
Subtract the bigger number with the smaller
If the result is not equal to 6174, then do the calculation again and write the result for each and every calculation
When the result is equal to 6174, write a message to show that the calculation is done
This is what I’ve tried:
print("type in a number")
number = (input())
while number != 6174:
start_big = "".join(sorted(number, reverse=True))
start_small = "".join(sorted(number))
number = (int(start_big)-int(start_small))
print(number)
print("Calculation finnished!")
I’m getting the error:
start_big = "".join(sorted(number, reverse=True)) TypeError: 'int'
object is not iterable
When you calculate this:
number = (int(start_big)-int(start_small))
The type of number becomes int, so in the next iteration the error occurs.
One solution would be
print("type in a number")
number = input()
while number != "6174":
start_big = "".join(sorted(number, reverse=True))
start_small = "".join(sorted(number))
number = str((int(start_big) - int(start_small)))
print(number)
print("Calculation finnished!")
you have to convert the input number to an iterable, you can just do
number = iter(number)
also you need to change the while loop condition:
while int(number) != 6174:
for printing the number just do this:
number = str((int(start_big)-int(start_small)))
You are almost there. You need to convert number to an iterable. I suggest:
start_big = "".join(sorted(str(number), reverse=True))
start_small = "".join(sorted(str(number)number))
You have multiple issues with your solution:
input() always returns a string, so number will never be an integer and as such it will never be equal to 6174. So your loop will still run for an input of 6174.
You need to convert the string into a number first, you can do that by simply calling int() on the string. Note that this may fail, so you might want to ask the user for input until they enter a valid number.
Once number is an integer, it is no longer an iterable, so you cannot call sorted() on it. If you want to sort the digits, then you need to convert it into a string first: sorted(str(number)).

Resources