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
Related
ip_address = input().split(".")
if ip_address[0] >= 0 and ip_address[0].isnumeric() and ip_address[0] <=255:
print("Valid first byte")
else:
print("Invalid first byte")
In this code, when I add my final condition of ip_address[0] <=255 I always get my byte as invalid even though it would technically fit those parameters. For example, I've tried inputs 0 and 127 but they come up as invalid, but if I remove the last condition they are valid. Where am I going wrong?
I've tried putting it as ip_address[0] < 256 but this hasn't worked either.
The value returned by input() is always a string. When you use .split('.') you then get a list of strings.
To test the range of the number you will need to convert it to int first, but even before that you can use the numeric check:
ip_address = input().split(".")
if ip_address[0].isnumeric() and (0 <= int(ip_address[0]) <= 255):
print("Valid first byte")
else:
print("Invalid first byte")
ip_address = input().split(".")
print(ip_address)
if ip_address[0].isnumeric() and int(ip_address[0]) >= 0 and int(ip_address[0] )<=255:
print("Valid first byte")
else:
print("Invalid first byte")
Try this
when you input some ip address: 192.168.2.3
['192'.'168'.'2'.'3'] it will be converted to list of strings .
you cannot compare strings with numbers . so you have to convert
string to int to compare.
You can try this code:
ip_address = int(input().split(".")[0])
if ip_address >= 0 and ip_address <=255:
print("Valid first byte")
else:
print("Invalid first byte")
Explanation: It first coverts the input() to int() and then it checks for the conditions.
Conclusion: Your code was not converting the input() to int() and that is the main reason for the error!
In your code you are testing a string (e.g. "255") with and integer (255) and that is why your test is failing.
It might also we useful to separate the requesting input from the testing of the inputted value.
For example, in the code below the main() function is where the code requests input from the user. It will continue to ask until the user enters a correct ip address.
The is_valid_ip_address return None until the address is valid when it will return a list of the four values.
This allows for easier test (example given) and better error messages for the user.
def is_valid_ip_address(ip_address):
parts = ip_address.split(".")
# is numeric
if not all([part.isnumeric() for part in parts]):
print("Error: Not all parts are numeric values")
return
# Test there are four parts
if len(parts) != 4:
print("Error: There needs to be four parts to the ip address")
return
# convert parts to integer for easy comparison
parts = list(map(int, parts))
# Test all parts in valid range
for idx, part in enumerate(parts):
if not 0 < part < 255:
print(f"Error: Part {idx + 1} is not in valid range")
return
return parts
def run_tests():
test_values = [
"192.168.2.300",
"192.168.2.3",
"192.168",
"dave"
]
for test_ip in test_values:
print(f"\nTesting: {test_ip}")
is_valid_ip_address(test_ip)
def main():
ip_address = None
while ip_address is None:
entered_value = input("Enter an IP address: ")
ip_address = is_valid_ip_address(entered_value)
print(f"You entered a valid address")
if __name__ == '__main__':
run_tests()
main()
Here's my code:
#Greeting
print('\n---Sales Discount Calculator---\n')
#User Input
packageCount = input('Packages Purchased: ')
#To check whether packageCount is an integer or not
#loop continues until a positive integer is inputted
validInput = False
while (validInput == False):
if (packageCount.isdigit()):
packageCount = int(packageCount)
if (packageCount != 0):
validInput = True
print(packageCount)
else:
print('Invalid Input. Try again...')
packageCount = input('Packages Purchased: ')
I'm trying to see if the input from the user is a positive integer and also not a zero. I need to check if it's an integer first(the first if-statement) because you can't compare type string to numbers. If it is an integer, then I need to check if it is a zero or not(second if-statement). When the second if-statement is not present, the code checks for both a positive integer and if it's a string or not, but somehow when I include the second if statement and type in a string, it continues without printing the 'Invalid Input'(the else). *This causes issues later on.
This is because you have two seperate if-else statements. So the first checks for a digit, and sets packageCount to an int explicitly, however if this isn't hit then packageCount stays as a string and continues into the next if statement either way
if (packageCount != 0):
I believe you probably want to indent this in so your code becomes:
#Greeting
print('\n---Sales Discount Calculator---\n')
#User Input
packageCount = input('Packages Purchased: ')
#To check whether packageCount is an integer or not
#loop continues until a positive integer is inputted
validInput = False
while (validInput == False):
if (packageCount.isdigit()):
packageCount = int(packageCount)
if (packageCount != 0):
validInput = True
print(packageCount)
else:
print('Invalid Input. Try again...')
packageCount = input('Packages Purchased: ')
else:
print('Invalid Input. Try again...')
packageCount = input('Packages Purchased: ')
You will notice you now have repeated code, but I will leave that to you to remove :)
---edit---
The extra indents we have added ensures the second if-else is only called if the first is successful. The reason I've added a new else in is so that the error message and input request is maintained.
So the first if checks for an integer, if this fails (ie. the input was a string), then we hit the second else.
If this succeeds we then check if packageCount != 0 and either succeed or hit the first else in the code.
I have worked on many projects (school projects, I'm not too advanced), and have found that in many programs where I require the user to input a value that is an integer, or decimal(float), I need to use a "try-except" statement, within a while loop, in order to make certain that the user inputs the required value type.
For example:
def main():
userValue = input("Please enter an integer: ")
while(True):
try:
userValue = int(userValue)
break
except:
userValue = input("That is not an integer, try again: ")
print("The integer you entered is: " + str(userValue))
main()
# Input: SADASD (A non-integer value)
# Output: "That is not an integer, try again: "
# Second-Input: 3
# Second-Output: "The integer you entered is: 3"
Understandably, typing out this entire section of code repeatedly, in a program that requires user input multiple times, is not really efficient. So understanding, that user-defined functions help when I need to perform one action, multiple times. With this in mind, I defined my own function with that same try-except statement in a while loop. However, now, when I use the function, instead of printing the same output previously, rather, it prints out the first value the user had input.
For example:
def valueCheck_Integer(userInput):
while(True):
try:
userInput= int(userInput)
break
except:
userInput = input("That is not an integer, try again: ")
def main():
userValue = input("Please enter an integer: ")
valueCheck_Integer(userValue)
print("The integer you entered is: " + str(userValue))
main()
# Input: SADASD (A non-integer value)
# Output: "That is not an integer, try again: "
# Second-Input: SASASD
# Second-Output: "That is not an integer, try again: "
# Third-Input: 3
# Third-Output: SADASD (The first value that the user Input, instead of 3)
Can someone please explain to me why this happens, and some suggestions on how to fix it?
Thank you!
It's probably going to be easier to expect the function to get/check/return the integer rather than check input you already have. You can pass it the string to use for asking for the value (you could also pass the error string). It will keep asking until it's successful and then return the number you want:
def get_integer(question):
while(True):
try:
return int(input(question))
except ValueError:
question = "That is not an integer, try again:"
def main():
userValue = get_integer("Please enter an integer: ")
print("The integer you entered is: " + str(userValue))
main()
It is because of you are printing userValue instead of userInput.
I used return make it easier. So the code will be like this
def valueCheck_Integer(userInput):
while(True):
try:
userInput= int(userInput)
break
except:
userInput = input("That is not an integer, try again: ")
return userInput
def main():
userValue = input("Please enter an integer: ")
print("The integer you entered is: " + str(valueCheck_Integer(userValue)))
main()
You can make your code smaller like this:
def valueCheck_Integer(userInput):
while not(userInput.isdigit()):
userInput = input("That is not an integer, try again: ")
return userInput
def main():
userValue = input("Please enter an integer: ")
print("The integer you entered is: " + str(valueCheck_Integer(userValue)))
main()
First off, Good Question.
To understand what is going on, we first have to talk about scope of a variable.
When you define a variable outside a function, it becomes something called a global variable. This basically means that you can access it from anywhere in your code. When you define the variable within a function, it becomes a local variable. This means that it is only accessible from within your function. Finally, when a function gets passed in a variable, it gets its own local copy of the variable to work with.
Now let's look at your code.
when you call valueCheck_Integer(userInput): the function gets its own copy of userInput to work with. thus all the changes that the function does modifies the local userInput while the global userInput stays the same. As such, when the user enters a correct answer, the global userInput is the one that gets printed and the changes the function makes to local userInput is lost.
So, how can we fix this?
There are two main methods:
1)Using the global keyword
def valueCheck_Integer(userInput):
global userInput
while(True):
try:
userInput= int(userInput)
break
except:
userInput = input("That is not an integer, try again: ")
This keyword asks the function to modify the global userInput
2)Returning a value
def valueCheck_Integer(userInput):
while(True):
try:
userInput= int(userInput)
break
except:
userInput = input("That is not an integer, try again: ")
return userInput
def main():
userValue = input("Please enter an integer: ")
print("The integer you entered is: " + str(valueCheck_Integer(userValue)))
main()
This works by returning the local copy of userInput and modifying global userInput to equal local userInput
The second code I used was from
Osadhi Virochana Jayasinghe Si's answer.
It's because, if you see your line of code where you print the final output -:
print("The integer you entered is: " + str(userValue))
you will realise that the value you are printing is the one you take the first time from the input function. But this is not the value you have been working on to achieve in your other function.
So for you to rather get that value, the function in some way has to return it back to you.
For this you should allow the function to return the value in the last line.
like so -:
return userInput
and then change the line where you call function so it saves the value returned.
like so -:
userValue = valueCheck_Integer(userValue)
Also as mentioned by others using the global keyword you can define the variable in global scope.
But this is really not a good practice until really needed as it can increase the amount of space that the var is taking, before the variable only took the space for a limited time for when the function is called, but now the variable takes space throughout the time the program runs.
While return will not do so as it will only return the value and once assigned to the already defined variable it will remove the returned value from space.
This should hopefully fix your problem.
I hope this helps.
And also hope that you're safe during the time of this ongoing pandemic.
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
New to coding...
i am a student and have been tasked with writing a code that asks the user to input a series of values that will i will store in a list and then to ask to input a value (continue this until user types done) and then to check to determine if it is found in the list of valid values.
I'm assuming this could be done with a while true loop to accomplish the input until 'done' is typed and i'm assuming a search using 'if' and 'in' would accomplish the second part.
I am struggling finding a while true using the list of input. i am using an integer input. what am i comparing the condition to if to continue the loop?
Any help is appreciated! The code below is what i wrote i test if i could store input in a list but the while true is where i'm struggling with what to compare.
while True:
if list_of_inputs
list_of_inputs = input("Write numbers: ").split()
list_of_inputs = list(map(int , list_of_inputs))
print (list_of_inputs)
Here's some code that does what you described in the comments.
We use two while loops. The first one gets lines of input, one by one, and adds them to the list_of_inputs. If a line consisting of the string "done" is read we break out of the loop, and we don't add "done" to the list.
The second loop gets lines of input and tests whether or not they are present in list_of_inputs, printing an appropriate message. If the user inputs a line that is present in list_of_inputs we break out of the loop and the program ends.
print('Please enter values for the list, one value per line')
print('Enter "done" (without the quotes) to end the list')
list_of_inputs = []
while True:
s = input('value: ')
if s == 'done':
break
list_of_inputs.append(s)
print('Here is the list:')
print(list_of_inputs)
while True:
s = input('Please enter a test value: ')
if s in list_of_inputs:
print('Yes!', repr(s), 'is in the list')
break
else:
print('No', repr(s), 'is NOT in the list')
test run
Please enter values for the list, one value per line
Enter "done" (without the quotes) to end the list
value: abc def
value: ghi
value: jkl
value: done
Here is the list:
['abc def', 'ghi', 'jkl']
Please enter a test value: def
No 'def' is NOT in the list
Please enter a test value: ghij
No 'ghij' is NOT in the list
Please enter a test value: jkl
Yes! 'jkl' is in the list
Python 3.x
list_of_inputs = list()
while True:
var = input("Enter Number or type 'done' to exit :")
if var.lower() == 'done':
print(" Your inputs are: ",list_of_inputs)
exit()
else:
list_of_inputs.append(int(var))
Make sure indentation is proper in python codes.