-1

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 this:

Enter your name: Lin Hi Lin, you have a short name.

If the name has between 4 and 8 letters (inclusive), your program should work like this:

Enter your name: Jimmy Hi Jimmy, nice to meet you.

Otherwise, if the name has more than 8 letters, your program should work like this:

Enter your name: Yaasmeena Hi Yaasmeena, you have a long name.

Here's my attempt but it always returns "Hi XXXXXXX, you have a short name" regardless of the length.

Name = input('Enter your name: ')

if Name.count('Name') >= int(3):
  print ('Hi', 'Name', ',', 'nice to meet you.') 

elif Name.count('Name') <= int(3):
  print ('Hi', 'Name', ',', 'you have a short name.')

elif Name.count('Name') > int(8):
  print ('Hi', 'Name', ',', 'you have a long name.')
4

3 回答 3

4

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.

于 2013-08-13T03:46:31.903 回答
1

您的代码不会像您预期的那样运行。除了使用 len,使用字符串格式。尝试重新安排您的 if 语句,如下所示:

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)

或者你可以像这样考虑它:

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)
于 2013-08-13T04:06:41.447 回答
0
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.')
于 2016-02-17T08:03:25.840 回答