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