#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    1
    Rep Power
    0

    Learning python, help please


    I have just recently began learning python (I already know Java), and I am using the google class as I go. I've been having trouble getting python to recognize my if statements and act on them. Here's an example.

    Code:
    # B. both_ends
    # Given a string s, return a string made of the first 2
    # and the last 2 chars of the original string,
    # so 'spring' yields 'spng'. However, if the string length
    # is less than 2, return instead the empty string.
    def both_ends(s):
      # +++your code here+++
      print s
      if s >= 2:
        p1 = s[0:2]
        p2 = s[-2:]
        tot = p1 + p2
        return tot
      
      else: tot = ''
      return tot
    When the input is 'a', the program actually uses the first if statement and it returns 'aa', when it should actually return an empty string. Does anyone know what the problem is?
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,700
    Rep Power
    480
    Code:
    def both_ends(s):
      if len(s) >= 2:############ len(s)
        p1 = s[0:2]
        p2 = s[-2:]
        tot = p1 + p2
      else:
        tot = ''
      return tot
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo