Python if input is "ls" then print
Go to solution
Solved by lewdicrous,
@ughiwanthackintosh Do you mean something like this? Or something else?
Code 1:
Spoiler
while True: user_input = str(input("Enter a word: ")) #input from user if user_input == "ls": #checks if input is similar to assigned command print("Works") #prints message then exits loop break elif user_input == "as": #checks if input is similar to assigned command print("Works") #prints message then exits loop break elif user_input == "bn": #checks if input is similar to assigned command print("Works") #prints message then exits loop break else: #if input is not similar print("Error: invalid syntax") #prints message then returns to start of loop continue
If so, you can replace "break" with "continue" if you wanted the user to stay in the loop, but you'll need to add another if statement for them to exit the loop.
Edit: this loop works somewhat similarly to what you provided earlier, with additional commands and an if statement for exiting the loop.
Code 2:
Spoiler
while True: user_input = str(input("Enter a word: ")) #input from user if user_input == "ls": #checks if input is equal to "ls" print("Works") continue #returns to start of loop elif user_input == "as": #checks if input is equal to "as" print("Works") continue #returns to start of loop elif user_input == "bn": #checks if input is equal to "bn" print("Works") continue #returns to start of loop elif user_input == "exit": #checks if input is equal to "exit" print("Exiting") break #exits loop else: #if input is not available print("Error: invalid syntax") #prints message then returns to start of loop continue #returns to start of loop
Difference between code 1 and code 2: code 1 exits the loop if the input is correct/available, while code 2 stays in the loop if the input is correct/available.
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now