Python: String similar to everything - python-3.x

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']

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 password validator

I'm trying to make a basic program that checks if a password meets certain criteria. This isn't returning any errors but gives the 'password verified' message whether there is a special character or not. Any ideas welcome!
import re
begin = str(input("Would you like to check your password strength?"))
while begin.lower() == "yes" or begin.lower() == "y":
password = str(input("Please enter your password"))
if len(password)<8:
print ("Your password needs to be at least 8 characters long")
elif password.isupper() or password.islower():
print ("Please and include at least one upper and one lower case letter in your password")
elif password.isnumeric() or password.isalpha():
print ("Your password should not be numbers only or letters only but should include a mixture of both")
elif re.match("£$%^&*()",password) == True:
print ("Your password should contain at least one special character")
else:
print ("Password verified")
Your use of re.match() is flawed on several counts. Rather get into that, though, I would propose a different tactic:
elif set("£$%^&*()").isdisjoint(password):
This converts your string of special characters into a set of characters, then checks to see if it is disjoint from the password... that is, if it shares no elements with the password. If that is true, then you know that none of your special characters appear in the password and can proceed accordingly.

How do I create an input that can only receive strings?

I have approached my own question using while loops, if functions and try/except, but have not yet had the desired results.
Here is a method that I have tried recently:
Surname2 = input('\nSurname:')
while Surname2 != type('a'): #2
print('\nPlease define Surname only in letters')
Surname2 = input('\nSurname:')
break
The error I keep on having here is that it either continues to loop, doesn't receive a string as a string or receives a number as a string.
My aim is to have the users only able to select the supplied options or desired object type.
Here's an example using Python. Get initial user response and then use a while loop to continue getting responses until they enter a valid response.
Gender2 = input('Gender (M/F):')
while (Gender2 != "M" and Gender2 != "F"):
Gender2 = input('Gender (M/F):')
I'm not a Python coder so my code could be off but this might give you a good idea on how to do this. I usually use PHP or PERL.
The following function should do what you want.
def get_input(message, choices):
assert type(message) == type("string"), "Message must be a string"
assert type(choices) == type([]), "Choices must be an array"
choice = ""
out = message + " (" + "/".join(choices) + "): "
while True:
c = input(out)
if c in choices:
break
else:
print "Please enter a valid choice"
return c
Simply call it like the following:
get_input("Gender", ["M","F"])
Some test calls:
Gender (M/F): asdf
Please enter a valid choice
Gender (M/F): 234
Please enter a valid choice
Gender (M/F): 1
Please enter a valid choice
Gender (M/F): 534
Please enter a valid choice
Gender (M/F): zxcv
Please enter a valid choice
Gender (M/F): Ff
Please enter a valid choice
Gender (M/F): Mm
Please enter a valid choice
Gender (M/F): m
Please enter a valid choice
Gender (M/F): f
Please enter a valid choice
Gender (M/F): M
'M'

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.")

I am writing a script that contains a name validation, but it keeps looping

letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
userName = input('Please enter your name: ')
def NameValidation(userName):
nameValidation = []
print(nameValidation)
nameValidation += username.lower()
print(nameValidation)
for x in range(len(nameValidation)):
if nameValidation[x] not in letters:
print('I\'m sorry, I can\'t accept that')
userName = input('Please enter your name: ')
NameValidation(userName)
NameValidation(userName)
This script will allow you to continue if you are correct on the first time, but if you give an input as string in the userName which any letter of enter string doesn't contain in letter List, you won't be able to continue to the next part. When it loops back and asks you again what are your userName, even if it fits the requirements, the script won't let you continue onto the next part of the script.
your code keeps looping because of recursion. Let, Input is sakib123 then your code take sakib1 then Output I'm sorry, I can't accept that. so then you give again New Input, the nameValidation is new_Input + 23. That's why it keeps looping. :)
You can try this code. :) :)
letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
userName = input('Please enter your name: ')
def NameValidation(userName):
nameValidation = ''
print (nameValidation)
nameValidation += userName.lower()
print (nameValidation)
flag = True
for x in range(len(nameValidation)):
if nameValidation[x] not in letters:
print('I\'m sorry, I can\'t accept that')
flag = False
break
if not flag:
userName = input('Please enter your name: ')
NameValidation(userName)
NameValidation(userName)

Resources