Code Point
September 10, 2010, 07:21:51 AM *
Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
News: Geshi Sintax Hilighting Mod Installed. Tens of languages available.
 
   Home   Help Search Login Register  
Pages: [1]   Go Down
  Print  
Author Topic: Too long If...elif...else  (Read 2185 times)
Telplate
Jr. Member
*

Karma: 1
Offline Offline

Posts: 4


« on: September 11, 2006, 05:40:38 PM »

I need to print a string depending on a value. The code is like this:

Code
choice = int(raw_input('Type a number between 0 and 9: '))
 
if choice == 0:
  print 'number 0'
elif choice == 1:
  print 'number 1'
elif choice == 2:
  print 'number 2'
elif choice == 3:
  print 'number 3'
elif choice == 3:
  print 'number 4'
elif choice == 4:
  print 'number 5'
elif choice == 5:
  print 'number 6'
elif choice == 6:
  print 'number 7'
elif choice == 7:
  print 'number 8'
elif choice == 9:
  print 'number 9'
else:
  print 'The number must be between 0 and 9'

The problem is that it is too long. I know other languages have statements like case and switch. Isn't there something like that in Python?
Logged
Alter Lobo
Global Moderator
Jr. Member
*****

Karma: 10
Offline Offline

Posts: 65


« Reply #1 on: September 11, 2006, 05:52:13 PM »

In Python you can do better than using case or switch. Use a dictionary:

Code
choice = int(raw_input('Type a number between 0 and 9: '))
 
choices = {1: 'number 1',
          2: 'number 2',
          3: 'number 3',
          4: 'number 4',
          5: 'number 5',
          6: 'number 6',
          7: 'number 7',
          8: 'number 8',
          9: 'number 9'}
 
print choices.get(choice, 'The number must be between 0 and 9')

The get method of the dictionary returns the element which index is given in the first parameter. If it is not found it returns the second parameter.

A dictionary is shorter and can be created and modified in runtime while case and switch statements are hard coded.
« Last Edit: September 11, 2006, 06:05:45 PM by Alter Lobo » Logged
Pages: [1]   Go Up
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!