Why am I getting this bad input? - python

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

Related

Default output of input

I'm trying to make a sample code that extracts first name from a full name.
If my input is not string or simply press just enter, it will print out enter valid name.
But no matter what I type, it just prints out normal outcome.
Also if I type nothing, it just makes an error.
How can I solve this?
name = input("Enter your full name (end to stop): ")
def print_first_name():
if type(name) == str:
name.split()
first = name.split()[0]
last = name.split()[-1]
print('Your first name is: ', first)
elif name == 'end':
break
else:
print('You must enter at least your first name!')
print_first_name()
name = input("Enter your full name: ")
def print_first_name():
if len(name) > 0:
first = name.split()[0]
if first.isalpha():
print('Your first name is: ', first)
else:
print("Enter a valid name")
last = name.split()[-1]
else:
print('You must enter at least your first name!')
print_first_name()
The condition you wrote (type(name)==str) will always be true
we cant use break outside a loop. (in your case, there was no loop at all, so u cant use break)
if you enter nothing, it gives an error because the line
name.split()[0]
if name="", (which means an empty string), name.split() gives an empty list
In a empty list, there will be no element at index 0, so it gives an error.
When you say if type(name) == str:, then even when you type end as input, this condition is satisfied and the if block is executed and hence code flow never goes to the elif block.
You can put your else condition first and then the if condition:
if name == 'end':
#do whatever
elif type(name) == str:
#do whatever
else:
print('Invalid input')
Your code has a few problems, marked with comments below:
name = input("Enter your full name (end to stop): ")
# Generally you should pass a variable to a function
# or define the variable inside the function, rather
# than using a global variable (name). It's not clear
# which part of the code you want to isolate in a
# function in this example, so it's probably simplest
# not to use a function at all.
def print_first_name():
# The next test will always be True, so the else
# and elif parts will never run.
# You probably want a test for non-empty
# strings with only alphabetic characters instead
if type(name) == str:
# the next line creates a list of the parts of
# name (if possible) but doesn't store it
# anywhere, so it has no effect.
name.split()
# the next two lines will fail if name is
# an empty string
first = name.split()[0]
last = name.split()[-1]
print('Your first name is: ', first)
# the next block needs to be moved earlier to
# make sure it is tested before you try to extract
# the names
elif name == 'end':
# break cannot be used inside a function
# even if the function is called in a loop
break
else:
print('You must enter at least your first name!')
print_first_name()
Here's a version that fixes these problems:
while True:
name = input("Enter your full name (end to stop): ")
# check this first, to avoid treating as a name
if name == 'end':
break
# check whether name contains any digits or is empty
elif name.isalpha() and name != "":
name_parts = name.split()
first = name_parts[0]
last = name_parts[-1]
print('Your first name is: ', first)
else:
print('You must enter at least your first name!')
input() defaults to returning a string type. It looks like you're trying to sanitize the input by making sure the input is a string of letters, and also has a length > 0 before running.
You would probably be served by flipping out
if type(name) == str:
with something that checks both for a non-zero AND alpha only. so something like
if name.isalpha() and len(name) > 0:
{conditional code here...}
The input is always string, so you can use a array or list to store 0 -> 9 numbers (The str one). If there is a number in input, it'll print something.
You can use '' to describe that input is empty

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)

How would I loop this on Python?

How would I loop this code to make it so that the user inputs the number of friends they have, their names, and in the end, the program will be able to output the information? This is what I have so far, but I believe it's incorrect.
Friends = int(input("Please enter number of friends")
for i in range(Friends):
Name = input("Please enter friend number 1:")
Append each name to a list, then print the list. And use string formatting to put an appropriate number in the prompt.
friendList = []
Friends = int(input("Please enter number of friends")
for i in range(Friends):
Name = input("Please enter friend number %d: " % (i+1))
friendList.append(Name)
print(friendList)
Loop using the number of friends, and store the name for each of them:
friend_count = int(input("Please enter number of friends: "))
friend_list = []
for friend_index in range(friend_count):
name = input("Please enter friend number {}: ".format(friend_index + 1))
friend_list.append(name)
print(friend_list)
Here a try using list comprehension:
Friends = int(input("Please enter number of friends :"))
Names = [input("Please enter friend number {}:".format(i)) for i in range(1,Friends+1)]
print(Names)
You can use raw_input, from the documentation
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
Code
name_array = list()
num_friends = raw_input("Please enter number of friends:")
print 'Enter Name(s): '
for i in range(int(num_friends)):
n = raw_input("Name :")
name_array.append((n))
print 'Names: ',name_array

Iterations and print out message for error

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.

I need to multiply every other number by 3 but dont know what i'm doing wrong

print("Welcome")
barcode1 = input("Please enter your first digit")
barcode2 = input("Please enter your second digit")
barcode3 = input("Please enter your third digit")
barcode4 = input("Please enter your fourth digit")
barcode5 = input("Please enter your fifth digit")
barcode6 = input("Please enter your sixth digit")
barcode7 = input("Please enter your seventh digit")
barcode1 = barcode1*3
print(barcode1)
Instead of the number being multiplied by 3, the solution comes out as 111
You could do it like that:
codes = []
i = 0
while True:
try:
codes.append(int(input("Please input your Barcode {}: ".format(i))) * 3)
if i == 6: break
i += 1
except ValueError:
print("Something went wrong!")
print(codes)
Add a try-catch statement around it and try to cast your input to int. With that you could also input a string but your script wouldn't crash.
The confusing phenomenon here is that python supports string multiplication as well as integer multiplication! To the inexperienced this may seem confusing, but it's actually a very nice feature. The following can be done:
>>> string = 'hi!'
>>> multiplied_string = string * 4
>>> multiplied_string
"hi!hi!hi!hi!"
So as you can see, multiplying a string repeats its contents n times, where n is the number it is multiplied by.
In your case you're expecting to multiply a numeric value, but the input function is returning a string value instead of a numeric value. That means that when you multiply it, instead of performing numeric multiplication, python does string multiplication.
Simply transform the result of input into an integer by using the int method. Or, you can even write a function to accept numeric input from the user.
def input_int(msg):
'''
Repeatedly asks the user for a valid integer input until a validly
formatted input is provided.
'''
while True:
try:
return int(input(msg))
except:
print('Please enter a numeric input.')
print("Welcome")
barcode1 = input_int("Please enter your first digit")
barcode2 = input_int("Please enter your second digit")
"........"
print(barcode1 * 3)
change barcode1 from a string to an integer, for example:
b1 = int(barcode1)*3
print(b1)

Categories

Resources