Python Mistake - Number of letters in name

后端 未结 3 569
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-29 10:28

Write a program that checks how long a name is. The program should take a name as input from the user.

If the name has 3 or fewer letters, your program should work like

相关标签:
3条回答
  • 2021-01-29 11:08
    a = input('Enter your name: ')
    
    if len(a) <= int(3):
      print ('Hi', a+ ',', 'you have a short name.')
    
    elif len(a) <= int(8):
     print ('Hi', a+ ', nice to meet you.') 
    
    elif len(a) > int(8):
      print ('Hi', a+ ', you have a long name.')
    
    0 讨论(0)
  • 2021-01-29 11:15

    You code will not behave as you expect. In addition to using len, use string formatting. Try re-arranging your if statements as follows:

    name = raw_input('Enter your name: ')
    
    if len(name) > 8:
      print 'Hi {}, you have a long name.'.format(name)
    elif len(name) > 3:
      print 'Hi {}, nice to meet you.'.format(name)
    else:
      print 'Hi {}, you have a short name.'.format(name)
    

    or you could factor it like this:

    name = raw_input('Enter your name: ')
    greeting = 'Hi {}, '.format(name)
    
    if len(name) > 8:
      statement = 'you have a long name.'
    elif len(name) > 3:
      statement = 'nice to meet you.'
    else:
      statement = 'you have a short name.'
    
    print '{}{}'.format(greeting, statement)
    
    0 讨论(0)
  • 2021-01-29 11:18

    You should use len(name) and you don't need int(3) as 3 is already an integer. Your check should look like this:

    name = input('Enter your name: ')
    
    if len(name) >= 3:
       # do stuff
    

    I changed Name to name as this is the standard convention of variable naming in Python.

    0 讨论(0)
提交回复
热议问题