Home > Net >  How to have input in Python only take in string and not number or anything else only letters
How to have input in Python only take in string and not number or anything else only letters

Time:11-25

I am a beginner in Python so kindly do not use complex or advanced code.

contact = {}

def display_contact():
    for name, number in sorted((k,v) for k, v in contact.items()):
        print(f'Name: {name}, Number: {number}')



#def display_contact():
# print("Name\t\tContact Number")
# for key in contact:
#    print("{}\t\t{}".format(key,contact.get(key)))

while True:
  choice = int(input(" 1. Add new contact \n 2. Search contact \n 3. Display contact\n 4. Edit contact \n 5. Delete contact \n 6. Print \n 7. Exit \n Enter "))
  
#I have already tried


  if choice == 1:
    while True:
      try:
        name = str(input("Enter the contact name "))
        if name != str:
      except ValueError:
        continue
      else:
        break

    while True:
      try:
        phone = int(input("Enter number "))
      except ValueError:
        print("Sorry you can only enter a phone number")
        continue
      else:
        break
    contact[name] = phone
    
  elif choice == 2:
    search_name = input("Enter contact name ")
    if search_name in contact:
      print(search_name, "'s contact number is ", contact[search_name])
    else: 
      print("Name is not found in contact book")
      
  elif choice == 3:
    if not contact:
      print("Empty Phonebook")
    else: 
      display_contact()
      
  elif choice == 4:
    edit_contact = input("Enter the contact to be edited ")
    if edit_contact in contact:
      phone = input("Enter number")
      contact[edit_contact]=phone
      print("Contact Updated")
      display_contact()
    else:
      print("Name is not found in contact book")
      
  elif choice == 5:
    del_contact = input("Enter the contact to be deleted ")
    if del_contact in contact:
      confirm = input("Do you want to delete this contact Yes or No? ")
      if confirm == 'Yes' or confirm == 'yes':
        contact.pop(del_contact)
      display_contact
    else:
      print("Name is not found in phone book")



  elif choice == 6:
    sort_contact = input("Enter yes to print your contact")
    if sort_contact in contact:
      confirm = input("Do you want to print your contact Yes or No? ")
      if confirm == 'Yes' or confirm == 'yes':
        strs = [display_contact]
        print(sorted(strs))     
    else:
      print("Phone book is printed.")
  else:
        break

I tried but keep getting errors and I can't fiugre out how to make it only take string or letter as input and not numbers.

if choice == 1:
    while True:
      try:
        name = str(input("Enter the contact name "))
        if name != str:
      except ValueError:
        continue
      else:
        break

it is not working my code still accepts the ans in integer and string.

I am a beginner so I might have made a lot of mistakes. Your patience would be appreciated.

CodePudding user response:

You can use a regex with re.fullmatch:

import re

while True:
    name = input("Enter the contact name ")
    if re.fullmatch(r'[a-zA-Z] ', name):
        break

Or use the case-insensitive flag: re.fullmatch(r'[a-z] ', name, flags=re.I):

CodePudding user response:

As you noted that you are a beginner, I'm adding this piece of code as a "custom-made" validation, just so you can check how you would do something like this by your own .

Note: @mozway gave a MUCH BETTER solution, that is super clean, and I recommend it over this one.

def valid_input(input: str):
    # Check if any char is a number 
    for char in input:
        if char.isdigit():
            print('Numbers are not allowed!')
            return False
    return True


while True:
    name = input("Enter data:")
    if valid_input(name):
        break

CodePudding user response:

sorry I'm dumb so I found this answer from another website:

extracted_letters = " ".join(re.findall("[a-zA-Z] ", numlettersstring))

First, import re to use the re function. Then lets say that numlettersstring is the string you want only the letters from. This peice of code will extract the letters from numlettersstring and output it in the extracted_letters variable.

  • Related