I need to check whether the input is empty or not and cannot use if statements.
print("What is your name?")
name = input()
print("Hi, {}".format(name))
Use a while loop that only terminates if the length of name is 0:
name = ""
while len(name) == 0:
print("What is your name?")
name = input()
print("Hi, {}".format(name))
You could try something like this:
print("What is your name?")
name = input()
name = "Hi, {}".format(name)
while name == "Hi, ":
name = "You didn't key in any name"
print(name)
This is ugly, but it will produce the exact output you want.
The idea is to use a loop that will run only once, and will only run if the name variable is empty after input() is called.
I would recommend assert. It will stop your programming to continue running when the requirement is not met.
print("What is your name?")
name = input()
assert name != "", "You didn't key in any name"
print("Hi, {}".format(name))
What is your name?
AssertionError: You didn't key in any name
As my previous answer with the while loop received some criticism, I decided to demonstrate a less "naive" but perhaps more complicated solution, that actually does not use any kind of direct conditional operator:
print("What is your name?")
name = input()
answer = {}
answer[len(name)] = "Hi, {}".format(name)
answer[0] = "You didn't key in any name"
print(answer[len(name)])
Here we rely on a dictionary with the length of the input as an integer key.
We don't even need to compare the length to 0, we just overwrite the 0 key with the error message.
If input length is greater than 0, the name will be under its own key, and will be printed, if not, the empty "Hi" string will be replaced.
Would this ever be useful in the real world?
Probably not, unless there are many more than 2 options.
Does it comply with the task requirements?
Yes. It gives the desired output.
Related
I am attempting to make a game that I made via Rpg Maker MV in python but I've hit a road block in the if statement or rather the gender input. The code is meant to have the user input either "Boy" or "Girl" and depending on that the variable "gender" will be set for pronouns. How ever the console is saying This
This is the code
import time
print ("Elvoria")
print ("Start")
input = input()
if input == ("Start"):
print ("Always Great To See New People")
time.sleep(1)
print ("Now Are You A Boy Or Girl")
genderin = input()
if input == ("Boy"):
gender = 1
elif input == ("Girl"):
gender = 2
else:
print ("Error")
You need to check the input using the variable name genderin that you defined, instead of input == ("Boy").
EDIT: Also, you are mirroring the built-in method input() with the variable name input and you should not do that. Rename your variable to e.g. start_input.
import time
print ("Elvoria")
print ("Start")
start_input = input()
if start_input == "Start":
print ("Always Great To See New People")
time.sleep(1)
print ("Now Are You A Boy Or Girl")
genderin = input()
if genderin == "Boy":
gender = 1
elif genderin == "Girl":
gender = 2
else:
print ("Error")
You're defining the variable "input" on line 4 to be a string, given from the "input" function. This overrides the keyword. Then, on line 9, you're calling "input" again. Since you've replaced the built-in function with a string, an error is thrown (the error "not callable" means that you're trying to treat a non-function like a function).
Here's your code sample, without overriding built-in methods:
import time
print ("Elvoria")
print ("Start")
user_input = input()
if user_input == ("Start"):
print ("Always Great To See New People")
time.sleep(1)
print ("Now Are You A Boy Or Girl")
genderin = input()
if genderin == ("Boy"):
gender = 1
elif genderin == ("Girl"):
gender = 2
else:
print ("Error")
You should avoid using input as a varible name, since a built-in function with that name already exists, input(). So just change it's name to something else. Secondly, you're storing the gender input (boy/girl) in genderin, but then checking input, when you should be checking genderin. So the code after fixing these would look something like this:
import time
print ("Elvoria")
print ("Start")
choice = input()
if choice == "Start":
print("Always Great To See New People")
time.sleep(1)
print("Now Are You A Boy Or Girl?")
genderin = input()
if genderin == "Boy":
gender = 1
elif genderin == "Girl":
gender = 2
else:
print("Error")
I have used choice for demonstration purposes, you can use a different name if you want, just remember to make sure that a python built-in with that name doesn't exist. Also, no need to put ("Start") in the if statement, use "Start" instead (same goes for other if/elif statements)
You have also used print ("example") (space between print and brackets), i've rarely ever seen someone using this, most people use print("example") instead.
Finally a tip -> You can make the string lowercase, genderin = genderin.lower() to manage case sensitivity, i.e, both boy and Boy will be valid inputs, etc.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
How to validate person names? - Python/Django
(4 answers)
Closed 4 years ago.
I am at the part where I ask the user for their name. So far I got this:
# Import stuff
import time
# Create empty variable
Name = ""
# Ask their name
while Name = ""
Name = input("What is your name? ")
print("")
print(Name)
print("")
time.sleep(3)
So if the user inputs nothing, it repeats the question. But when the user inputs an integer or a float it registers this as a valid name.
How will I be able to make it so that if the Name variable is an integer or a float, it will respond with "Please enter a valid name" and repeat the question?
I'm updating my answer to simplify the code and make it more readable.
The below function is a function that I would use in my own code, I would consider it to be more "proper" than my old answer.
from string import ascii_letters
def get_name():
name = input("What is your name?\n: ").strip().title()
while not all(letter in ascii_letters + " -" for letter in name):
name = input("Please enter a valid name.\n: ").strip().title()
return name
To break this down, the line all(letter in ascii_letters + " -" for letter in name) means "if each letter in name is not an alphabetical character, a space, or a hyphen".
The part letter in ascii_letters + " -" checks to see if a letter is in the string "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -".
This is repeated by the next part, for letter in name, for every character in the string. This will effectively return a list of booleans, [True, True, True, ...] where any False is a character that did not pass the conditional. Next, this list is passed to the all() function, which returns True if all of the list items are True.
After the all() is executed, conditional is reversed, allowing the loop to continue on the existence of a single failed character.
Old answer is as follows, it will still be useful.
This function should work well for you. Simply check if the string the user entered is alpha characters only, otherwise ask again.
Notice the use of str.isalpha().
def get_name():
name = input("What is your name?\n: ").strip().title()
while not (name.replace("-", "") and
name.replace("-", "").replace(" ", "").isalpha()):
name = input("Please enter a valid name.\n: ").strip().title()
return name
Checking if name will check if the string is empty, and using str.strip() on the values returned will remove any surrounding whitespace (stray spaces) to the left or right of the user input.
The str.replace("-", "") eliminates hyphens while checking validity. Thanks for pointing this out #AGN Gazer.
Now you can just call the function later in your script, or store it for later.
name = get_name().title()
print("You said your name was " + name + ".)
The str.title() converts the letter of each word in a string to uppercase. For example, if I entered my name "jacob birkett", the output (and subsequent value of name would be "Jacob Birkett".
Take a look at the documentation for str.isalpha(), str.strip(), str.replace() and str.title().
You can try this :
while Name == "" or Name.isnumeric() == True:
Name = input("What is your name? ")
print("")
Here if the Name is any numeric value it will ask again, But if the name is like alphanumeric it will accept.
You can use a function like .isalpha() as this will return True if all the string contains all the alphabets:
while True:
Name = input("Please enter a valid name.\n: ")
if name.isalpha()
break
else:
print("Please enter a valid name.")
continue
print(Name)
Or You can try exception handling in python as (but this should be prevented):
try :
int(Name)
print("Please enter a valid name")
...
except:
print("Accepted")
...
This will check if the input is an integer print the error.
You can try:
This will check if variable Name containing numeric data or not.
import time
Name = ""
while Name == "" :
Name = input("What is your name? ")
if not Name.isalpha():
print "It is containing numberic characher or characters"
Name = ""
print("")
print(Name)
print("")
time.sleep(3)
You also can try if name is like "harsha-biyani":
import time
Name = ""
while Name == "" :
Name = input("What is your name? ")
if any(i.isdigit() for i in Name):
print "It is containing numberic characher or characters"
Name = ""
print("")
print(Name)
print("")
time.sleep(3)
You can use:
Name.isalpha()
"3".isalpha()
False
"anna".isalpha()
True
I'll start by saying that I did look up answers to this question and unfortunately, I just couldn't understand them or they didn't seem to work for me. This is of course down to me rather than the people who answered the question, so I do apologise in advance.
So pretty much I'm trying to call a variable that is assigned by the user from one function to the other, I'll give an example:
def function_one():
a = input("What is your name?")
return a
def function_two():
print("Nice to meet you, "a)
function_one()
function_two()
This of course does not work and I'm sure that is down to my own stupidity, I wasn't sure why at first because I saw other people saying to simply return the variable, which I did!
I also tried calling the variable from the other function, for example:
def function_two()
a = function_one()
but I realised that was pretty stupid since I'm just assigning that function as a, so it's not going to work.
I'd appreciate some insight, I know these are not the kind of questions you'd expect but yeah... I'm clueless.
I think what you want to do is take user input, store it in a variable, then greet the user using that variable:
def ask_for_users_name():
name = input("What is your name?")
return name
def greet_user(name):
print("Nice to meet you, " + name)
users_name = ask_for_users_name()
greet_user(users_name)
One important thing to note is that I had to concatenated the name with the string "Nice to meet you, " using the + operator.
Edit:
To answer to the question in the comments, you could do something like this in that case:
def ask_for_user_info():
name = input("What is your name?")
age = input("What is your age?")
return name, age
user_name, user_age = ask_for_user_info()
Best practice is to make functions that only do one thing, for many reasons, one is that the name of the function normally replaces any need for inline comments:
def ask_for_user_name():
name = input("What is your name?")
return name
def ask_for_user_age():
age = input("What is your age?")
return age
In the case of the ask_for_user_info() method, it isn't immediately clear what exactly it is doing from the name.
Edit 2:
You could then use those two functions like this, in either order:
age = ask_for_user_age()
name = ask_for_user_name()
or
name = ask_for_user_name()
or
age = ask_for_user_name()
you do have it. this should work.
def function_two():
a = function_one()
print('hi {}'.format(a))
then
>>>function_two()
Another way is to use this:
def ask_for_users_name():
name = input("What is your name?")
greet_user(name)
def greet_user(user_name):
print("Nice to meet you,"+user_name)
ask_for_users_name()
You merely call ask_for_users_name() at the end.
Edit:
greet_user_() is a void function, which means it does not return anything. In this case, all it does is receive input passed to it and prints it. If you want to perform other operations, you can pass it additional parameters, or keep it the way it is.
Version 1:
def ask_for_users_name():
name = input("What is your name?")
age = int(input("What is your age? "))
print("Your age is ", age)
greet_user(name)
def greet_user(user_name):
print("Nice to meet you,"+user_name)
ask_for_users_name()
In version 1, we are still utilizing greet_user() to just print one thing, and performing another print operation in ask_for_users_name().
Version 2:
def ask_for_users_name():
name = input("What is your name?")
age = int(input("What is your age? "))
greet_user(name, age)
def greet_user(user_name, user_age):
print("Nice to meet you,"+user_name)
print("Your age is", user_age)
ask_for_users_name()
In version 2, we are passing both age and name to greet_user(), which in turn prints out the passed variables. I hope this helps.
I'm really new to Python and I'm mainly just messing around. I'm trying to put together a function that validates a user input (in my case, to check wether the user writes either James or Peter. This is probably a very newbie question, but I was just wondering if my code is a good way to accomplish this function.
Thanks for any help.
namelist = "Peter", "James"
def nameinput():
global name
name = raw_input("Write a name. ")
def checkname(x):
while name not in namelist:
print "Try again"
nameinput()
else:
print "Good,", name
checkname(nameinput())
if name == "Peter":
print "This is a text for Peter"
elif name == "James":
print "This is a text for James"
No; there is no reason to use global variables here. Pass data around to the functions that need it.
def nameinput():
return raw_input("Write a name. ")
def checkname(name):
namelist = ["Peter", "James"]
while name not in namelist:
print "Try again"
name = nameinput()
else:
print "Good,", name
return name
name = checkname(nameinput())
Using global variables is generally frowned upon (it can really do stupid stuff if you don't always know what you are doing), so don't start doing so that early.
You could easily avoid that by returning the name from nameinput.
Also, you already have the name list. Do the following in the end:
if name in namelist:
print("This is a text for " + name)
I have been trying to figure this out for way too long! What to do?
def fallBack(submission):
if (submission == ""):
submission = "fixed!"
return(submission)
name = input("What is your name?")
(fallBack(name))
location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")
I keep having the last input just print out nothing...
You need to store the result of fallBack().
Also, change fallBack() to return the original value if it is non-null:
def fallBack(submission):
if not submission:
return "fixed!"
else:
return submission
Then, use it like this:
name = fallBack(input("What is your name?"))
Just remove the brackets around fallBack(name)
def fallBack(submission):
if (submission == ""):
submission = "fixed!"
return submission
name = input("What is your name?")
name = fallBack(name)
location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")
Also remember that if using python 2.7 you should use raw_input instead of input
I'm not sure what you want to do, but I think this would do it:
def fallBack(submission):
if (submission == ""):
submission = "fixed!"
return (submission)
name = input("What is your name?")
name = fallBack(name)
location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")
Your two mistakes were not to return anything in case there is nothing to fix, and not to assin the value returned by the function.
By the way, there is a much more idiomatic way of doing this in Python:
name = input("What is your name?")
name = name or 'fixed!'
location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")
The second line tests if converting name to a boolean, and, if it returns False (for a string, it is equivalent to testing if it is not empty), replace it with 'fixed!'
The return is not well aligned! You are not returning anything unless submission is empty! :-)
def fallBack(submission):
if (submission == ""):
submission = "fixed!"
return(submission)