Checking if a variable contains spaces and letters - python-3.x

I am trying to make a program that asks for a name but will reject the input if it doesn't contain letters/spaces. However, it seems to reject spaces as well as numbers and symbols.
print("Welcome to the Basic Arthmetics Quiz.")
print("What is your name?")
name=input()
if not name.isalpha()or name not in(str(" ")):
print('Please only enter letters for your name!')
while not name.isalpha()or name in(str(" ")):
v=1
print('Please enter your name again.')
name=input()
if name.isalpha()or name not in(str(" ")):
v=0
else:
v=1
Where have I gone wrong?

This looks an awful lot like homework.
Your test name not in(str(" ")), which should be written name not in " ", tests whether name is one of {"", " "}.
It would be easiest to test the name one char at a time, with a per-char condition like
char.isalpha() or char == ' '
Combine this with all and a generator expression to test all chars of name.
The actual implementation, as well as proper code flow (you don't use v, you perform the test thrice, and call input() twice, all of which is unacceptable) are left as exercise.

Related

Python Error message for entering a number instead of a letter

I just started my programming education with python in school. One of the programs I started with simply asks you your name and then repeats it back to you. I'd like some help with getting an error message to show up if you put in a number rather than letters.
This is what I have:
while True:
name = input("What is your full name? ")
try:
n = str(name)
except ValueError:
print("Please enter your name in letters, not", repr(name))
continue
else:
break
print(name)
You can check the name if only contains letters by using string.isalpha()
in your case you name it n so n.isalpha() will return True or False
for more information:
How can I check if a string only contains letters in Python?

Python: String similar to everything

I need to use string (or int, bool, etc.) which will be same as everything. So this code:
user_input = input()
if user_input in *magic_string_same_as_everything*:
return True
should return True everythine, no matter what will user type into console.
Thanks for your help
Edit:
I see, that I've asked verry badly.
I'm trying to get 3 user input in this for cycle:
user_input = ["", "", ""] # Name, class, difficulty
allowed_input = ["", ["mage", "hunter"], ["e", "m", "h"]]
difficulty = {"e": 1, "m": 2, "h": 3}
message = ["Please enter your heroic name",
"Choose character (mage/hunter)",
"Tell me how difficult your journey should be? (e / m / h)"]
print("Welcome to Dungeons and Pythons\n" + 31 * "_")
for i in range(3):
while True:
print(message[i], end=": ")
user_input[i] = input()
if user_input[i] in allowed_input[i]:
break
Choose of name is without restrictions.
I hope, that now my question makes a sense.
You could just get rid of the if-statement and return True without the check or (if you really want to use the if-statement) you type if(True) and it will always be true.
You want True for non empty string?
Just use user_input as bool.
user_input = input()
if user_input:
return True
In your question Name is special case, just check it like this and for the rest of input you can use range(1,3).
Alternatively switch to using regular expressions
allowed_input = ["\A\S+", "\A(mage|hunter)\Z", "\A[emh]\Z"]
for i in range(3):
while True:
print(message[i], end=": ")
user_input[i] = input()
if re.match(allowed_input[i], user_input[i]) :
break
Initial response
This one liner should work.
If user inputs anything, it counts as an input & prints 'True', but if user just hits 'Enter' without typing anything, it returns 'No input'
print ("True" if input("Type something:") else 'No input')
After your edited question
To achieve what you want, you can define a function that checks for the user input values & corrects them if incorrect.
import re
# for user input, a single line of code is sufficient
# Below code takes 3 inputs from user and saves them as a list. Second and third inputs are converted to lowercase to allow case insensitivity
user_input = [str(input("Welcome to Dungeons & Pythons!\n\nPlease enter username: ")), str(input("Choose character (mage/hunter): ").lower()), str(input("Choose difficulty (e/m/h):").lower())]
print (user_input) # Optional check
def input_check(user_input):
if user_input[0] != '':
print ("Your username is: ", user_input[0])
else:
user_input[0] = str(input("No username entered, please enter a valid username: "))
if re.search('mage|hunter', user_input[1]):
print ("Your character is a : ", user_input[1])
else:
user_input[1] = str(input("Incorrect character entered, please enter a valid character (mage/hunter): ").lower())
if re.search('e|m|h',user_input[2]):
print ("You have selected difficulty level {}".format('easy' if user_input[2]=='e' else 'medium' if user_input[2]=='m' else 'hard'))
else:
user_input[2] = str(input("Incorrect difficulty level selected, please choose from 'e/m/h': "))
return (user_input)
check = input_check(user_input)
print (check) # Optional check
In each of the if-else statements, the function checks each element and if no input/ incorrect input (spelling mistakes, etc.) are found, it asks the user to correct them & finally returns the updated list.
Test Output
With correct entries
[Out]: Welcome to Dungeons & Pythons!
Please enter username: dfhj4
Choose character (mage/hunter): mage
Choose difficulty (e/m/h):h
['dfhj4', 'mage', 'h']
Your username is: dfhj4
Your character is a : mage
You have selected difficulty level hard
['dfhj4', 'mage', 'h']
With incorrect entries
[Out]: Welcome to Dungeons & Pythons!
Please enter username:
Choose character (mage/hunter): sniper
Choose difficulty (e/m/h):d
['', 'sniper', 'd']
No username entered, please enter a valid username: fhk3
Incorrect character entered, please enter a valid character (mage/hunter): Hunter
Incorrect difficulty level selected, please choose from 'e/m/h': m
['fhk3', 'hunter', 'm']

Python - Check if a user input is in another user input

Python 3.5
I am writing a program that essentially asks the user to input a sentence (no punctuation). Then it will ask for the user to input a word. I want the program to identify whether or not that word is in the original sentence (I refer to the sentence as string 1 (Str1) and the word as string 2 (Str2)). With the current code I have, it will only ever tell me that the word has been found and I can't seem to find a way to fix it.
str1 = input("Please enter a full sentence: ")
print("Thank you, You entered:" , str1)
str2 = input("Now please enter a word included in your sentence in any way you like: ")
if (str2,str1):
print("That word was found!")
else:
print("Sorry, that word was not found")
If anyone has any advice on that might help me and anyone else interested in this topic then that would be greatly appreciated! :)
Although as this is a learning process for me, i don't really want straight forward "here's the code you should have..." but if that is all that can be offered then i would be happy to take it.
if str2 in str1:
print("That word was found!")
else
print("Sorry, that word was not found")
Is this what you are looking for ?
The in checks if str2 is literally in str1. Since str1 is a list of words it checks if str2 is inside str1.
The answer provided works ok, but if you want word matching, will provide a false positive given:
EDIT: just spotted the prompt asks for a word in the sentence... In my experience, these sorts of things are most prone to breakage when they interact with a human, so I try to plan accordingly.
str1 = "This is a story about a man"
str2 = "an"
where:
broken_string = str1.split()
if str2.lower() in [x.lower() for x in broken_string]:
print("The word {} was found!".format(str2))
else:
print("{} was not found in {}.".format(str2, str1))
Gets a little more complicated (fun) with punctuation.

Asking python for a breakfast menu

'meals = ("Juice", "Milk", "Bread")
name = input("What do you want in a breakfast? ")
if meals =='bread''milk''juice':
print("I love it ")
else:
print(" I don't want it ")'
You need to compare the user input, which is a string stored in the variable name with meals which is a tuple of strings. To compare the two, you need to include a in logical operator:
name = input("What do you want in a breakfast? ")
if name in meals:
print("i love it")
else:
print("i dont want it")
However, for this code to work, the user input must always be capitalized. Next time, ask a question and state your desired outcome instead of just posting code.

Python How to check if user input is a string?

My first question on here...
I want to know how to check if the user input is a string. If it is not a message should appear. Otherwise the answer should be accepted. Here is what I have (I am looking for the simplest fix please):
try:
name=str(raw_input("What is your name? "))
except:
print("Your name must consist of letters only")
else:
print("Thank you for entering your name.")
str.isalpha() checks if all characters in the string are alphabetic and there is at least one character. So
name=str(raw_input("What is your name? "))
if not name.isalpha():
print("Your name must consist of letters only")
else:
print("Thank you for entering your name.")
However this will not work if name is "Homer Simpson" (with a space) which is valid input for name.
And don't you forget this!!!
What about an assertion with the check for non ascii letters in the string , similar to here,
import string
try:
name = raw_input("What is your name? ")
assert any([char not in string.ascii_letters for char in name]) is False
except AssertionError:
print("Your name must consist of letters only")
else:
print("Thank you for entering your name.")

Resources