I want to get user input of a code that has to be 11 numbers long and must not contain any characters. Otherwise the question to enter will be repeated.
code=input("Please enter your code ")
while len((code)) !=11: #here should be something to nullify strings inout :)
code = input("Please enter your code and in numbers only ")
There is definitely a better solution for this, just can't think of any.
This might be what you're after
def validate(s):
for char in s: #iterate through string
if not char.isdigit(): # checks if character is not a number
return False # if it's not a number then return False
return True # if the string passes with no issues return True
def enter_code():
while True: #Will keep running until break is reached
code = input("Please enter your code: ") #get user input
# if the length of input and it passes the validate then print 'Your code is valid'
if len(code) == 11 and validate(code):
print('Your code is valid')
break #break out of loop if valid
# if code fails test then print 'Your code is invalid' and return to start of while loop
print('Your code is invalid')
if __name__ == '__main__':
enter_code()
Related
I'm trying to make a program that tests the strength of a password. Right now, everything else works, however the numbers doesn't. I can't test whether a string is a number without it not returning the last print statement. I probably haven't explained it well, but how can I make it so that it tests if a characer in a string is a number?
error_list = ['']
errors = ''
password = str(input('Enter in your password to test: '))
for char in password:
if type(char) == int:
safe_unsafe.append('y')
else:
safe_unsafe.append('n')
if 'y' in safe_unsafe:
pass
else:
errors = errors + 'No instance of a number was found.\n'
error_list.append('number')
safe_unsafe.clear()
print(errors)
You are looking for isdigit() API
https://docs.python.org/3.8/library/stdtypes.html#str.isdigit
Example
str = "1"
str.isdigit() #this return True
"a".isdigit() #return False
Updates in your code
error_list = ['']
errors = ''
password = str(input('Enter in your password to test: '))
for char in password:
if char.isdigit(): #changed line
safe_unsafe.append('y')
else:
safe_unsafe.append('n')
if 'y' in safe_unsafe:
pass
else:
errors = errors + 'No instance of a number was found.\n'
error_list.append('number')
safe_unsafe.clear()
print(errors)
So I'm making a game of hangman and it starts with a "BotMaster" entering a string and then how many guesses that player will have to try and guess the string. I only just started and I'm trying to write a function that will check if what the BotMaster put is a valid string. A valid string would be a string that is only letters, no symbols, numbers, or extra spaces. I already have the functions that will remove extra spaces, and non-alpha inputs (So it takes out periods, extra spaces and such) and a function that makes it all lower case, but my function breaks if I enter a number an empty string. How should I add these?
#Imports (this is for later code I haven't written)
import os,time,random
#Removes extra spaces from the function
def space_cull(the_str):
result = the_str
result = result.strip()
result =" ".join(result.split())
the_str = result
return the_str
#Makes the string lowercase
def make_lower(the_str):
the_str = the_str.lower()
return the_str
#Checks if everything in the string are Alpha Inputs
def check_alpha(the_str):
the_str =''.join([char for char in the_str if char.isalnum()])
return the_str
#Ask Botmaster the string they want
def ask_bot():
while True:
bot_str = input('Enter a string for the player to guess: ')
bot_str = space_cull(bot_str)
bot_str = make_lower(bot_str)
bot_str = check_alpha(bot_str)
if bot_str == '':
print('That is not a correct string, try again')
True
return bot_str
ask_bot()
I added the ask_bot() part so I can test the function faster
This is what happens:
Enter a string for the player to guess: 1
#nothing
#Tested again:
Enter a string for the player to guess: ''
That is not a correct string, try again.
#But then exits the loop, which I don't want it to, if the string is wrong I want it to ask them again.
#Tested Again
Enter a string for the player to guess: 'Katze'
#Nothing, which is actually good this time
How do I fix this?
Your while loop will always terminate in the function as it is written.
def ask_bot():
while True:
bot_str = input('Enter a string for the player to guess: ')
bot_str = space_cull(bot_str)
bot_str = make_lower(bot_str)
bot_str = check_alpha(bot_str)
if bot_str == '':
print('That is not a correct string, try again')
True # <- this does nothing
return bot_str # < - this breaks out of the function and the loop
Your code edited to work:
def ask_bot():
while True:
bot_str = input('Enter a string for the player to guess: ')
bot_str = space_cull(bot_str)
bot_str = make_lower(bot_str)
bot_str = check_alpha(bot_str)
if bot_str == '':
print('That is not a correct string, try again')
else: # returns the string if the input is correct
return bot_str # this still breaks out of the function and the loop
# but only if the string has passed the checks
As other answers already mention, you could use str.isalpha() to check that the string is valid, or if you would like to modify the string in place you will need to adjust your check_alpha function like so:
def check_alpha(the_str):
the_str =''.join([char for char in the_str if char.isalpha()])
return the_str
As John Gordon already mentioned the solution is the method "isalpha" of the "str" class.
userInput = input("Your suggestion: ")
if userInput.isalpha():
# do some magic
else:
print("please only type in letters")
You don't need the check_alpha(str) function at all. Modify the ask_bot() as follows.
def ask_bot():
while True:
bot_str = input('Enter a string for the player to guess: ')
bot_str = space_cull(bot_str)
bot_str = make_lower(bot_str)
if not bot_str.isalpha():
if bot_str.isnum():
print("The entered string is a number")
continue
if bot_str == '':
print('That is not a correct string, try again')
continue
continue
break
return bot_str
ask_bot()
this is my password checker code (whether it is valid or not)
I need to run the password checker for 5 times, until it's valid.
If it's valid, I have to break out of the loop.
The password should be more than 7 characters.
The password needs to include both numbers (at least two) and characters.
(If not, return False)
There should be no space.
If there is anything else than numbers and characters, I need to return False
I need to run my password_checker function in the for loop,
but I'm not so sure what to say after 'if'.
I have tried -
if a=False:
print(password_checker(i))
print(Invalid password)
but it didn't work.
Also, I don't understand how should I call my password_checker() in the for loop.
Finally, I need to put a break in my for loop
if the password in the input is valid.
But I'm not sure where is the appropriate part to place it
def password_checker(password):
a=True
num_Count = 0
if password.isalpha() == True:
print ("error! needs numbers")
a = False
if password.isnum() == True:
print ("error! needs characters")
a = False
if password.isspace() == True:
print ("error! no space allowed")
a = False
if len(password)<=8:
print ("error! needs more than 8 characters")
a = False
for i in range(0, 10):
num_Count += password.count(i)
if num_Count(password.count()) < 2:
print("error! needs at least 2 numbers")
a = False
password = str(input("Enter password: "))
for i in range(0,5):
if ____________________:
print(password_checker(i))
print("Invalid password")
else:
print(password_checker(i))
print("Valid password")
break
How should I correct my code in order to make my function work?
for i in range(0,5):
password = str(input("Enter password: "))
password_checker_result = password_checker(password)
if not password_checker_result:
print("Invalid password")
else:
print("Valid password")
break
This code will work for you, now let me explain:
The flow is as following:
This is done 5 times (is inside the for loop):
1) Request password from user.
2) Check if password is valid.
3) Print according to valid/not valid result.
The fact that you are using a for loop does not require you to actually use the iteration index (meaning 'i' in our case)
This is my first coding class and I'm a little confused...
Im looking to write a program that prompts for a phone number and determines whether or not it's a valid 10-digit number by ignoring any punctuation. I have to write a function that takes the phone number string as a parameter and returns True if it is valid, and False if not. I also have to use a loop to iterate over the string and increment counter whenever I see a digit.
I'm not sure this is correct , but this is what I came with so far. I'm not sure how to create a loop to iterate over a string to determine True or False phone numbers.
main():
phone_number= input("Please enter a phone number in the format XXX-XXX-XXXX: ")
validNumber(phone_number)
def validNumber(phone_number):
for i,c in enumerate(phone_number):
if i in [3,7]:
if c!= "-":
phone_number=input("Please inter a valid phone number:")
return False
elif
How about think the solution with step-by-step?
Check the number of "-" that split the number to three part.
Check the length of each XXX(or XXXX) at XXX-XXX-XXXX, if the each XXX has appropriate length(3, 3 and 4)
Check if each XXX(or XXXX) is decimal or not.
The code can be like:
def validNumber(phone_number):
p_num_list = phone_number.split('-') # get list of each XXX
if len(p_num_list) is not 3: # if the number has 3 part
return False
else:
if len(p_num_list[0]) is not 3: # Check length of each part
return False
if len(p_num_list[1]) is not 3:
return False
if len(p_num_list[2]) is not 4:
return False
if p_num_list[0].isdecimal() and p_num_list[1].isdecimal() and p_num_list[2].isdecimal(): # check if each part is decimal
return True
return False
if __name__ == '__main__':
p_num = input("Enter the phone number : ")
print(validNumber(p_num))
You could try something like this:
def valid_number(phone_number):
try:
number = [str(int(i)) for i in phone_number.split('-')]
except:
print('Error, only numbers allowed')
number = ''
if len(''.join(number)) == 10:
print('This is a valid phone number')
return True
else:
print('This is not a valid phone number')
return False
def main():
phone_number = input('Enter number in format xxx-xxx-xxxx: ')
valid_number(phone_number)
if __name__ == '__main__':
main()
int() is trying to convert the string into an integer, if it fails, its not a number, then it checks whether the number is 10 characters long or not returning then True or False.
OK so what I need to do is make my code only allow the user to enter one letter and then one symbol at a time. The example below shows what I want in a better view.
At the moment my code allows the user to enter more than one character at a time which I don't want.
What letter would you like to add? hello
What symbol would you like to pair with hello
The pairing has been added
['A#', 'M*', 'N', 'HELLOhello']
What I want is a message to be displayed like this and the pairing not to be added to the list.
What letter would you like to add? hello
What symbol would you like to pair with hello
You have entered more than one character, the pairing was not added
['A#', 'M*', 'N',].
So far my code for this section is as follows...
It would also be great for when the user enters a number in the letter section, an error message to be printed.
def add_pairing(clues):
addClue = False
letter=input("What letter would you like to add? ").upper()
symbol=input("\nWhat symbol would you like to pair with ")
userInput= letter + symbol
if userInput in clues:
print("The letter either doesn't exist or has already been entered ")
elif len(userInput) ==1:
print("You can only enter one character")
else:
newClue = letter + symbol
addClue = True
if addClue == True:
clues.append(newClue)
print("The pairing has been added")
print (clues)
return clues
The easiest way to ensure user input is with a loop:
while True:
something = raw_input(prompt)
if condition: break
Something set up like this will continue to ask prompt until condition is met. You can make condition anything you want to test for, so for you, it would be len(something) != 1
Your method can be simplified to the following if you let the user enter a letter and symbol pair:
def add_pairing(clues):
pairing = input("Please enter your letter and symbol pairs, separated by a space: ")
clues = pairing.upper().split()
print('Your pairings are: {}'.format(clues))
return clues
Not exactly sure what you want to return but this will check all the entries:
def add_pairing(clues):
addClue = False
while True:
inp = input("Enter a letter followed by a symbol, separated by a space? ").upper().split()
if len(inp) != 2: # make sure we only have two entries
print ("Incorrect amount of characters")
continue
if not inp[0].isalpha() or len(inp[0]) > 1: # must be a letter and have a length of 1
print ("Invalid letter input")
continue
if inp[1].isalpha() or inp[1].isdigit(): # must be anything except a digit of a letter
print ("Invalid character input")
continue
userInput = inp[0] + inp[1] # all good add letter to symbol
if userInput in clues:
print("The letter either doesn't exist or has already been entered ")
else:
newClue = userInput
addClue = True
if addClue:
clues.append(newClue)
print("The pairing has been added")
print (clues)
return clues
I am fan of raising and catching exceptions in similar cases. Might be shocking for people with 'C-ish' background (sloooow), but it is perfectly pythonic and quite readable and flexibile in my opinion.
Also, you should add check for characters outside of set you are expecting:
import string
def read_paring():
letters = string.ascii_uppercase
symbols = '*##$%^&*' # whatever you want to allow
letter = input("What letter would you like to add? ").upper()
if (len(letter) != 1) or (letter not in letters):
raise ValueError("Only a single letter is allowed")
msg = "What symbol would you like to pair with '{}'? ".format(letter)
symbol = input(msg).upper()
if (len(symbol) != 1) or (symbol not in symbols):
raise ValueError("Only one of '{}' is allowed".format(symbols))
return (letter, symbol)
def add_pairing(clues):
while True:
try:
letter, symbol = read_paring()
new_clue = letter + symbol
if new_clue in clues:
raise ValueError("This pairing already exists")
break # everything is ok
except ValueError as err:
print(err.message)
print("Try again:")
continue
# do whatever you want with letter and symbol
clues.append(new_clue)
print(new_clue)
return clues