python checking user input for number in a while loop - python

I have a function below which is part of my big main function, what I want this function to do is that whenever called, I want the function to check if the user input is
a number or not. If it is a number it will return the number and break.
But if it is not a number I want it to loop again and again.when I try to
run it, it gives me unexpected an error:
unexpected eof while parsing
can any body help me what I am missing or how I should rearrange my code? thank you!
def getnumber():
keepgoing==True
while keepgoing:
number = input("input number: ")
result1 = number.isdigit()
if result1 == 1:
return number
break
elif keepgoing==True:

A neater and clearer what to do what you are already doing:
def getnumber():
while True:
number = input("Input number: ")
if number.isdigit():
return number
That's all you need, the extra variables are superfluous and the elif at the end makes no sense. You don't need to check booleans with == True or == 1, you just do if condition:. And nothing happens after return, your break will never be reached.

You don't need the last line:
elif keepgoing==True:
It's waiting for the rest of the file after the :.
Side note, it should be a single = in the first part, and can just be written simpler as well.
def getnumber():
while True:
number = input("input number: ")
result1 = number.isdigit()
if result1:
return number
Since you're inside the while loop, it'll keep executing. Using return will end the while loop, as will breaking and exiting the program. It will wait for input as well each time, though.

While assigning you have used keepgoing == True, I think it should be keepgoing=True

The following solution works on my machine, although I am running Python 2.7
def get_num():
while True: #Loop forever
number_str = raw_input("> Input a number: ") #Get the user input
if number_str.isdigit(): #They entered a number!
return int(number_str) #Cast the string to an integer and return it
I used raw_input rather than input, because raw_input gives you the exact string the user entered, rather than trying to evaluate the text, like input does. (If you pass the 12 to input, you'll get the number 12, but if you pass "12", you'll get the string '12'. And, if you pass my_var, you'll get whatever value was in my_var).
Anyway, you should also know that isdigit() returns whether or not the string has only digits in it and at least one character - that is not the same thing as isNumber(). For instance, "123".isdigit() is True, but "123.0".isdigit() is False. I also simplified your loop logic a bit.

Related

How to make an integer in a "while true" loop stop when I write a string?

I'm trying to make a calculator that asks the user for input until the user writes a string like "stop", then the user has to write an input operation (+,-,etc..).
My main problem is how do I make a user write a string inside an integer input and how do I make another input after the brake?
I have managed to create an infinite loop, how do I replace "i = 0" with "i = "stop"?
If user writes a string it will result in error.
i = 0
while True:
user_input = int("Enter a number: ")
if user_input = i:
break
Unless you need them to write "stop" for a specific reason, you can do something like :
i = 0
while True:
print ("Enter a number", end="")
x = input()
x = int(x)
# use x as your input number in your calculator.
This way, the act of user pressing enter key works as your "stop" check. So the user can input a number. When they press enter, the input is stored in x as string. Then the code converts it into an int.
To parse the keyword stop, you can do
x = input()
x = int(x.split("stop")[0].strip())
This basically looks for the word "stop" and splits the string from that point. The 0th index should contain the number (assuming the user enters the numbers first followed by "stop"). The .strip() removes white spaces. Finally, we convert this string (that has numbers in it, and no whitespaces) to int.
Your code was running indefinitely because of the "=". When it hits that line, it overrides the current value of user_input with 0, which a conditional statement reads as false, so the 'break' statement will never be reached.
First you must use double "==" instead of one "=" when comparing. You also should check before converting to an int:
i = "stop"
while True:
print("Enter a number: ")
user_input = input()
if user_input == i:
break
else:
intInput = int(user_input) #assuming you are checking for int inputs and properly handling type errors
# you can now use intInput
Of course, you can remove "i" and just directly check "if user_input == "stop":" if you'd like

How to evaluate user's input in s loop?

I'm new in coding or programming so I hope for respect.
How can I create a program that continually accepts input from the user. The input shall be in this format operatornumber like -3
Like
num = 0
while((a := input("Enter operatornumber like -9;")) != "-0"):
if (len(a) >= 2) and (a[0] in "/*-+"):
num = eval(f"{num}{a}")
else:
print("Invalid input, try again.")
print(num)
But how can I make the first input of the user to only use the add (+) or subtract(-) operators but in the next input they can now use the other operators.
Like
Enter operatornumber like -9; +9
Enter operatornumber like -9; -8
Enter operatornumber like -9; -0
1
And how can I combine all the input like
+9-9 is 1?
In the input statement, you're closing the "Enter operator and number like" msg. This is creating more problems after that line, where all green parts are considered as string now. Also, in while statement, "w" should be small letter, python is case sensitive. Try doing this:
Number = input("Enter operator and number like '-9' ")
Operator = ("+","-","/")
while Number == (Operator + Number):
if Number == "-0":
Total = 0
Total += Number
print(f"the result of {num} is {total} ")
You can use double quotes for the text and single quotes for the number, so they don't close each other.
You can get input forever using following code:
while True:
Number = input("Enter operator and number like '-9'")
# Place your next code here.
Here is another answer. We have to take input from user with operator as well, so len(<user_input<) should be >=2. Now, we'll take another variable h in which we'll traverse the string from index 1 to end, which means the operator gets removed and we'll convert it into int. Then we'll put if condition in which we'll check the user_input[0] is +,-,*,/ and then acc to that, we'll update the result. We'll ask the user whether he wants more operations or no, if y, then keep asking, else, break the while loop. Here's my code:
result=0
while True:
a=input("Enter operator and number= ")
if len(a)>=2 and a[0] in ["+","-","*","/"]:
h=int(a[1::])
if a[0]=="+":
result+=h
elif a[0]=="-":
result-=h
elif a[0]=="*":
result*=h
elif a[0]=="/":
result/=h
else:
print("choose only from +-/*")
else:
print("invalid input")
ch=input("Enter more?")
if ch=='n':
break
print(f"The result is {result}")
Check for indentation errors because I've copied and pasted it so it may have indentation errors

How to Go Back to an Original Prompt in Python

I am trying to create a basic calculator that takes the first number, takes the operation(+,-,*,/), and second number. If a person puts in a zero for the first number and/or the second number my program is supposed to go back to the number it was at and ask again for a number other than 0. So if a person puts in 0 for number 2 then my program will take the person back to number two. I am also supposed to do the same concept for the operation but have the person start over if they do not put in the operation available to use which includes the ones previously shown in parentheses. Below is the code I have so far. Any help would be appreciated. My class is currently on while loops and breaks among other things, but I am wondering if those two would be beneficial in my code.
#Programming Fundamentals Assignment Unit 5
#Create a basic calculator function
while True:
#Num1 will require user input
num1 = input ("Enter the first number\n")
#Operation will require user input
operation = raw_input("Enter the operation(+,-,*,/)\n")
#Num2 will require user input
num2 = input("Enter the second number\n")
#Now to define how the operation will be used
if operation == "+":
print num1+num2
elif operation == "-":
print num1-num2
elif operation == "*":
print num1*num2
elif operation == "/":
print num1/num2
else:
print "Please enter an operation"
#Exit will end the calculation from going into a loop
exit()
Put loops around your various inputs to ensure proper checking. So for the first number, you could have:
num1 = 0
while num1 == 0:
num1 = input ("Enter the first number\n")
This'll keep asking till they input something that isn't a 0.
For the second issue (starting over if they enter an invalid operation), you want to immediately check if the operation is valid and if it isn't, then you need to re-loop (which is just by skipping the remaining parts of the current loop).
So to easily check if it's valid:
operation not in ["+","-","*","/"]
which will return false if they enter invalid, and then the second part (skipping the rest of the loop) can easily be accomplished with the "continue" keyword.
if operation not in ["+","-","*","/"]:
continue
This will take you back to the beginning of the loop, asking for new number first number.
When you want to stop execution, you'll need to implement "break" which will break out of the inner most loop that it's a part of.

breaking out of the loop?

I'm having some trouble with breaking out of these loops:
done = False
while not done:
while True:
print("Hello driver. You are travelling at 100km/h. Please enter the current time:")
starttime = input("")
try:
stime = int(starttime)
break
except ValueError:
print("Please enter a number!")
x = len(starttime)
while True:
if x < 4:
print("Your input time is smaller than 4-digits. Please enter a proper time.")
break
if x > 4:
print("Your input time is greater than 4-digits. Please enter a proper time.")
break
else:
break
It recognizes whether the number is < 4 or > 4 but even when the number inputted is 4-digits long it returns to the start of the program rather than continues to the next segment of code, which isn't here.
You obviously want to use the variable done as a flag. So you have to set it just before your last break (when you are done).
...
else:
done = 1
break
The reason it "returns to the beginning of the program" is because you've nested while loops inside a while loop. The break statement is very simple: it ends the (for or while) loop the program is currently executing. This has no bearing on anything outside the scope of that specific loop. Calling break inside your nested loop will inevitably end up at the same point.
If what you want is to end all execution within any particular block of code, regardless of how deeply you're nested (and what you're encountering is a symptom of the issues with deeply-nested code), you should move that code into a separate function. At that point you can use return to end the entire method.
Here's an example:
def breakNestedWhile():
while (True):
while (True):
print("This only prints once.")
return
All of this is secondary to the fact that there's no real reason for you to be doing things the way you are above - it's almost never a good idea to nest while loops, you have two while loops with the same condition, which seems pointless, and you've got a boolean flag, done, which you never bother to use. If you'd actually set done to True in your nested whiles, the parent while loop won't execute after you break.
input() can take an optional prompt string. I've tried to clean up the flow a bit here, I hope it's helpful as a reference.
x = 0
print("Hello driver. You are travelling at 100km/h.")
while x != 4:
starttime = input("Please enter the current time: ")
try:
stime = int(starttime)
x = len(starttime)
if x != 4:
print("You input ({}) digits, 4-digits are required. Please enter a proper time.".format(x))
except ValueError:
print("Please enter a number!")

How do I improve my code for Think Python, Exercise 7.4 eval and loop

The task:
Write a function called eval_loop that iteratively prompts the user, takes the resulting input and evaluates it using eval(), and prints the result.
It should continue until the user enters 'done', and then return the value of the last expression it evaluated.
My code:
import math
def eval_loop(m,n,i):
n = raw_input('I am the calculator and please type: ')
m = raw_input('enter done if you would like to quit! ')
i = 0
while (m!='done' and i>=0):
print eval(n)
eval_loop(m,n,i)
i += 1
break;
eval_loop('','1+2',0)
My code cannot return the value of the last expression it evaluated!
Three comments:
Using recursion for this means that you will eventually hit the system recursion limit, iteration is probably a better approach (and the one you were asked to take!);
If you want to return the result of eval, you will need to assign it; and
I have no idea what i is for in your code, but it doesn't seem to be helping anything.
With those in mind, a brief outline:
def eval_loop():
result = None
while True:
ui = raw_input("Enter a command (or 'done' to quit): ")
if ui.lower() == "done":
break
result = eval(ui)
print result
return result
For a more robust function, consider wrapping eval in a try and dealing with any errors stemming from it sensibly.
import math
def eval_loop():
while True:
x=input('Enter the expression to evaluate: ')
if x=='done':
break
else:
y=eval(x)
print(y)
print(y)
eval_loop()
This is the code I came up with. As a start wrote it using the If,else conditionals to understand the flow of code. Then wrote it using the while loop
import math
#using the eval function
"""eval("") takes a string as a variable and evaluates it
Using (If,else) Conditionals"""
def eval_(n):
m=int(n)
print("\nInput n = ",m)
x=eval('\nmath.pow(m,2)')
print("\nEvaluated value is = ", x)
def run():
n= input("\nEnter the value of n = ")
if n=='done' or n=='Done':
print("\nexiting program")
return
else:
eval_(n)
run() # recalling the function to create a loop
run()
Now Performing the same using a While Loop
"using eval("") function using while loop"
def eval_1():
while True:
n=input("\nenter the value of n = ") #takes a str as input
if n=="done" or n=="Done": #using string to break the loop
break
m=int(n) # Since we're using eval to peform a math function.
print("\n\nInput n = ",m)
x=eval('\nmath.pow(m,2)') #Using m to perform the math
print("\nEvaluated value is " ,x)
eval_1()
This method will run the eval on what a user input first, then adds that input to a new variable called b.
When the word "done" is input by the user, then it will print the newly created variable b - exactly as requested by the exercise.
def eval_loop():
while True:
a = input("enter a:\n")
if a == "done":
print(eval(b)) # if "done" is entered, this line will print variable "b" (see comment below)
break
print(eval(a))
b = a # this adds the last evaluated to a new variable "b"
eval_loop()
import math
b = []
def eval_loop():
a = input('Enter something to eval:')
if a != 'done':
print(eval(a))
b.append(eval(a))
eval_loop()
elif a == 'done':
print(*b)
eval_loop()

Categories