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.
Related
I am going through book automate boring stuff with python and trying to solve the practical problems.
In this project I need to define collatz() function and print results as seen in code until it gets 1.
So basically i need to input only one number and program should return numbers until it returns 1.
Program works fine but i have one question if i can make it better :D .
My question is after using try: and except: is there a way to not end process when typing string in input function but to get message below 'You must enter number' and get back to inputing new number or string and executing while loop normally. Code works fine just wondering if this is possible and if so how?
def collatz(number):
if number % 2 == 0:
print(number // 2)
return number // 2
else:
print(3 * number + 1)
return 3 * number + 1
try:
yourNumber = int(input('Enter number: '))
while True:
yourNumber = collatz(yourNumber)
if yourNumber == 1:
break
except ValueError:
print('You must enter a number')
Put the try/except inside a loop, such that on the except the loop will continue but on a success it will break:
while True:
try:
yourNumber = int(input('Enter number: '))
except ValueError:
print('You must enter a number')
else:
break
while yourNumber != 1:
yourNumber = collatz(yourNumber)
I'm new to python and I'm trying to help out a friend with her code. The code receives input from a user until the input is 0, using a while loop. I'm not used to the python syntax, so I'm a little confused as to how to receive user input. I don't know what I'm doing wrong. Here's my code:
sum = 0
number = input()
while number != 0:
number = input()
sum += number
if number == 0:
break
In your example, both while number != 0: and if number == 0: break are controlling when to exit the loop. To avoid repeating yourself, you can just replace the first condition with while True and only keep the break.
Also, you're adding, so it is a good idea to turn the read input (which is a character string) into a number with something like int(input()).
Finally, using a variable name like sum is a bad idea, since this 'shadows' the built-in name sum.
Taking all that together, here's an alternative:
total = 0
while True:
number = int(input())
total += number
if number == 0:
break
print(total)
No need last if, and also make inputs int typed:
sum = 0
number = int(input())
while number != 0:
number = int(input())
sum += number
You can actually do:
number=1
while number!=0:
number = int(input())
# Declare list for all inputs
input_list = []
# start the loop
while True:
# prompt user input
user_input = int(input("Input an element: "))
# print user input
print("Your current input is: ", user_input)
# if user input not equal to 0
if user_input != 0:
# append user input into the list
input_list.append(user_input)
# else stop the loop
else:
break
# sum up all the inputs in the list and print the result out
input_sum = sum(input_list)
print ("The sum is: ", input_sum)
Or
If you don't want to use list.
input_list = 0
while True:
user_input = int(input("Input an element: "))
print("Your current input is: ", user_input)
if user_input != 0:
input_list += user_input
else:
break
print ("The sum is: ", input_list)
Note:
raw_input('Text here') # Python 2.x
input('Text here') # Python 3.x
If I'm asking for a user input of numbers which continues as long as an empty string is not entered, if an empty string is entered then the program ends.
My current code is:
n=0
while n != "":
n = int(input("Enter a number: "))
But obviously this isn't exactly what I want. I could remove the int input and leave it as a regular input, but this will allow all types of inputs and i just want numbers.
Do i ago about this a different way?
calling int() on an empty string will cause a ValueError so you can encapsulate everything in a try block:
>>> while True:
try:
n = int(input('NUMBER: '))
except ValueError:
print('Not an integer.')
break
NUMBER: 5
NUMBER: 12
NUMBER: 64
NUMBER:
not a number.
this also has the added benefit of catching anything ELSE that isn't an int.
I would suggest using a try/except here instead.
Also, with using a try/except, you can instead change your loop to using a while True. Then you can use break once an invalid input is found.
Also, your solution is not outputting anything either, so you might want to set up a print statement after you get the input.
Here is an example of how you can put all that together and test that an integer is entered only:
while True:
try:
n = int(input("Enter a number: "))
print(n)
except ValueError:
print("You did not enter a number")
break
If you want to go a step further, and handle numbers with decimals as well, you can try to cast to float instead:
while True:
try:
n = float(input("Enter a number: "))
print(n)
except ValueError:
print("You did not enter a number")
break
I have a program with some user inputs and I need to check if what the user entered was a string or an integer value between 1 and 10 million.
My code looks like this (simplified):
while True:
inp = raw_input("Enter a value between 1 and 10 million: ")
if inp < 1:
print "Must be higher than 1"
continue
elif inp > 10.000.000:
print "Must be less than 10.000.000"
continue
elif 'inp is a string': #here's my problem
print "Must be an integer value!"
continue
else:
'execute the rest of the code'
I don't know how to solve this. My program always terminates when I enter a string by mistake.
Thank you!
First, you're using Python 2, which will happily compare strings to integers. You don't want to do that. Secondly, raw_input() will always return a string. What you're hoping to do is check if that string could possibly represent a number. Third, 10.000.000 is improper syntax. Don't use separators. Fourth, you only need to continue if you want to go to the top of the loop early. If everything's in an if..elif..else block at the end of the loop, only one of those will be executed, so you don't need to put a continue at the end of each branch. You can use continue statements or restructure your branch. Finally, don't use in as a variable name, because that's a Python keyword.
while True:
inp = raw_input("Enter a value between 1 and 10 million: ")
if not inp.isdigit():
print "Must be an integer value!"
continue # each of these continue statements acts like a "failed, try again"
inp = int(inp)
if inp < 1:
print "Must be higher than 1"
continue # same for this one
if inp > 10000000:
print "Must be less than 10.000.000"
continue # and this one
# execute the rest of the code
You can use .isdigit() to check if string consists of numbers to make sure it can be convertible to integer:
while True:
in = raw_input("Enter a value between 1 and 10 million: ")
if in.isdigit():
number = int(in)
if number < 1:
print "Must be higher than 1"
continue
elif number > 10**6:
print "Must be less than 10.000.000"
continue
else:
'execute the rest of the code'
else:
print "Must be an integer value!"
continue
I have no idea how you came up with your code but here are different suggestions:
Don't use "in" as variable name because it's a python operator.
After the input you can check whether it is an int or a string.
Your program can look like this:
while True:
try:
input_int = int(raw_input("Enter a value between 1 and 10 million: "))
if input_int < 1 :
print "Must be higher than 1"
elif input_int > 10**7:
print "Must be less than 10.000.000"
except:
print "Must be an integer value!"
else: #You can use else with try/except block
#'execute the rest of the code'
VoilĂ
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