1

For the YourName input() I would like to get a value that's a string. Hence, it shouldn't be a float, int, etc. In this example I would like to replace "Sunny" with any value that's a string to make the while loop accept the input.

YourName = ''

while YourName != "Sunny":
    print("Please type in your name")
    YourName = input()

print(YourName + " is correct")

Thanks in advance, best

Sentino

Sentino
  • 25
  • 4
  • 1
    You presumably mean that it cannot be converted to those types, because `input()` will always give a string. You probably need to look into `try`/`except`. – roganjosh Jun 28 '18 at 15:38
  • 2
    Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – SiHa Jun 28 '18 at 15:40
  • Just want to point out that your description doesn't totally match the code you've provided. This loop will only break when the user inputs "Sunny", and the loop will not end if any other string value is provided (whether it contains non-alphabetic characters or not). As such, checking for alphabetic characters would be redundant, since no string containing non-alphabetic characters will ever be equal to "Sunny". – Luke Baumann Jun 28 '18 at 16:26

3 Answers3

4

As mentioned in the comments you could use something similar to the following:

YourName = input("Please enter your name: ")

while True:
    if YourName.isalpha():
        break
    else:
        print("Must enter string")
        print("Please type in your name")
        YourName = input("Please enter your name: ")
        continue

isinstance() is a built-in function that checks to see if a variable is of a specific class, e.g. isinstance(my_var, str) == True. However, the Input() function always returns a string. Thus, if you want to make sure the input was all letters you want to use .isalpha(). You could also use Try/except. As @SiHa said this SO question has a great response.


As pointed out in the comments, this answer will not work if there is a space in the string. If you want to allow multiple name formats you can use Regex. for example you can do the following:

import re

YourName = input("Please enter your name: ")

while True:
    if re.fullmatch(r"[a-zA-Z]+\s?[a-zA-Z]+", YourName) is not None:
        break
    else:
        print("Must enter string")
        print("Please type in your name")
        YourName = input("Please enter your name: ")
        continue

Using Regular Expressions will give you more control on the inputs than regular string methods. Docs, Python Regex HOWTO. re is a standard library that comes with python and will give you the most flexibility. You can use regex101 to help you test and debug.

What the re.fullmatch() will return a match object if found and None if not. It says the input can be any lower or uppercase letter with an optional space in the middle followed by more letters.


If you don't want to import a package then you can loop through your input object and check to see if all characters are a space or alpha using:

all([x.isalpha() | x.isspace() for x in YourName])

however this will not say how many spaces there are or where they are. It would be optimal to use Regex if you want more control.

lwileczek
  • 2,084
  • 18
  • 27
  • Just a note: if you want to accept spaces in the input string, this will not allow that. In order to accept spaces, you need to loop over each character, and check that it is either a space or an alphabetic character (if you try to use `YourName.isalpha() or YourName.isspace()` without a loop, it will only return true if the entire string is all letters or all spaces, but will return false if there is a mix). – Luke Baumann Jun 28 '18 at 16:22
  • 1
    @LukeBaumann I added some info on Regex to test for cases where it's first name last name. – lwileczek Jun 28 '18 at 16:50
  • Is the last line, continue, necessary here? Does it make any difference? Wouldn't the while-loop just start a new iteration anyway? – Hias Apr 14 '19 at 13:23
  • 1
    @Hias `continue` is unnecessary, I was just being explicit in the example. – lwileczek Apr 17 '19 at 18:00
1

It's possible that you're using Python 2.7, in which case you need to use raw_input() if you want to take the input as a string directly.

Otherwise, in Python 3, input() always returns a string. So if the user enters "3@!%," as their name, that value will be stored as a string (You can check the type of a variable by using type(variable)).

If you want to check to make sure the string contains only letters, you can use the method isalpha() and isspace() (in my example code, I'll assume you want to allow spaces, but you can exclude that part if you want to require one word responses).

Because these methods operate on characters, you need to use a for loop:

YourName =""
while YourName is not "Sunny" or not all(x.isalpha() or x.isspace() for x in YourName):

     #You can pass a string as a prompt for the user here
     name = input("please enter name")
print (YourName)

However, I should note that this check is totally redundant since no string containing a non-letter character could ever be equal to "Sunny".

Luke Baumann
  • 596
  • 12
  • 35
  • @roganjosh appreciate the feedback, I'm not sure I understand though--the asker was asking how to ensure that input would be read as a string, which I think is already guaranteed since the input() method returns type string. – Luke Baumann Jun 28 '18 at 16:02
  • You absolutely can shoot me down on this because we can fall back to the ambiguous question, but I think it's obvious that the OP intends to throw out `3.14` as not-a-string and not a valid name. – roganjosh Jun 28 '18 at 16:04
  • @roganjosh right, I just realized that's probably totally right. I'm going to edit my answer accordingly. – Luke Baumann Jun 28 '18 at 16:06
  • @roganjosh I just realized this question doesn't make much sense, because the loop only ends when `YourName` is not `"Sunny"`. Therefore there's no need to check whether the input is alphabetic, since it's also required to be equal to an alphabetic string. Perhaps OP will use this in another context, though. – Luke Baumann Jun 28 '18 at 16:18
  • 1
    The question doesn't make sense, no, but you adapted your answer to come as close to answering it as I think up so you got my +1. – roganjosh Jun 28 '18 at 16:19
0

As others have pointed out, input() always returns a string.

You can use the str.isalpha method to check the character is a letter.

YourName = ''

while True:
    print("Please type in your name")
    YourName = input()
    failed = False
    for char in YourName:
        if not char.isalpha():
            failed = True

    if not failed:
        break

Example:

Please type in your name
> 123
Please type in your name
> John1
Please type in your name
John
John is correct
Ethan Brews
  • 131
  • 1
  • 5