Make a Yes/No question with user input in Python, an exciting and highly applicable topic that increases user interaction. To create a yes/no question, I will use the input() function and the click.confirm() function from the click module. Post details below.
Make a Yes/No question with user input in Python
Use the input() function.
- prompt: A hint string for the user to enter data
Python’s built-in input() method enables users to enter string data and retrieve it.
# Use the input() function to make a yes/no question. userInput = input('Do you like the LearnshareIt website?(Y/N):') if userInput.upper() == 'Y': print('Thank you for trusting us as your reference!') elif userInput.upper() == 'N': print('Sorry for making you unhappy. We will improve in the future.') else: print('Please enter the correct character "Y" or "N".')
Do you like the LearnshareIt website?(Y/N):Y Thank you for trusting us as your reference!
Use the click.confirm function.
The confirm() function can determine the user’s desire to take action. It automatically returns the prompt’s outcome as a boolean value. Additionally, if the function doesn’t return True, there is an option to have the program execution instantly stop.
- When you run the program, the command line ‘Do you want to visit LearnshareIt website to read more interesting articles?’ If you press ‘Y’, the command line in the if will run. If you press ‘n’, the program will end.
import click # Use the click.confirm to make a yes/no question if click.confirm('Do you want to visit LearnshareIt website to read more interesting articles?', default=True): print('Thank you for trusting us as your reference.')
Do you want to visit LearnshareIt website to read more interesting articles? [Y/n]: Y Thank you for trusting us as your reference.
If you set the parameter default = False, the program will look like this.
import click # Use the click.confirm to make a yes/no question. if click.confirm('Do you want to continue?', default=False): print('Visit LearnshareIt website')
Do you want to continue? [y/N]: N
Note: The difference is that when you set any bool value as default, the letter that returns that value will be capitalized when you output it.
Note: Before using the click module, install it with the command: pip install click.
My article about how to make a Yes/No question with user input in Python has ended. Through the article, you will get an idea of this topic. If there is a better way, please leave a comment down below. Thank you for reading the article!
My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.
Name of the university: HHAU
Programming Languages: C++, Python, Java