0

How to loop back to the right line?

I am so new to coding, and here is my question: 1) I am writing this interactive calculator code, basically the user has to input two numbers. so, if the user fail to input the first number(for example, maybe user input alphabet not numbers ), it will loop back and ask for the first number, and if the user fail to input the second number, I want it to loop back and ask the second number again, but my code always loop back to ask the first number... any ideas? (2018 09 27 edited) first_time = True while True: if first_time == True: print("Here are your options:" + "\n") print("Enter one of those functions to continue:") print("(add, subtract, multiply, divide, quit)") first_time = False user_input = input("Enter your option here: " + "\n") if user_input == "quit": break elif user_input == "add": # while user_input == "add": while True: num1 = (input("Enter a number: ")) if not (num1.isalpha()): break else: print ("(number only...)") continue while True: num2 = (input("Enter the second number: ")) if (num2.isalpha()): print ("(number only, please...)") continue else: result = float(num1) + float(num2) print("The answer is " + "\n>>> " + str(result)) print() break

16th Aug 2018, 4:40 PM
Vosen Chen
Vosen Chen - avatar
6 Answers
+ 1
If you want to go with while-loops only, I would make a separate one for every number. while True: x=input() if x == whatever: break while True: y =input()...
16th Aug 2018, 10:39 PM
HonFu
HonFu - avatar
+ 1
Is the above version the recent one?
27th Sep 2018, 9:26 AM
HonFu
HonFu - avatar
+ 1
You want to start the code with printing out the instructions, but only once. Instead of using a flag variable, I would just pull the line "while True" down to the point from where you actually want to loop. Then for the number testing I would probably write my own little function, for example: def getNum(): while True: n = input() if n.isdigit(): return int(n) Then, in your main code you can just write: num1 = getNum() num2 = getNum() If you want to accept floats, maybe it's easiest to do it with "try" (after the input in the function): try: n = float(n) return n except: continue Oh, and I'd recommend you upload your code here and link it in your question so that people can go there, hit run and potentially upvote. ;-)
27th Sep 2018, 9:35 AM
HonFu
HonFu - avatar
+ 1
Got it! Thank you! Yeah, I should've upload my code so people can just hit run easily... Thank you :)
27th Sep 2018, 1:40 PM
Vosen Chen
Vosen Chen - avatar
0
HonFu thanks for your feedback! do you have a better suggestion to write this code?
27th Sep 2018, 9:25 AM
Vosen Chen
Vosen Chen - avatar
0
@HonFu, Yes, I updated it, now it runs as expected from your suggestion. I hope I can make it better it looks quite off :(
27th Sep 2018, 9:30 AM
Vosen Chen
Vosen Chen - avatar