How to make a proper name input program in python

Caeruleas

I am at the part where I ask the user for their name. So far I got this:

# Import stuff
import time

# Create empty variable
Name = ""

# Ask their name
while Name = ""
    Name = input("What is your name? ")
    print("")
print(Name)
print("")
time.sleep(3)

So if the user inputs nothing, it repeats the question. But when the user inputs an integer or a float it registers this as a valid name.

How will I be able to make it so that if the Name variable is an integer or a float, it will respond with "Please enter a valid name" and repeat the question?

spikespaz

I'm updating my answer to simplify the code and make it more readable.

The below function is a function that I would use in my own code, I would consider it to be more "proper" than my old answer.

from string import ascii_letters

def get_name():
    name = input("What is your name?\n: ").strip().title()

    while not all(letter in ascii_letters + " -" for letter in name):
        name = input("Please enter a valid name.\n: ").strip().title()

    return name

To break this down, the line all(letter in ascii_letters + " -" for letter in name) means "if each letter in name is not an alphabetical character, a space, or a hyphen".

The part letter in ascii_letters + " -" checks to see if a letter is in the string "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -".

This is repeated by the next part, for letter in name, for every character in the string. This will effectively return a list of booleans, [True, True, True, ...] where any False is a character that did not pass the conditional. Next, this list is passed to the all() function, which returns True if all of the list items are True.

After the all() is executed, conditional is reversed, allowing the loop to continue on the existence of a single failed character.


Old answer is as follows, it will still be useful.

This function should work well for you. Simply check if the string the user entered is alpha characters only, otherwise ask again.

Notice the use of str.isalpha().

def get_name():
    name = input("What is your name?\n: ").strip().title()

    while not (name.replace("-", "") and
               name.replace("-", "").replace(" ", "").isalpha()):
        name = input("Please enter a valid name.\n: ").strip().title()

    return name

Checking if name will check if the string is empty, and using str.strip() on the values returned will remove any surrounding whitespace (stray spaces) to the left or right of the user input.

The str.replace("-", "") eliminates hyphens while checking validity. Thanks for pointing this out @AGN Gazer.

Now you can just call the function later in your script, or store it for later.

name = get_name().title()

print("You said your name was " + name + ".)

The str.title() converts the letter of each word in a string to uppercase. For example, if I entered my name "jacob birkett", the output (and subsequent value of name would be "Jacob Birkett".

Take a look at the documentation for str.isalpha(), str.strip(), str.replace() and str.title().

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to make a variable name dependant on input in python?

How to make proper Input validation with regex?

How to make wget to save with proper file name

How to make this program in python?

How to make a proper word searcher with Python?

Python How to make a proper string slicing?

proper name for python * operator?

How do I make my Python program search up my questions on Google (based on a certain input)?

how to make a tkinter program with a login input, an input area, and a submit button

How do I write a python program that takes my name as an input and gives the letters of my name as an output, each in a new line

How to make a proper copy of 2D list in Python

In Powershell, how to make the zip output name the same as the input name

How to make this program give proper output and shift elements in list properly using for loop and one board

after compiling python program, how to input arguments

How to take input in beginning of the program in python?

How to give input to python program through bash?

How to make a word counter program using Python?

How to make globally callable python program?

how to make sign up and login program in python?

How to make any python program run standalone

How To Make a Python Program Automatically Restart Itself

How to make a program that can be opened with a file? (python)

Python | How to make a program that calculates strings

How to make python program ".py" executable?

How to make a program run at startup using python

How to make a program end on a blank line in python?

How to make an on/off switch for a function in a python program?

How do I make a program that reverse user input of integers in Java?

How to make a C program loop back to reprompt for new input?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive