I always had stumbled on this topic, but, well, yeah.

I want to learn how to combine if statements. I made a thread like this long ago, but I don't want to necropost.

So, As an example, what exactly would I do if I had something like this?

def add_n():
    n = int(raw_input('> '))
    print n + 5
if a == 1:
    print 'string'
elif a == 2:
    n = int(raw_input('> '))
    print n + 5
else:
    add_n()

(I know this is unreliable to convert because of its shortness, but I'd rather keep it simple.)

Where is a comming? Also value of n is lost after exit from function at line 3, better to do:

a=int(raw_input('a: '))
if a == 1:
    print 'string'
else:
    print 5+int(raw_input('> '))

And that simpler:

print  'string' if int(raw_input('a: ')) == 1 else 5+int(raw_input('> '))

Edited 5 Years Ago by pyTony: n/a

As you can see, LogicallyInsane, the question you're asking isn't very clear as the answers were focused on the example rather than the actual meaning behind it. What is it you are trying to accomplish? Just how are you trying to 'combine' if: statements? Do you mean, how do you write nest if:s? Or do you mean, how do you combine two or more conditionals into one? Or (as Tonyjv interpreted it), how do you simplify if:/elsif:/else: combinations when two or more of them are redundant? What you want isn't entirely clear.

Edited 5 Years Ago by Schol-R-LEA: n/a

I'm copying this from my old thread, but, I want the example in this style:

import math
import sys
if 3 > sys.version_info[0]:
  input = raw_input

lookup = {
  '1': ('Sine',math.sin),
  'sin': ('Sine',math.sin),
  '2': ('Cosine',math.cos),
  'cos': ('Cosine',math.cos),
  '3': ('Tangent',math.tan),
  'tan': ('Tangent',math.tan),
  }
  
a = input("Enter 1 or sin, 2 or cos, 3 or tan: ").lower()[:3]
funcPair = lookup.get(a)
if not funcPair:
  print("'%s' is not a legal function choice"%a)
  sys.exit(1)
funcName, func = funcPair
try:
  arg = int(input("Enter number of degrees for function %s: "%funcName))
  val = func(math.radians(arg))
  print("%s of %s is %s"%(funcName,arg,val))
except:
  print("Sorry, we can only calculate for integer degrees")
  sys.exit(1)

That is a fairly standard menu. An example only partially completed and tested.

import math
import sys

def get_number(func_name):
    try:
        arg = int(input("Enter number of degrees for function %s: " % func_name))
        return arg
    except:
        print("Sorry, we can only calculate for integer degrees")
        sys.exit(1)

def sin_funct():
    name = "Sine"
    val = get_number(name)
    print("%s of %d is %f" % (name, val, math.sin(math.radians(float(val)))))

def cos_funct():
    name = "Cosine"
    val = get_number(name)
    print("%s of %d is %f" % (name, val, math.cos(math.radians(float(val)))))

def tan_funct():
    print "tan_funct called"


lookup = {
  '1': "sin_funct()",
  'sin': "sin_funct()",
  '2': "cos_funct()",
  'cos': "cos_funct()",
  '3': "tan_funct()",
  'tan': "tan_funct()" 
  }
 
a = raw_input("Enter 1 or sin, 2 or cos, 3 or tan: ").lower()[:3]
if a in lookup:
    eval(lookup[a])

Edited 5 Years Ago by woooee: n/a

Happy Christmas!

My go of simplified version of math functions with prompting:

""" Do single parameter math calculations with prompting
optionally converting degrees to radians"""

import math
try:
    input = raw_input
    # Python 2, input is replaced by raw_input like in Python 3
except:
    # no raw_input -> Python 3, input has correct definition -> do nothing
    pass

lookup = dict((func,math.__dict__[func])
              for func in math.__dict__
              # let's take out special __ starting functions
              if not func.startswith('__'))

while True:
    a = input("""
Enter function or
empty input to quit
? for list of functions:
""").lower()
    try:
        func = lookup[a]
    except KeyError:
        if not a:
            break
        elif a == '?':
            print('Available functions are:\n\t'+'\n\t'.join(lookup)+'\n')
        else:        
            print("%r is not a legal function choice!" % a)
    else:
        print('\n%s\n' % func.__doc__)
        try:
            arg= input('Give parameter for %s: ' % a)
            arg = float(arg) if '.' in arg else int(arg)
            arg = arg if input('Convert degrees to radians (Y/n)?').lower().startswith('n') else math.radians(arg)
            print (func(arg))
        except ValueError as e:
            print(e)

TODO:
Coping with variable parameter counts.

Edited 5 Years Ago by pyTony: n/a

>:I

Alright, I just want to see how

def add_n():
    n = int(raw_input('> '))
    print n + 5
if a == 1:
    print 'string'
elif a == 2:
    n = int(raw_input('> '))
    print n + 5
else:
    add_n()

would look if I changed it to this style

import math
import sys
if 3 > sys.version_info[0]:
  input = raw_input

lookup = {
  '1': ('Sine',math.sin),
  'sin': ('Sine',math.sin),
  '2': ('Cosine',math.cos),
  'cos': ('Cosine',math.cos),
  '3': ('Tangent',math.tan),
  'tan': ('Tangent',math.tan),
  }
  
a = input("Enter 1 or sin, 2 or cos, 3 or tan: ").lower()[:3]
funcPair = lookup.get(a)
if not funcPair:
  print("'%s' is not a legal function choice"%a)
  sys.exit(1)
funcName, func = funcPair
try:
  arg = int(input("Enter number of degrees for function %s: "%funcName))
  val = func(math.radians(arg))
  print("%s of %s is %s"%(funcName,arg,val))
except:
  print("Sorry, we can only calculate for integer degrees")
  sys.exit(1)

not that I want you to further simplify into it.

If I interpret your problem, you have problem of understanding how to replace switch statement with dictionary.

try:
    input = raw_input
except:
    pass


def add_n():
    n = int(input('> '))
    print n + 5

def one():
    print 'string'

def two():
    n = int(input('> '))
    print n + 5

def default():
    print 'Not defined value, doing default action'
    add_n()


switch = {1:one, 2:two}

a=True
while a:
    a = int(input('Enter the switch value, 0 to finish: '))
    if a: switch.get(a, default)()

Edited 5 Years Ago by pyTony: n/a

This article has been dead for over six months. Start a new discussion instead.