[英]How to use a variable as value of replace function in python pandas
[英]How to replace value of variable within function in python 3
我是python的新手,我可能會使這個問題復雜化。 我在函數中的值沒有被替換時遇到問題。 相反,它似乎只是為它添加新值。 使用此功能,如果您選擇1或2,則應該執行某些操作,如果您選擇其他任何操作,則應該說這不是一個選項並讓您再試一次。 如果在選擇有效選項之前選擇了錯誤的選項,則輸出如下:
Select Option
[1] Option 1
[2] Option 2
You selected Option 1
1
9
7
6
因此,不是將我的變量的值替換為1並清除以前的值,它似乎只是添加它。 這是我的代碼:
def testfunc():
testvar = input('Select Option\n\n[1] Option 1\n[2] Option 2\n\n >')
if testvar in ('1', 'Option 1', 'option 1'):
print("\nYou selected Option 1")
elif testvar in ('2', 'Option 2', 'option 2'):
print("\nYou Selected Option 2")
else:
print("\n\nThat is not an option, please select another option")
testfunc()
print(testvar)
testfunc()
如果我可以讓某人解釋為什么它存儲多個值以及我如何防止這種情況,我會非常感激。 謝謝!
你的問題是,你使用遞歸回去再弄值(調用testfunc()
內testfunc()
本身)。
如果輸入無效值,它將再次調用該函數,保存其當前位置( print
前),以便它可以返回到那里。
然后,當你最終輸入一個好的值時,它最終將展開堆棧,打印出無效的堆棧。
你最好使用循環進行這種驗證,例如:
def testfunc():
ok = False
while not ok:
testvar = input('Select Option\n\n[1] Option 1\n[2] Option 2\n\n >')
if testvar in ('1', 'Option 1', 'option 1'):
print("\nYou selected Option 1")
ok = True
elif testvar in ('2', 'Option 2', 'option 2'):
print("\nYou Selected Option 2")
ok = True
else:
print("\n\nThat is not an option, please select another option")
print(testvar)
testfunc()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.