Using Loop to Accept Additional User Input Until User Enters a Value That Ends the Input

How to repeat the input until a special condition is meet in Python?

When the exception happens, a remains unset. Try this instead.

s = set()
# Notice also correct quoting
print("Please type the number, when you're done please type 'Done':")
while True:
a = input()
try:
n = int(a)
s.add(n)
# Avoid blanket except
except ValueError:
if a == "Done":
break
else:
print('Integer only, please re-type:')
continue
print(s)

How to keep asking user to input until condition is satisfied in C?

I recommend that you use the following code:

#include <stdio.h>

int main( void )
{
int u1,u2,u3;

for (;;) //infinite loop, equivalent to while(true)
{
printf( "Enter 3 Numbers: " );
scanf( "%d %d %d", &u1, &u2, &u3 );

if ( u1!=u2 && u2!=u3 && u3!=u1 ) break;

printf( "Error: Condition is not satisfied!\n" );
}
}

In contrast to one of the other answers, this solution has the advantage that it only checks the condition once per loop iteration.

However, the above code (and the code of most other answers) has a serious issue: If the user enters an alphabetical letter instead of a number, the program will get stuck in an infinite loop. This is because it is not safe to call scanf without checking the return value. See the following page for more information on why it is unsafe: A beginners' guide away from scanf()

How to create a loop for user input until user enters valid input

char input;  
do
{
displayWellDoneMenu();
scanf("%c", &input);
system("cls");
if (c=='1' || c=='2')
break;
printf("You must select 1 or 2!\n");
}while(1);

switch (input)
{
case'1':
additionIntermediate();
break;
case '2':
main();
break;
}

How do I request user input until user enters valid input in ruby?

My understanding is that the user enters sentences until one contains an "s" or an "S", at which time a certain action is taken and the program terminates.

Let's go through what you have.

print "Please enter a sentence with a letter s"

I think you want puts, which adds a newline character, rather than print, which does not.

while user_input = gets.chomp.downcase!

Suppose the user enters "Cat" (even though it's not a sentence), then presses the Enter key, then

str0 = gets
#=> "Cat\n"
str1 = str0.chomp
#=> "Cat"
user_input = str1.downcase!
#=> "cat"
str1
#=> "cat"
user_input
#=> "cat"

so we have

while "cat"

As "cat" is neither false nor nil (the only logical false objects), this is the same as

while true

so execution moves to the first statement within the while loop. Suppose instead the user entered "cat" and pressed the Enter key. Then

str0 = gets
#=> "cat\n"
str1 = str0.chomp
#=> "cat"
user_input = str1.downcase!
#=> nil
str1
#=> "cat"
user_input
#=> nil

so the program would not enter the while loop! How, you ask, can "cat".downcase return nil? Look at the doc for String#downcase!. It shows that nil is returned if there were no characters to downcase. Ruby has many methods that do the same: if the receiver is not altered nil is returned. (Don't get sidetracked with "why" at this point of your education.) For the present you are advised to avoid using bang methods (ending with an "!").

Similarly, if the user didn't enter anything and pressed enter,

str1 = "\n".chomp
#=> "" (an empty string)
user_input = str1.downcase
#=> nil

"".downcase! returns nil for the same reason that "cat".downcase! does.

I think what you what here is the following.

user_input = gets.chomp
while !user_input.match?(/s/i)

/s/i is a regular expression used to determine if the string contains an "s" or an "S". i in /i is a case-indifference modifier. (One could instead write while user_input !~ /s/i.)

The first statement within the while loop is

  case user_input

When case has an argument (here user_input) the when statements contain arguments that are possible values of the case argument, for example

  case user_input
when "call me silly!"
puts "You are silly"
when...

You are not doing that here, so you want case on a line by itself:

case
when user_input == ...
...
end

Here, however, there is no need for a case statement or "if/elsif/else/end" construct within the loop because we have already determined that user_input does not contain an "s". All we need in the loop is this:

while !user_input.match?(/s/i)
puts "Please enter a sentence with a letter s"
user_input = gets.chomp
end

After the loop is terminated user_input is a string that contains an "s". We therefore need only perform the following.

puts "Daffy Duck says #{user_input}"
#=> "Quack, quack, quackity-quack, sir"

Note that your statement

user_input.gsub(/s/, "s")

substitutes each "s" with an "s". :-) Nor is there a need for the break keyword.

Putting all this together, you could write:

puts "Please enter a sentence with a letter s"
user_input = gets.chomp
while !user_input.match?(/s/i)
puts "Please enter a sentence with a letter s"
user_input = gets.chomp
end
puts "Daffy Duck says #{user_input}"

You thought I was finished. Not so fast!

Firstly, many Ruby coders try to avoid negations such as while !user_input.match?(/s/i) (though it is purely a matter of taste). You could instead write that line

until user_input.match?(/s/i)

A more significant problem is the replication of code. You can improve upon that by using Kernel#loop and the keyword break instead of while or until.

loop do
puts "Please enter a sentence with a letter s"
user_input = gets.chomp
if user_input.match?(/s/i)
puts "Daffy Duck says #{user_input}"
break
end
end

If, however, we wrote

loop do
puts "Please enter a sentence with a letter s"
user_input = gets.chomp
break if user_input.match?(/s/i)
end
puts "Daffy Duck says #{user_input}"

The last line would raise the exception

NameError (undefined local variable or method `user_input' for main:Object)

because the variable user_input is only defined within the loop.

I generally use loop and break in preference to while or until.

Using a while loop to output a list after user input

You didn't show error message but if this is your original indentations then problem is that you create movie_genre inside function - so it is local variable which exists only inside function, but rest of code is outside function and it can't access it. You should move all code inside function or you should keep all code outside function.

I will keep all outside function - so I can remove it.

There are other mistakes and few elements which you could fix

You could keep genders withou inner [] and then you don't need zip(*...)

movie_genre = ["Action", "Horror", "Adventure", "Musical", "Comedy", "Sci-Fi", "Drama", "Romance", "Thriller"]

for genre in movie_genre:
print(genre)

You use name in strange way in i = name(..) - name is a string and you can't use it like a function. Maybe you needed input() to ask for selected genre - selected = input(...) - but I would do this after displaying genres.

I also don't know what you want to do with while name. This will run loop forever because you doesn't change name inside loop. Maybe you need something different - ie. maybe you want to repeate loop until user select correct gender - `while selected not in movie_genre:


Full example

#Movie list
movie_genre = ["Action", "Horror", "Adventure", "Musical", "Comedy", "Sci-Fi", "Drama", "Romance", "Thriller"]
name = ''

#We introduce the program to the user
print("Hello my name is Frank, the theatre clerk!")

#Asks the user to input their name
print("May I please know who i have the pleasure of speaking with?")

#User submits name
name = input()

#Returns user name + prompt
print(name + ", pleasure to make your acquaintance!")

# --- select genre ---
selected = "" # default value before loop

while selected not in movie_genre: # repeate until user select genre

for genre in movie_genre:
print(genre)

#Asks the user for what genre they want to watch
selected = input("What are we interested in watching today?")


Related Topics



Leave a reply



Submit