简体   繁体   中英

How do i say if name != str: print(“thats not a name”) python 3

I'm new to python but i was just testing this out and it doesn't work.

what i want is for the user to input their name and if it is a string, it will print("Hello" + name) and if it isn't a string it will print("That's not a name")

here is my code:

name = str(input("What is your name? "))
if name != str:
    input("Thats not your name! Please retype your name ")
else: 
    print("Hello " + name)

input("Press any button to close")

You can use isalpha function in python to check if the input contains only letters.

This should work:

name = input("What is your name? ") # REMOVED REDUNDANT EXPLICIT TYPE CAST

if name.isalpha(): # CHECK IF IT ONLY CONTAINS LETTERS
    print("Hello " + name)
else:
    name = input("Thats not your name! Please retype your name ") # NOT REQUIRED, BUT SINCE QUESTION WAS TO RE-ENTER

input("Press any button to close")

Hope this helps.

The first print statement you see will prompt the user with the question "What is your name?" In the second line of the code,the raw input is then taken from the user and stored in a variable called "name". In the if statement we have a function ".isalpha()" which checks if 'name' is alphabets or not.If it is then it return True and so the first print statement is printed else if its not alphabets then False is returned,hence the print statement after else is printed.

print("What is your name?") 
name = input() 

if name.isalpha(): #
  print("Hello " + name)
else:
  print("Thats not your name! Please retype your name ")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM