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))
Answer from BrokenBenchmark on Stack OverflowUse 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.
Videos
I need to write a program that asks for numbers from an user until the user gives "an empty input". I am stuck on this empty input part in particular. I have Googled for hours and hours but haven't found anything that would match and help me.
lst = []
user_input = int(input("Please enter a number: "))
while user_input != 0:
lst.append(user_input)
user_input = int(input("Please enter a number: "))
if user_input == 0:
break
print("You said: ", lst)
This example works, because it has 0, not completely empty input. How do I change the 0 to just empty?
if user_input == "":
break
This doesn't work? Where am I going wrong here?
You know if nothing was entered for the second one because it will raise a SyntaxError. You can catch the error like this:
try:
y=input('Number>> ')
except SyntaxError:
y = None
then test
# not just 'if y:' because 0 evaluates to False!
if y is None:
or, preferably, use raw_input:
try:
y = int(raw_input('Number>> '))
except ValueError:
print "That wasn't a number!"
For the first one, x will be an empty string if nothing is entered. The call to str is unnecessary -- raw_input already returns a string. Empty strings can be tested for explicitly:
if x == '':
or implicitly:
if x:
because the only False string is an empty string.
This also work too
y = input('Number>> ')
while not y:
y = input('Number>> ')