为何Python代码中pas1()函数被执行两次?求单次执行方案
pas1() Runs Twice and How to Fix It Let's break down why your code is prompting you twice, and walk through the fixes step by step.
The Root Cause
The most likely reason pas1() executes twice is unintended code running during module import:
- If your
nnk.pymodule has a direct call topassword.pas1()at the top level (outside of any function or class), Python will run that code the second youimport nnk. - Then, when you run
me=nnk.password.pas1()in your main script, you’re calling the function a second time—hence the double prompts for input.
A secondary (non-breaking but unidiomatic) issue: your pas1() method doesn’t follow Python’s class method rules. It lacks either a self parameter (for instance methods) or the @staticmethod decorator (for static methods). While it works now, this could cause confusion or errors later.
Fixes to Implement
1. Remove Top-Level Calls in nnk.py
First, open your nnk.py file and delete any line like this that’s outside the password class:
password.pas1() # This line causes the first execution on import!
Modules should only hold definitions (classes, functions, variables) unless you specifically want code to run when the module is imported.
2. Fix the pas1() Method Definition
Update your class to follow Python conventions, and add a return value so you can actually use the inputted data later:
class Password: # Use PascalCase for class names (PEP8 best practice) @staticmethod def pas1(): pas = [] tedad = int(input('how many entries do you have? ')) # Note: range(1, tedad) would loop tedad-1 times—use range(tedad) to match the user's input count for _ in range(tedad): entry = input('enter your entry: ') pas.append(entry) print('your entries are ---> {}' . format(pas)) return pas # Return the list so you can assign it to 'me'
3. Call the Method Correctly in Your Main Script
Now when you import and run the method, it will only execute once:
import nnk me = nnk.Password.pas1() # Now 'me' stores the list of entries you inputted
Quick Side Note: Fixing the Loop Count
Your original range(1, tedad) would loop one fewer time than the user specifies. For example, if someone enters 3, it would only prompt twice. Using range(tedad) fixes this to match the number of entries the user expects.
内容的提问来源于stack exchange,提问作者magic man

