Python - if else - 程序流程

时间:2015-09-11 17:25:29

标签: python python-2.7

我写了一个多项选择程序,它的表现不符合我的预期。

我希望它以这种方式行事 -

  1. 当您键入1时,转到#USD和
  2. 下面的块
  3. 当您输入2时,它应该转到#Euro
  4. 下面的区块

    以下是我的代码:

    print "Welcome to Currency Converter By Fend Artz"
    print "your options are:"
    print " "
    print "1) GDP -> USD"
    print "2) GDP -> Euro"
    USD = int(raw_input(''))
    if USD == 1:
        choice = USDchoice    
    elif USD == 2:
        choice = EUROchoice
    else:
        print ("You have to put a number 1 or 2")
        int(raw_input(''))
    #USD
    def USDchoice():
        userUSD = float(input('How many pounds do you want to convert?(e.g. 5)\n'))
        USD = userUSD * 0.65
        print userUSD, "Pounds =",USD,"USDs"
    
    #Euro
    def EUROchoice():
        userEURO = float(input('How many pounds do you want to convert?(e.g. 5)\n'))
        Euro = userEURO * 1.37 
        print userEURO, "Pounds =",Euro,"Euros"
    
    #Thing so the script doesn't instantly close
    Enter = raw_input('press ENTER to close\n')
    

1 个答案:

答案 0 :(得分:1)

代码有两个问题。

  1. 您可以将变量choice设置为对您的某个功能的引用:USDChoiceEUROChoice。您需要调用这些函数,使用括号将变量设置为等于它们返回的值。正如一些评论指出的那样,您可以执行此操作,例如USDChoice()EUROChoice()
  2. 您尝试在功能创建之前调用它们。它们需要移到上面,因为一切都在全局范围内(模块级)。
  3. 固定代码:

    #USD
    def USDchoice():
        userUSD = float(input('How many pounds do you want to convert?(e.g. 5)\n'))
        USD = userUSD * 0.65
        print userUSD, "Pounds =",USD,"USDs"
    
    
    #Euro
    def EUROchoice():
        userEURO = float(input('How many pounds do you want to convert?(e.g. 5)\n'))
        Euro = userEURO * 1.37 
        print userEURO, "Pounds =",Euro,"Euros"
    
    
    print "Welcome to Currency Converter By Fend Artz"
    print "your options are:"
    print " "
    print "1) GDP -> USD"
    print "2) GDP -> Euro"
    USD = int(raw_input(''))
    
    if USD == 1:
        choice = USDchoice()
    elif USD == 2:
        choice = EUROchoice()
    else:
        print ("You have to put a number 1 or 2")
        int(raw_input(''))
    
    #Thing so the script doesn't instantly close
    Enter = raw_input('press ENTER to close\n')