Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have an assignment. It was suppose to do the following:
--> Take an integer input(say 100)
--> Add the digits till the sum is a single digit number(1)
My program till now is:
goodvalue1=False
goodvalue2=False
while (goodvalue1==False):
try:
num=input("Please enter a number: ")
except ValueError:
print ("Wrong input. Try again.")
else:
goodvalue1=True
if (goodvalue1==True):
ListOfDigits=list(map(int,str(num)))
sum=10
while(sum>9):
Sum=sum(ListOfDigits)
if (Sum>9):
ListOfDigits=list(map(int,str(Sum)))
Sum=sum(ListOfDigits)
Those booleans are not needed. You can factor the code down to:
while True:
try:
num = int(input("Please enter a number: ")) # Note how I've added int()
break # Breaks out of the loop. No need for a boolean.
except ValueError:
print("Wrong input. Try again.")
I don't see why you called list(map(int, str(num))); but I think you were intending to put int() around your input. So I added one in above. Now it can catch an error :).
Now, to get one digit, you can use another while loop here:
while num > 9:
num = sum(map(int, str(num)))
Pretty much this creates [1, 0, 0] which sum() then calls on. This repeats until it is no longer a two digit number (or three, four, etc)
So altogether:
while True:
try:
num = int(input("Please enter a number: ")) # Note how I've added int()
break # Breaks out of the loop. No need for a boolean.
except ValueError:
print("Wrong input. Try again.")
while num > 9: # While it is a two digit number
num = sum(map(int, str(num)))
Just note that for conditional statements, it's never pythonic to do a == True or b == False.
From the PEP:
Don't compare boolean values to True or False using ==.
Yes: if greeting:
No: if greeting == True:
Worse: if greeting is True:
My take on this:
inp = None
while inp is None:
try:
inp = int(input('Enter number here: '))
except ValueError:
print('Invalid Input, try again')
summed = sum(map(int, str(inp)))
while summed > 9:
summed = sum(map(int, str(summed)))
print('The result is {}'.format(summed))
For an explanation #Haidro did a good job: https://stackoverflow.com/a/17787707/969534
You're very close. Here's what you need to change:
Sum=sum(ListOfDigits)
while(Sum>9):
Sum=sum(ListOfDigits)
if (Sum>9):
ListOfDigits=list(map(int,str(Sum)))
Sum=sum(ListOfDigits)
In this code, you have a while loop that executes when sum is bigger than 9. So why use another variable Sum (also, it makes for really difficult-to-read code)? Do this instead:
while(sum>9):
sum=sum(ListOfDigits)
ListOfDigits=list(map(int,str(sum)))
This is only to show you what went wrong with your code. I wouldn't recommend using it (look below for what I would do). First, you mix variable-naming conventions, which is a very bad idea, especially when you work in a team (even otherwise, can you imagine looking at your code a month or six months from now?).
Second, you don't ever use goodvalue2; what's it there for?
Third, if goodvalue1 is only ever going to be a bool, then why check if (goodvalue1==True)? if goodvalue1 is clearer and more pythonic.
Please, for the love of all that is good, use some spaces in your code. Eyes get very strained after looking at expressions like ListOfDigits=list(map(int,str(num))) for a while. Try ListOfDigits = list(map(int, str(num))) instead.
Personally, I would do this:
num = None
while num is None:
try:
num = int(raw_input("Enter a number: "))
except ValueError:
num = None
num = sum(int(i) for i in str(num))
while num > 9:
num = sum(int(i) for i in str(num)) # this uses a list comprehension. Look it up, they're very useful and powerful!
RECURSION !
Calculate the sum of the digits. Check if the sum has one digit or multiple digit. If one digit, that is your answer, else, call the function on the sum again.
def oneDigitSum(n):
if n < 10:
return n
else:
return oneDigitSum(sum([int(i) for i in str(n)]))
# [f(elem) for elem in li] = [f(a), f(b), .... ] where li = [a, b, ... ]
# sum returns the total of the numbers in list
while True: # continue this loop for eternity, until it gets break
try:
num=int(input("Please enter a number: "))
print(oneDigitSum(num))
break # printed the sum, now I can break the loop peace fully
except ValueError:
print ("Wrong input. Try again.")
continue # oops, looks like wrong input, lets continue the loop
Related
number = 0
number_list = []
while number != -1:
number = int(input('Enter a number'))
number_list.append(number)
else:
print(sum(number_list)/ len(number_list))
EDIT: Have found a simpler way to get the average of the list but if for example I enter '2' '3' '4' my program calculates the average to be 2 not 3. Unsure of where it's going wrong! Sorry for the confusion
Trying out your code, I did a bit of simplification and also utilized an if statement to break out of the while loop in order to give a timely average. Following is the snippet of code for your evaluation.
number_list = []
def average(mylist):
return sum(mylist)/len(mylist)
while True:
number = int(input('Enter a number: '))
if number == -1:
break
number_list.append(number)
print(average(number_list));
Some points to note.
Instead of associating the else statement with the while loop, I revised the while loop utilizing the Boolean constant "True" and then tested for the value of "-1" in order to break out of the loop.
In the average function, I renamed the list variable to "mylist" so as to not confuse anyone who might analyze the code as list is a word that has significance in Python.
Finally, the return of the average was added to the end of the function. If a return statement is not included in a function, a value of "None" will be returned by a function, which is most likely why you received the error.
Following was a test run from the terminal.
#Dev:~/Python_Programs/Average$ python3 Average.py
Enter a number: 10
Enter a number: 22
Enter a number: 40
Enter a number: -1
24.0
Give that a try and see if it meets the spirit of your project.
converts the resulting list to Type: None
No, it doesn't. You get a ValueError with int() when it cannot parse what is passed.
You can try-except that. And you can just use while True.
Also, your average function doesn't output anything, but if it did, you need to call it with a parameter, not only print the function object...
ex.
from statistics import fmean
def average(data):
return fmean(data)
number_list = []
while True:
x = input('Enter a number')
try:
val = int(x)
if val == -1:
break
number_list.append(val)
except:
break
print(average(number_list))
edit
my program calculates the average to be 2 not 3
Your calculation includes the -1 appended to the list , so you are running 8 / 4 == 2
You don't need to save all the numbers themselves, just save the sum and count.
You should check if the input is a number before trying to convert it to int
total_sum = 0
count = 0
while True:
number = input("Enter a number: ")
if number == '-1':
break
elif not number.isnumeric() and not (number[0] == "-" and number[1:].isnumeric()):
print("Please enter numbers only")
continue
total_sum += int(number)
count += 1
print(total_sum / count)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
my code not stop in line 9-10 when inserted words, I would like it to continue only when numbers are entered
from cs50 import get_int
numbers = []
while True:
number = get_int("number: ")
if not number: # here #
break # here #
if number not in numbers:
numbers.append(number)
print()
for number in numbers:
print(number)
need stopping if input not number
You can parse the input string to be a number or not in a while True loop, if it is not a number, break the loop, else keep asking.
numbers = []
while True:
#Ask for input
s = input("number: ")
number = 0
#Try to parse the string as a number, if you cannot, break the loop
try:
number = int(s)
except:
break
#If you can parse the string as a number, add it to the list
numbers.append(number)
print(numbers)
Sample outputs will be
number: 123
number: 456
number: 789
number: abc
[123, 456, 789]
In Python 3, you can use the following to ensure number is an integer (whole number):
isinstance(number, int)
If either an integer or a float (number with decimals) is allowed, you can use the following:
isinstance(number, (int, float))
I highly recommend reading more about this subject in this answer.
You don't need to define a new function to do that.
numbers = []
while True:
number = input("number: ")
try:
number = int(number)
if number not in numbers:
numbers.append(number)
except:
break
print (numbers)
try:
if number == int(number):
if number not in numbers:
numbers.append(number)
except:
#invalid input will throw you into this block
break
I'm building my first calculator. Trying to implement While loop to get a number through user input. I want the While to break once user put a number.
num1 = raw_input("Add mumber one: " )
try:
input = int(num1)
except ValueError:
print "This is not a number"
attempt = 0
while type(num1) != int and attempt < 5:
num1 = raw_input("Add Number one again: " )
attempt += 1
break
print "You are not putting number. So, goodbuy"
operation = raw_input("Add Operator: ")
Try this:
for _ in range(5):
num1 = unicode(raw_input("Add number one: "))
if num1.isnumeric():
break
Another method you can try is to have num1 and do the following in the while loop:
if type(num1) is int:
break
What this does is check the type of the variable num1. If it is an integer, int, then it breaks out of the while loop.
I want the While to break once user put a number.
You already are doing that in the condition for your while loop by having type(num) != int so your while loop should stop after the user enters an integer.
You have several errors here:
while type(num1) != int and attempt < 5:
num1 = raw_input("Add Number one again: " )
attempt += 1
break
The break statement shoud be inside the loop, but the indentation is wrong. As you write, it is after the loop (hence useless). Also, when you read from standard input, you always get a string even if it is a number. So when you check type(num1) != int this is always false. You must convert num1 with int() each time you read from standard input, not only the first time:
while True:
num1 = raw_input("Add Number one again: " )
try:
input = int(num1)
break
except ValueError:
print "This is not a number"
if attempt == 5:
break
attempt += 1
Here I try to convert to an integer the string read from stdin. If it works, I break the loop immediately. If it does not work (the except clause) I check how many attempts have been done, and break the loop if the attempts are equal to 5.
I am working on a program that requires the user to enter a number and will continue to loop until a positive number is given. When a positive number is given, it will alert the user and present them with the sum of the digits of their number. However, I thought I had written my code correctly, but it is giving me an incorrect answer. What have I done wrong and how can I fix this?
user_input = float(int(input("Please Enter Your Number:")))
s = 0
while user_input < 0:
float(int(input("Please Enter Another Number: ")))
if user_input > 0:
s += user_input%10
user_input //= 10
print("You've entered a positive number! The sum of the digits is: ", s)
Four things:
Not sure why you storing the input as float, int should suffice.
If you give a negative input, it will enter the while loop. However, in the while loop, you are not actually assigning the new input to user_input. Fix this by adding user_input =
The while loop guarantees user_input is >= 0, so if user_input > 0: is unnecessary.
Probably the most important, to calculate the sum of digits, you need to repeatedly divide and sum, not just do it once. So, add a while loop.
Final code:
user_input = int(input("Please Enter Your Number: "))
s = 0
while user_input < 0:
user_input = int(input("Please Enter Another Number: "))
while user_input:
s += user_input % 10
user_input //= 10
print("You've entered a positive number! The sum of the digits is: ", s)
The if statement is generally used to decide if something should be done once.
If you want to keep going until user_input becomes zero, you'll need a while.
Also, I'm not entirely certain why you're storing the number as a float, especially when you make that from an int anyway. It may as well just be an int.
Additionally, you're loop to re-enter the value if it was negative doesn't actually assign the new value to the variable.
And you probably also want to outdent the print statement lest it be done on every iteration of the loop you're about to add.
Of course, some may suggest a more Pythonic way of summing the digits of a positive number is a simple:
sum([int(ch) for ch in str(x)])
That works just as well, without having to worry about explicit loops.
Another way to solve this is using assert and a function:
def sum_num():
# try get user input
try:
user_in = input('Enter Number: ')
assert int(user_in) > 0
except AssertionError:
# we got invalid input
sum_num()
else:
s_d = sum([int(i) for i in user_in])
print('You\'ve entered a positive number! The sum of the digits is: ', s_d)
#run the function
sum_num()
So this will asked user input, if it is not greater than zero it will throw assertion error, which we catch and return the user to inputting the number by calling the function again. If all is well, we split the input into character and add them up. as list('12') gives ['1','2']. We convert to int and add them. :)
The awesome thing about this is you can add more too the asset to capture other issue as floats, character as invalid inputs. E.g.
Assuming literal_eval is important( from ast import literal_eval)
assert isinstance(literal_eval(user_in),int) and int(user_in)>0
Check if user_in is integer and it is greater than 0. So you won’t get issues when user inputs floats or characters.
I am new to python and I am taking a summer online class to learn python.
Unfortunately, our professor doesn't really do much. We had an assignment that wanted us to make a program (python) which asks the user for a number and it determines whether that number is even or odd. The program needs to keep asking the user for the input until the user hit zero. Well, I actually turned in a code that doesn't work and I got a 100% on my assignment. Needless to say our professor is lazy and really doesn't help much. For my own knowledge I want to know the correct way to do this!!! Here is what I have/had. I am so embarrassed because I know if probably very easy!
counter = 1
num = 1
while num != 0:
counter = counter + 1
num=int(input("Enter number:"))
while num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
There are a couple of problems with your code:
You never use counter, even though you defined it.
You have an unnecessary nested while loop. If the number the user inputs is even, then you're code will continue to run the while loop forever.
You are incorrectly using the else clause that is available with while loops. See this post for more details.
Here is the corrected code:
while True:
# Get a number from the user.
number = int(input('enter a number: '))
# If the number is zero, then break from the while loop
# so the program can end.
if number == 0:
break
# Test if the number given is even. If so, let the
# user know the number was even.
if number % 2 == 0:
print('The number', number, 'is even')
# Otherwise, we know the number is odd. Let the user know this.
else:
print('The number', number, 'is odd')
Note that I opted above to use an infinite loop, test if the user input is zero inside of the loop, and then break, rather than testing for this condition in the loop head. In my opinion this is cleaner, but both are functionally equivalent.
You already have the part that continues until the user quits with a 0 entry. Inside that loop, all you need is a simple if:
while num != 0:
num=int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
I left out the counter increment; I'm not sure why that's in the program, since you never use it.
Use input() and If its only number specific input you can use int(input()) or use an If/else statement to check
Your code wasn't indented and you need to use if condition with else and not while
counter = 1
num = 1
while num != 0:
counter = counter + 1
num = int(input("Enter number:"))
if num % 2 == 0:
print ("Even", num)
else:
print ("Odd", num)
Sample Run
Enter number:1
Odd 1
Enter number:2
Even 2
Enter number:3
Odd 3
Enter number:4
Even 4
Enter number:5
Odd 5
Enter number:6
Even 6
Enter number:0
Even 0