Python 3.6.4简易计算器开发遇NameError问题求助
Hey there! Let's figure out why you're hitting that NameError with z when using subtraction, multiplication, or division.
First, the root cause is incorrect indentation in your code. Right now, your if z in [2], if z in [3], etc. blocks are sitting outside the if b in ["Add", "add"] block. That means when you choose any operation other than addition, the program still tries to run those z checks—but z is only defined when you select "Add"! That's exactly why you're seeing name 'z' is not defined.
Let's fix that, plus clean up the code to make it more scalable (writing a separate block for every number count from 2-10 gets really repetitive fast). Here's the step-by-step solution:
1. Fix the Indentation
Move all addition-specific z checks inside the if b in ["Add", "add"] block. This way, they only run when the user selects addition, and z will always be defined in that context.
2. Simplify Number Input with Loops
Instead of writing unique code for 2, 3, ..., 10 numbers, use a loop to collect input. This makes the code shorter and easier to maintain.
3. Minor Cleanups
- Remove the unnecessary
+in print statements (likeprint("The result is", + c + d)—the+beforecdoes nothing here). - Add input validation to handle invalid number entries and division by zero.
- Use case-insensitive checks so users can type "Add", "ADD", etc., and it still works.
Revised Code
print("Welcome to this simple calculator") # Yes/No prompt a = input("Would you like to use this simple calculator?(Yes/No):") print(f"{a} confirmed") if a.lower() == "no": print("Come back next time!!") raise SystemExit if a.lower() == "yes": operation = input("Would you like to add, subtract, multiply, or divide?").lower() # Addition: handle 2-10 numbers if operation == "add": # Validate number count input while True: try: num_count = int(input("How many numbers would you like to add?(2-10):")) if 2 <= num_count <= 10: break print("Please enter a number between 2 and 10.") except ValueError: print("That's not a valid number. Try again.") total = 0.0 for i in range(num_count): num = float(input(f"Enter number {i+1} to add:")) total += num print(f"The result is {total}") print("Come back next time!!") # Subtraction (easily extendable to more numbers) elif operation == "subtract": num1 = float(input("Enter the first number:")) num2 = float(input("Enter the number to subtract from the first:")) result = num1 - num2 print(f"The result is {result}") print("Come back next time!!") # Multiplication (extendable to more numbers) elif operation == "multiply": num1 = float(input("Enter the first number:")) num2 = float(input("Enter the second number to multiply:")) result = num1 * num2 print(f"The result is {result}") print("Come back next time!!") # Division with zero-check elif operation == "divide": while True: num1 = float(input("Enter the dividend:")) num2 = float(input("Enter the divisor:")) if num2 == 0: print("Error: Cannot divide by zero. Enter a different divisor.") else: result = num1 / num2 print(f"The result is {result}") print("Come back next time!!") break else: print("Invalid operation. Please choose add, subtract, multiply, or divide.")
Key Improvements
- No more undefined variables: All addition-specific logic lives inside its own block, so
z(nownum_count) is only referenced when it's guaranteed to exist. - Scalable addition: The loop handles any number between 2-10 without repetitive code.
- Robust input handling: The code catches invalid number entries and prevents division by zero crashes.
- Readable formatting: F-strings make string concatenation cleaner and easier to read.
If you want to extend subtraction/multiplication/division to support more than 2 numbers later, you can reuse the loop pattern from the addition section. For example, subtraction could start with the first number and subtract all subsequent inputs, or multiplication could multiply all collected numbers together.
Great job for only 3 days with Python—keep experimenting! 😊
内容的提问来源于stack exchange,提问作者Narek Germirlian




