Iterations and print out message for error - python

For a python Bootcamp, I am working on a program which repeatedly asks for the input of a "name" and prints out it out.
When the user enters "bob", the program must print out "oh, not you, bob!", and print out the shortest and longest names previously entered.
If the user enters anything other than a string of characters (for instance, numbers), program must print out an error message and continue on to ask for a name again.
I don't know how to print out an error message when the user enters an int, a float, or something else than a string like 'romeo"
Please see below my program :
`new_name = ''
while new_name != 'bob':
#Ask the user for a name.
new_name = input("Please tell me someone I should know, or enter 'quit': ")
print('hey', new_name, 'good to see you')
if new_name != 'bob':
names.append(new_name)
largest = None
for name in names:
if largest is None or len(name) > len(largest) :
largest = name
smallest = None
for name in names:
if smallest is None or len(name) < len(smallest) :
smallest = name
print ('oh, not you, bob')
print ("The smallest name previously entered is :", smallest)
print("The largest name previously entered is :", largest)
Thank you very much for your help

Try to convert your input to a int if it works its a number.
try:
user_number = int(input("Enter a name: "))
except ValueError:
print("That's a good name!")

You can check if user input contains only letters:
if not new_name.isalpha():
print 'Only letters are allowed!'
Note: whitespace is also treated as forbidden character.

Related

Trying to validate a text input, so it allows characters in the alphabet only as the input but I'm having problems. (Python)

So, I have a homework where I'm assigned to write multiple python codes to accomplish certain tasks.
one of them is: Prompt user to input a text and an integer value. Repeat the string n
times and assign the result to a variable.
It's also mentioned that the code should be written in a way to avoid any errors (inputting integer when asked for text...)
Keep in mind this is the first time in my life I've attempted to write any code (I've looked up instructions for guidance)
import string
allowed_chars = string.ascii_letters + "'" + "-" + " "
allowed_chars.isalpha()
x = int
y = str
z = x and y
while True:
try:
x = int(input("Enter an integer: "))
except ValueError:
print("Please enter a valid integer: ")
continue
else:
break
while True:
try:
answer = str
y = answer(input("Enter a text: "))
except ValueError:
print("Please enter a valid text")
continue
else:
print(x*y)
break
This is what I got, validating the integer is working, but I can't validate the input for the text, it completes the operation for whatever input. I tried using the ".isalpha()" but it always results in "str is not callable"
I'm also a bit confused on the assigning the result to a variable part.
Any help would be greatly appreciated.
Looks like you are on the right track, but you have a lot of extra confusing items. I believe your real question is: how do I enforce alpha character string inputs?
In that case input() in python always returns a string.
So in your first case if you put in a valid integer say number 1, it actually returns "1". But then you try to convert it to an integer and if it fails the conversion you ask the user to try again.
In the second case, you have a lot of extra stuff. You only need to get the returned user input string y and check if is has only alpha characters in it. See below.
while True:
x = input("Enter an integer: ")
try:
x = int(x)
except ValueError:
print("Please enter a valid integer: ")
continue
break
while True:
y = input("Enter a text: ")
if not y.isalpha():
print("Please enter a valid text")
continue
else:
print(x*y)
break

How do I check the user has entered two or more words in a single string?

My function takes a string, and as long as the string has two names in it, such as "John Smith", the program runs OK.
My issue occurs when the user enters 1 or less names in their input.
user_input = input("Enter your name: ")
name = user_input.split()
print(name[0])
print(name[1])
Ideally, it would check that the user has entered a string of just two names, but it doesn't really matter.
I don't know the required checks in Python; if it was Java, it would be a different story.
You could use len() or try/except as in:
user_input = input("Enter your name: ")
if len(user_input.split()) > 1:
print("At least two words.")
else:
print("Only one word")
Or
user_input = input("Enter your name: ")
try:
user_input.split()[1]
print("At least two words.")
except IndexError:
print("Only one word")
user_input = input("Enter your name: ")
name = user_input.split()
for x in names:
print(x)

Why am I getting this bad input?

Trying to create code which two users input their names, if the length of the strings is an even number then the strings are printed, if the length of the strings are an odd number then the strings will not print their names.
#Creating the inputs
first_input = input('Please insert your first name:')
second_input = input('Please insert your last name:')
if:
if len(first_input)%2==0:
print('first_input')
if len(second_input)%2==0:
print('second_input')
else:
print('The name cannot be printed')
Output
Line 7: SyntaxError: bad input (':')
Your IF statement isn't clear.
Try with this
first_input = input('Please insert your first name:')
second_input = input('Please insert your last name:')
if len(first_input)%2==0:
print(first_input)
if len(second_input)%2==0:
print(second_input)
You can add the ELSE clause for each of these IF according to your logic
is because you are not passing a condition to evaluate on the first if statement
if: <------------This if statement doesn't have a condition
if len(first_input)%2==0:
print('first_input')
if len(second_input)%2==0:
print('second_input')
else:
print('The name cannot be printed')
try this:
first = input('first name ')
second = input('second name ')
if (len(first)%2 == 0 and len(second)%2 == 0 ):
print("the string is printed ", first , " ", second)
else:
print("the string cannot be printed")
output
first name carlos
second name even
the string is printed carlos even
second test
first name carol
second name noteven
the string cannot be printed

How to Make a Dictionary Accept any Integer to Trigger a Function

Let's say you have the following code:
def statementz():
print("You typed in", number)
digits = {
56 : statementz
}
while True:
try:
number = int(input("Enter a number: "))
except TypeError:
print("Invalid. Try again.\n")
continue
else:
digits.get(number, lambda : None)()
break
I am wondering if there is a way so that one could allow the dictionary to trigger the "statementz" function if the variable "number" holds the value of any integer/float, and not just the integer that is given in the (rather sloppy) example above.
Is it possible to do this? Thank you in advance for any guidance given!
If you want any number to be passed to statementz(), you can simply call it directly after validating it as a number. A dict is only useful if you want to map different numbers to different functions, which is not the behavior you are asking for. Also note that your statementz() should take a number as a parameter since you want to print the number in the function:
def statementz(number):
print("You typed in", number)
while True:
try:
number = float(input("Enter a number: "))
statementz(number)
except TypeError:
print("Invalid. Try again.\n")
Without try-except:
Try using:
def statementz(number):
print("You typed in", number)
while True:
number = input("Enter a number: ")
if number.isdigit():
statementz(number)
break
else:
print("Invalid. Try again.\n")
Example Output:
Enter a number: Apple
Invalid. Try again.
Enter a number: 12ab
Invalid. Try again.
Enter a number: --41-
Invalid. Try again.
Enter a number: 24
You typed in 24

creating a code that use .isdigit

I'm new to python. I was creating a code that use .isdigit. It goes like this:
a = int(input("Enter 1st number: "))
if 'a'.isdigit():
b = int(input("Enter 2nd number: "))
else:
print "Your input is invalid."
But when I enter an alphabet, it doesn't come out the "Your input is invalid.
And if I entered a digit, it doesn't show the b, 'Enter 2nd number'.
Is there anyway anyone out there can help me see what's the issue with my code.
That will be a great help. Thanks.
You are assigning the input to a variable a, but when you try to query it with isdigit() you're actually querying a string 'a', not the variable you created.
Also, you are forcing a conversion to an int before you've even checked if it's an int. If you need to convert it to an int, you should do that after you run the .isdigit() check:
a = raw_input("Enter 1st number: ")
if a.isdigit():
a = int(a)
b = int(raw_input("Enter 2nd number: "))
else:
print("Your input is invalid.")
Try to convert your a variable to string type, like this:
a = int(input("Enter 1st number: "))
if str(a).isdigit():
b = int(input("Enter 2nd number: "))
else:
print("Your input is invalid.")

Categories

Resources