2014-09-05 16 views
-2

如何在這種情況下使用函數。這些選項的功能(Python)

我想要做的是當

1,將允許用戶輸入一個數字,以節省

2,將允許用戶以減少保存的號碼

3-將使用戶查看儲存數

這是我當前的代碼:輸入

print '1. Add \n2. Remove \n3. View' 

x = raw_input('ur choice:') 

'1' 時:

if x == '1': 
    print 'you have:' 
    add = raw_input('how many do you want to add:') 
    print '1. Add \n2. Remove \n3. View' 

如果 '2' 進入:

if x == '2': 
    print 'you have:' 
    remove = raw_input ('How many do you want to remove:') 

    print '1. Add \n2. Remove \n3. View' 

和如果輸入3:

if x == '3': 
    print 'Total:' 
+0

什麼是你想通過把這個代碼到功能實現,你的避風港如果它已經有效,請說明問題。 – W1ll1amvl 2014-09-05 19:47:57

回答

0

我不知道你到底是什麼期望,但至少你可以在代碼轉移到功能:

def add: 
    print 'you have:' 
    add = raw_input('how many do you want to add:') 
    prompt() 

def remove: 
    print 'you have:' 
    remove = raw_input ('How many do you want to remove:') 
    prompt() 

def total: 
    print 'Total:' 

def prompt: 
    print '1. Add \n2. Remove \n3. View' 

x = raw_input('ur choice:') 
if x == '1': 
    add() 
elif x == '2': 
    remove() 
else: 
    total() 
+3

考慮將函數放在字典中去除​​'if:elif:'。 – jonrsharpe 2014-09-05 11:19:47

+0

我想要做的是當1 - 將允許用戶輸入一個數字來保存2 - 將允許用戶刪除或減少保存的數字3將使用戶查看保存的數字 – 2014-09-05 12:17:13