Data type validation in python - Strings - python

I am currently writing some python code that asks for a users name. I need the program to validate whether the user's input is a string or not. If it is a string, The loop will break and the programme will continue. If the input is not a string (like a float, integer etc), It will loop around and ask the user to input a valid string. I understand that you can use the following code when you are checking for an integer;
while True:
try:
number = int(input("Plese enter a number: "))
break
except ValueError:
print("Please enter a valid integer")
I was thinking that I could use something like this to check for a string;
while True:
try:
word = str(input("Plese enter a string: "))
break
except ValueError:
print("Please enter a valid string")
But as far as I understand, the str() just converts the user's input to a string, regardless of the data that was entered.
Please help!
thanks

Based on the comments, it looks like you want to check if the input consists of alphabetic characters only. You can use .isalpha() method:
while True:
word = input("Please enter a string: ")
if word.isalpha():
# Do something with valid input.
break
else:
print("Please enter a valid string")

Related

How do I make an input() detect if the user input is something other than a string?

I am fairly new to Python and I wanted to generate a simple user input that asks for your name. I got the prompt to work but when I added code that detects if the input is not a string, it doesn't let me input anything at all.
It was working up until I added the code that tells the user if they used an unsupported character.
Here's the code I have so far:
while True:
name = input('What is your name? ')
if name is str:
print('Hi,%s. ' % name)
if name != str:
print('That is not a valid character!')
Python supplies methods to check if a string contains on alphabets, alphanumeric or numeric.
isalpha() returns True for strings with only alphabets.
isalnum() returns True for strings with only alphabets and numbers and nothing else.
isdigit() returns True for strings with only numbers.
Also your if-else statement is off
name = input('What is your name? ')
if name.isalpha():
print('Hi,%s. ' % name)
else:
print('That is not a valid character!')
When you do
name = input('What is your name? ')
you get a string called name, so checking it it is a string won't work.
What you can check is if it's an alphabetical character, using isalpha:
if name.isalpha():
# as you were
There are various other string methods ( see here ) which start is to check for numbers, lower case, spaces and so on.

Trying to create code that both verifies that a variable is numbers and has 4 or 5 characters long

I am trying to create code that takes a ZIP code and verifies that the input is numeric and that it's between 4 to 5 characters in length. This is the code I am trying to use. But if I put in letters, it doesn't print "Invalid Area Code", it just errors out.
zip_code = int(input("Please enter your area code: "))
if len(zip_code) == 4 or len(area_code) == 5 and zip_code.isnumeric():
print (zip_code)
else:
print("Invalid zip Code")
There are two issues with your code:
You're converting the input to an integer, then calling len() on it. You can call len() on strings, but not integers, so don't transform the input to an integer.
area_code isn't defined. You're probably looking to use zip_code instead.
Here is a code snippet that resolves both of these issues:
zip_code = input("Please enter your area code: ")
if len(zip_code) == 4 or len(zip_code) == 5 and zip_code.isnumeric():
print(zip_code)
else:
print("Invalid ZIP code")
If a string is parsable to be an integer, meaning that it is actually a number, your code will work fine. But most of the time, user inputs can not be predicted. if you just use isnumeric or isdigit in your code, you won't have any problem.
Personally speaking, I use regex to validate user input in most of the cases. In your case, I came up with code below:
import re
string = input("Please enter your area code: ")
pattern = "^\d{4,5}$"
if re.search(pattern, string):
print("Valid " + string)
else:
print("Invalid zip Code")
Example of correct input:
1234
Output
Valid 1234
Example of incorrect input:
123415
Output:
Invalid zip Code
Explanation
re.search function takes two arguments. The first argument is a pattern which will check if the second argument, which is a string, follows the pattern or not. ^\d{4,5}$ checks if the user input is a number that has 4 or 5 digits.

How to make a string that only includes spaces be an invalid input in python

I'm a newbie in coding using python and I'm trying to write a piece of small code that prints whatever you input in the terminal, but I don't want anything that only includes spaces and no other characters or doesn't even have an input to be printed. Here's the code:
while True:
my_name= input("> ")
if "" in my_name:
print("I don't know what that means. Please choose a valid answer.")
else:
print(f"Ah, I see, so your name is {my_name}?")
would love to have multiple solutions to this, and thank you if you helped :)
https://docs.python.org/2/library/stdtypes.html#str.isspace
I think this should do the trick
if my_name.isspace():
print("Your name is full of spaces")
Python isspace() method is used to check space in the string. It returns true if there are only white space characters in the string. Otherwise it returns false.
ex:
# Python isspace() method example
# Variable declaration
str = " " # empty string
# Calling function
str2 = str.isspace()
# Displaying result
print(str2)
There's one way of doing that by using exceptional handling for no input using try - except block and a flag variable that checks if input doesn't contain only spaces.
try:
flag = False
my_name = input()
for i in my_name:
if i != ' ':
flag = True
if flag:
print(my_name)
else:
print('Invalid input')
except:
print('No input')
The other ways can be using the built in function strip() which removes the trailing and leading spaces in input.
If the input has only spaces then strip() will remove all of them resulting in an empty string.
try:
my_name = input()
if my_name.strip() == '':
print('Invalid input')
else:
print(my_name)
except:
print('No input')
Like this, you can use bools:
while True:
my_name= input("> ")
if my_name.strip():
print(f"Ah, I see, so your name is {my_name}?")
else:
print("I don't know what that means. Please choose a valid answer.")

How do i get my script to nicely reject invalid characters

at the moment if you put a character instead of a number in the input it gives an ugly error. I would like the script to output something like "Invalid character! Please enter a digit." whats something i can do to fix this?
import random
import string
string.ascii_letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.number_symbols='!##$%^&*()'
userLetterInput = int(input("How many letters would you like in your password?: "))
userSymbolInput = int(input("How many symbols would you like in your password?: "))
letterResult = ''.join([random.choice(string.ascii_letters) for i in range(userLetterInput)])
symbolResult = ''.join([random.choice(string.number_symbols) for i in range(userSymbolInput)])
print("".join(letterResult + symbolResult))
You can use a try/except statement in a loop to catch the exception and display a message for the user. The try/except statement catches the exception thrown when the user enters alphabetic characters, whereas the loop repeats the query for a number until the user gives a valid input.
import random
import string
string.ascii_letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.number_symbols='!##$%^&*()'
while True: # Repeat the question until valid input is given
try: # Catch ValueError which gets thrown when letters are entered
userLetterInput = int(input("How many letters would you like in your password?: "))
break # Exit the loop if no exception is thrown
except ValueError:
print("Invalid character! Please enter a digit.")
while True:
try:
userSymbolInput = int(input("How many symbols would you like in your password?: "))
break
except ValueError:
print("Invalid character! Please enter a digit.")
letterResult = ''.join([random.choice(string.ascii_letters) for i in range(userLetterInput)])
symbolResult = ''.join([random.choice(string.number_symbols) for i in range(userSymbolInput)])
print("".join(letterResult + symbolResult))
Instead of using a while True loop, you could of course also declare a boolean (e.g. invalid_input) which is True at first and gets set to False after the user entered a valid number.
you can check input type with "isinstance":
isinstance(1, int)
isinstance('be', str)

Python Encryption

So for an exam question I've followed this specific pseudo code which basically makes a program which encrypts a number sequence using the same principle as the ceasar cipher. It should work but for some reason it returns the error.
TypeError: 'int' object is not iterable
Heres the code, i hope you guys can help me, much appreciated
plainNum = input("enter a number to encode ")
codedNum = ' '
Key = input("enter a key ")
for i in plainNum:
codedNum = codedNum + str((int(i)+key)%10)
print codedNum
Use raw_input if you expect a string:
plainNum = raw_input("enter a number to encode ")
input() interprets the input as if it is Python code; enter 5 and it'll return an integer, enter 'some text' (with quotes) and it'll return a string. raw_input() on the other hand returns the entered input uninterpreted.
Most dirty fix of all, simply change
for i in plainNum:
with
for i in str(plainNum):
This is working but not if I use a decimal and it doesn't behave if I enter words or spaces. Consider checking first that the entry is a number with something like:
try:
float(element)
except ValueError:
print "Not a float"
after stripping any whitespace with something like:
plainNum = plainNum.strip()
But this outputs the encoded digits of your entered integer:
plainNum = raw_input("enter a number to encode ")
codedNum = ' '
key = input("enter a key ")
for i in plainNum:
codedNum = codedNum + str((int(i)+key)%10)
print codedNum
Ask the user for the number with raw_input. This makes the input a string which you can iterate over with:
for char in plainNum:
Yes, this is a now a char in a string and so you've used the int(i) function.
you maybe also wanna change key to Key to reflect what variable is declared
and also make codeNum initially equal to '' instead of ' ' (no space vs space)
just book keeping stuff

Categories

Resources