validation from input if character is alphabetical [duplicate] - python

This question already has answers here:
How to gather information from user input and apply it elsewhere
(3 answers)
Closed 6 years ago.
Hi I am new to programming and I am trying to write a code that will gather information from the input and determine if it is a valid alphabet.
I previously asked this question before but the answers given just didn't work so I am asking the question again. Please help
words = []
word = input('Character: ')
while word:
if word not in words:
words.append(word)
word = input('Character: ')
print(''.join(words),'is a a valid alphabetical string.')
suppose I choose three letters then the output of my code then pressed enter
on the fourth,
the code will be:
Character:a
Character:b
Character:c
Character:
abc is a valid alphabetical string.
I want to add to this code so that when I type in a character that is not
from the alphabet the code will do something like this.
Character:a
Character:b
Character:c
Character:4
4 is not in the alphabet.
This is exactly how I want my output to be.

If you look at the string class I think you will find it has some variables you would find useful.
from string import letters
word = raw_input("Character: ")
words = []
while word and word in letters:
if word not in words:
words.append(word)
word = raw_input('Character: ')
I don't have python on this computer but I think that you will find this chunk of code works. Also, the string class has a several other variables you might find useful including digits, punctuation, printable etc

You may use string.isalpha() function to find whether the input is alphabetic or not.
>>> 'a'.isalpha()
True <-- as 'a' is alphabet
>>> 'A'.isalpha()
True <-- as 'A' is also alphabet
>>> ''.isalpha()
False <-- empty string
>>> '1'.isalpha()
False <-- number
-------------------------
>>> 'ab'.isalpha()
True <-- False, since 'ab' is alphabetic string
# NOTE: If you want to restrict user to enter only one char at time,
# you may add additional condition to check len(my_input) == 1
>>> len('ab') == 1 and 'ab'.isalpha()
False
In order to get the input from user, you can do:
Using raw_input:
x = raw_input() # Value of x will always be string
Using input
x = input() # Value depends on the type of value
x = str(x) if x else None # Convert to str type. In case of enter with value set as None

Related

Python while loop to continue when inputting an integer. Break when inputting string or character [duplicate]

This question already has answers here:
Python how to check if input is a letter or character
(5 answers)
Closed 3 years ago.
I am new to python and trying to figure out how to make this program only take a string or character and then have it spell out said string/character. Unfortunately, when using the lines while word != str() or chr():
word = input("Enter a string or character...") I am constantly prompted to "Enter a string or character" even when I inputted a string/character to begin with. How would I be able to go about fixing this so that the program takes a string and breaks out of the while loop so that it can spell whatever I typed in?
word = input("What is your word? ")
while word != str() or chr():
word = input("Enter a string or character...")
for char in word:
print(char)
Try the following:
word = input("What is your word? ")
while type(word) is not str():
word = input("Enter a string or character...")
for char in word:
print(char)
Also, the input will always be a string.
If you want to check for numeric input, then you should do something like:
try:
int(word)
except ValueError:
# input is a string
else:
continue # input is a number
Maybe something like this would work:
word = input("What is your word? ")
while word.isdigit(): # the word contains only digits
word = input("Enter a string or character...")
for char in word:
print(char)
Few notes:
In your code word != str() would hold true as long as your input is not empty, as str() is a (very ugly) way of initializing an empty string.
The return type from input() is str. If you want to treat it as an integer or any other type you'd have to cast/parse it

Python: How to interpret user input as a list (beginner) [duplicate]

This question already has answers here:
Get a list of numbers as input from the user
(11 answers)
Closed 4 months ago.
I am trying to write a function that takes a user inputted list, and transforms it into a string that separates each value inside the list with a comma, and the last value in the list with "and". For example, the list ['cats', 'dogs', 'rabbits', 'bats'] would be transformed to: 'cats, dogs, rabbits, and bats'.
My code works if I assign a list to a variable and then pass the variable to my newString function, but if I pass a user input to my function, it will treat every character in the user input as a separate list value.
So my question is, how can I tell Python that I want input() to be read as a list. Is this even possible? I am very new to Python and programming in general, so Lists and Tuples is about as far as I know so far. I am learning dictionaries now. My code is printed below, thanks.
def listToString(aList):
newString = ''
for i in range(len(aList) - 1):
newString += aList[i] + ', '
newString = newString + 'and ' + aList[-1]
return(newString)
spam = list(input())
print(listToString(spam))
input() always gives you just a string.
You can analyze that string depending on how the user is supposed to enter the list.
For example, the user can enter it space separated like 'cats dogs rabbits bats'. Then you do
input_list = input().split()
print(listToString(input_list))
You can also split on , or any delimiter you like.
If you want to read a list literal from user input, use ast.literal_eval to parse it:
import ast
input_list = ast.literal_eval(input()) # or ast.literal_eval(raw_input()) on Python 2
You could build a list from the input and use your current working code to format it as you want.
def get_user_input():
my_list = []
print('Please input one word for line, leave an empty line to finish.')
while True:
word = input().strip()
if word:
my_list.append(word)
else:
break
return my_list

Check if a character is inside a string via a variable in Python? [duplicate]

This question already has answers here:
Check if a string contains a number
(20 answers)
Closed 7 years ago.
I am a newbie in Python. I am making a program where I take a input from user and check if any number is inside in the string. I am checking it by taking it in a variable. Is it not correct to check via a VARIABLE?
user_string=input("Enter the Word:")
print (user_string)
for index in (0,9):
number=str(index) #Typecasting Int to String
if number in user_string: #Check if Number exist in the string
print ("yes")
output:
Enter the Word:helo2
helo2
You can use the string method isdigit() on each character in a generator expression within any. This will short-circuit upon finding the first numeric character (if one is present)
>>> user_string = 'helo2'
>>> any(i.isdigit() for i in user_string)
True
>>> user_string = 'hello'
>>> any(i.isdigit() for i in user_string)
False
Look at your for-loop. You are looping over a tuple (0,9). So actually you are only testing for 0 and 9. Use range(10) instead.
More elegant, to get the numbers inside your string, you can use sets:
import string
print 'yes' if set(string.digits).intersection(user_string) else 'no'

How do I check if a string contains ANY numbers [duplicate]

This question already has answers here:
How to check if a string only contains letters?
(9 answers)
Closed 7 years ago.
I am trying to validate an input for the user's name. So far I can prevent them entering only numbers and the prompt is repeated using a while loop. How can I stop a string containing letters and numbers being accepted?
This is what I have so far:
name = ""
name = input("Please enter your name:")
while name == "" or name.isnumeric() == True:
name = input("Sorry I didn't catch that\nPlease enter your name:")
Use any and str.isdigit:
>>> any(str.isdigit(c) for c in "123")
True
>>> any(str.isdigit(c) for c in "aaa")
False
In your case:
while name == "" or any(str.isdigit(c) for c in name):
name = input("Sorry I didn't catch that\nPlease enter your name:")
Alternatively you can use str.isalpha:
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
For 8-bit strings, this method is locale-dependent.
I'd use it like this to validate stuff like "Reut Sharabani":
while all(str.isalpha(split) for split in name.split()):
# code...
What it does is split the input by whitespace and make sure each part is alphabetic letters only.

check user_input with if token in a loop

I am trying to write a function that checks my input to see whether I have entered the character '?'.
This is what I got so far:
def check_word():
word = []
check = 0
user_input = input('Please enter a word that does not contain ?: ')
for token in user_input.split():
if token == '?':
print('Error')
check_word()
My input: hello?
It is supposed to show 'Error'. But it doesn't show anything. Could you please tell me what wrong it is in my code.
I would use the in operator to do this
def check_word(s):
if '?' in s:
print('Error')
For example
>>> check_word('foobar')
>>> check_word('foo?')
Error
The problem is how you split the string of the user_input.
user_input.split():
The example doesn't contain whitespaces so the condition isn't met. If you want for example to check a sentence with spaces, you should split it like this: user_input.split(' ') to split it on the spaces.
But for this example you have two choices:
1) You can just iterate over the input itself because you want to check every char in the string for whether it's a ?.
That is, change user_input.split(): into simply user_input without splitting. This option is good if you might ever want to add some sort of action for each char.
2) It's very easy just to use in, like this:
if '?' in s:
print('There is a question mark in the string')
This is a very simple solution that you can expand and check for other chars in the string as well.
It's because user_input.split() splits the user_input by whitespace. Since hello? does not contain any whitespaces, token is equal to your input and the loop is executed once.
You should iterate over user_input instead, or simply check if '?' in user_input.

Categories