at the moment if you put a character instead of a number in the input it gives an ugly error. I would like the script to output something like "Invalid character! Please enter a digit." whats something i can do to fix this?
import random
import string
string.ascii_letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.number_symbols='!##$%^&*()'
userLetterInput = int(input("How many letters would you like in your password?: "))
userSymbolInput = int(input("How many symbols would you like in your password?: "))
letterResult = ''.join([random.choice(string.ascii_letters) for i in range(userLetterInput)])
symbolResult = ''.join([random.choice(string.number_symbols) for i in range(userSymbolInput)])
print("".join(letterResult + symbolResult))
You can use a try/except statement in a loop to catch the exception and display a message for the user. The try/except statement catches the exception thrown when the user enters alphabetic characters, whereas the loop repeats the query for a number until the user gives a valid input.
import random
import string
string.ascii_letters='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.number_symbols='!##$%^&*()'
while True: # Repeat the question until valid input is given
try: # Catch ValueError which gets thrown when letters are entered
userLetterInput = int(input("How many letters would you like in your password?: "))
break # Exit the loop if no exception is thrown
except ValueError:
print("Invalid character! Please enter a digit.")
while True:
try:
userSymbolInput = int(input("How many symbols would you like in your password?: "))
break
except ValueError:
print("Invalid character! Please enter a digit.")
letterResult = ''.join([random.choice(string.ascii_letters) for i in range(userLetterInput)])
symbolResult = ''.join([random.choice(string.number_symbols) for i in range(userSymbolInput)])
print("".join(letterResult + symbolResult))
Instead of using a while True loop, you could of course also declare a boolean (e.g. invalid_input) which is True at first and gets set to False after the user entered a valid number.
you can check input type with "isinstance":
isinstance(1, int)
isinstance('be', str)
Related
I'm a newbie in coding using python and I'm trying to write a piece of small code that prints whatever you input in the terminal, but I don't want anything that only includes spaces and no other characters or doesn't even have an input to be printed. Here's the code:
while True:
my_name= input("> ")
if "" in my_name:
print("I don't know what that means. Please choose a valid answer.")
else:
print(f"Ah, I see, so your name is {my_name}?")
would love to have multiple solutions to this, and thank you if you helped :)
https://docs.python.org/2/library/stdtypes.html#str.isspace
I think this should do the trick
if my_name.isspace():
print("Your name is full of spaces")
Python isspace() method is used to check space in the string. It returns true if there are only white space characters in the string. Otherwise it returns false.
ex:
# Python isspace() method example
# Variable declaration
str = " " # empty string
# Calling function
str2 = str.isspace()
# Displaying result
print(str2)
There's one way of doing that by using exceptional handling for no input using try - except block and a flag variable that checks if input doesn't contain only spaces.
try:
flag = False
my_name = input()
for i in my_name:
if i != ' ':
flag = True
if flag:
print(my_name)
else:
print('Invalid input')
except:
print('No input')
The other ways can be using the built in function strip() which removes the trailing and leading spaces in input.
If the input has only spaces then strip() will remove all of them resulting in an empty string.
try:
my_name = input()
if my_name.strip() == '':
print('Invalid input')
else:
print(my_name)
except:
print('No input')
Like this, you can use bools:
while True:
my_name= input("> ")
if my_name.strip():
print(f"Ah, I see, so your name is {my_name}?")
else:
print("I don't know what that means. Please choose a valid answer.")
I would like to know if the user entered a space before the number. Currently if you push space and then enter a number the program ignores the space and sees it as you just entered a number.
I tried a few methods found on this site but I must be missing something.
import re
while True:
enternum=input('Enter numbers only')
try:
enternum=int(enternum)
except ValueError:
print ('Try again')
continue
conv = str(enternum) # converted it so I can use some of the methods below
if conv[0].isspace(): # I tried this it does not work
print("leading space not allowed")
for ind, val in enumerate(conv):
if (val.isspace()) == True: # I tried this it does not work
print('leading space not allowed')
if re.match(r"\s", conv): # I tried this it does not work (notice you must import re to try this)
print('leading space not allowed')
print('Total items entered', len(conv)) # this does not even recognize the leading space
print ('valid entry')
continue
The problem in your example code is that you convert enternum to an integer (thus removing the spaces) before checking for spaces. If you just check enternum[0].isspace() before converting it to an integer, it will detect the space.
Don't forget to check that the user entered something instead of just pressing enter, otherwise you'll get an IndexError when trying to access enternum[0].
while True:
enternum = input('Enter numbers only')
if not enternum:
print('Must enter number')
continue
if enternum[0].isspace():
print('leading space not allowed')
continue
enternum = int(enternum)
...
You didn't specify why you want to prohibit spaces specifically, so you should consider if that's what you actually want to do. Another option is using enternum.isdecimal() (again, before converting to int) to check if the string only contains decimal digits.
I cannot get the code below to work properly. It works if the user enters numbers for the name and it prints the theName.isdigit. But if the user enters both numbers and letters, it accepts this and moves onto a welcome message that follows. Looking at this, is there a reason you can find why theName.isalnum is not working here but the one above is?
theName = raw_input ("What is your name?? ")
while theName.isdigit ():
if theName.isdigit ():
print "What kind of real name has just numbers in it?? Try again..."
elif theName.isalnum ():
print "What kind of name has any numbers in it?? Please try again..."
elif theName.isalpha ():
print "Ok, great"
break
theName = raw_input ("What is your name?? ")
theName = raw_input ("What is your name?? ")
while not theName.isalpha ():
if theName.isdigit ():
print "What kind of real name has just numbers in it?? Try again..."
elif theName.isalnum ():
print "What kind of name has any numbers in it?? Please try again..."
theName = raw_input ("What is your name?? ")
print "Ok, great"
The while condition should tell you when to stop looping, that is, when the input isalpha. Then, because the while loop stops when the input is correct, you can move the logic for what to do in that case below the loop.
Looping on isdigit is problematic because the string abc123 doesn't meet that condition, so you break out of the loop even though the name doesn't meet your criteria.
As mentioned by others your code has a few problems.
First, if the theName contains anything other than digits, you will never enter the while loop, because isdigit() will return False.
Next, the order of your tests means that you will only reach the isalpha() test if the entered name contains something other than letters or digits.
However, it is also overly complex. Assuming your goal is to get the user to enter a name consisting only of letters (i.e. no spaces, digits, or special characters)
theName = "1" # preseed with invalid value
firstTime = True
while not theName.isalpha():
if not firstTime:
print "Your name should not contain anything other than letters"
theName = raw_input("Please enter your name: ")
firstTime = False
print "OK, great. Hi " + theName
This will repeatedly prompt until the user enters a valid name.
I am currently writing some python code that asks for a users name. I need the program to validate whether the user's input is a string or not. If it is a string, The loop will break and the programme will continue. If the input is not a string (like a float, integer etc), It will loop around and ask the user to input a valid string. I understand that you can use the following code when you are checking for an integer;
while True:
try:
number = int(input("Plese enter a number: "))
break
except ValueError:
print("Please enter a valid integer")
I was thinking that I could use something like this to check for a string;
while True:
try:
word = str(input("Plese enter a string: "))
break
except ValueError:
print("Please enter a valid string")
But as far as I understand, the str() just converts the user's input to a string, regardless of the data that was entered.
Please help!
thanks
Based on the comments, it looks like you want to check if the input consists of alphabetic characters only. You can use .isalpha() method:
while True:
word = input("Please enter a string: ")
if word.isalpha():
# Do something with valid input.
break
else:
print("Please enter a valid string")
I'm getting a string from input() which consists of digits separated by spaces (1 5 6 3). First I'm trying to check that the input only consists of digits with the isdigit() function but because of the spaces I can't get it to work. Then I convert the string to a list using the split() function.
What I need is to make a list from input and make sure it only consists of digits, else send a message and ask for a new input. Is it maybe possible to add a parameter to isdigit() that makes an exception for spaces?
What you're describing is a look before you leap approach, i.e. checking first whether the input is conforming, and then parsing it. It's more pythonic to use a Easier to ask for forgiveness than permission approach, i.e. just do it and handle exceptions:
s = raw_input() # input() in Python 3
try:
numbers = map(int, s.split())
except ValueError:
print('Invalid format')
Probably a lot more complicated than it needs to be but this will return true if the string consists of only digits:
not sum([not i.isdigit() for i in thestring.split()])
You should try converting and, upon exception ask again. This is how I'd do it. (I've included a Ctrl+c escape to avoid being locked in the loop.
import sys
list = None
while True:
try:
print "Enter your digits : ",
content = raw_input()
list = [int(x) for x in content.strip().split(" ")]
break
except KeyboardInterrupt: # Presses Ctrl+C
print "Exiting due to keyboard interrupt"
sys.exit(-1)
except:
print "Bad content, only digits separated by spaces"
print list