Getting input from the user is a necessary task for most programs. There usually needs to be some input unless the program is completely automated to perform a task.
This article is not strictly on getting the information from the user, but managing that information and manipulating the input. These are some very basic tasks, but ones that you may need to know.
input()
Before we can manipulate the input, we need to get the input from the user. Getting information from the user is a very basic command using 'input()'. Within the parenthesis, we can place a prompt to show what input needs to be entered.
For example, let's ask the user for a name:
Whatever the user enters, we can place into the variable 'name'. If we wanted, we can print a prompt, then just accept an input:
The prompt section of the input command is empty, so there is no prompt from the 'input' command, but it comes from the previous print command. Be aware that this will use a line for the print statement and then a second line for the user's input.
We can also ask the user a question and expect a response, such as 'Y/N' for Yes and No. Single character input I will cover soon.
This input is visible to the screen, but what if we want the user input hidden, like a password?
getpass()
The 'getpass' command will let us get input from the user, but keep the input hidden. The input is blank. There aren't even asterisks that can show the length of the password.
The 'getpass' is a separate module that needs importing, but not installed. The 'getpass' module is usually in the Python package.
NOTE: If you come across a module that is not available on your system, go to a Terminal and use the command 'pip3 install <module_name>'. Using 'pip3', you can install the module.
To load a module, you use the keyword 'import' with the module's name. If you have more than one module, you can put them on the same line and separated them with commas.
We place the 'import' statement at the beginning of a Python script, even before functions.
So, the command is:
The 'getpass' module comprises several functions. There are two that we will look at in this section: 'getpass' and 'getuser'.
The 'getpass.getpass' (module.function) performs a hidden input. The command is like 'input()':
When we use the command, the prompt will appear and as the user types their input, nothing appears on the screen. With my example, the variable 'password' will contain what they typed and you can use it to compare to a database or file and verify that the password is correct. Otherwise, you can give the password to a program that will verify it.
The second function I want to bring up from 'getpass' is an input take from the system environment. Of course, this works best on Linux systems that store the current username in the system variable '$USER'. The command is:
There are no parameters to pass in the parenthesis so all you specify is the variable to place in the username value.
There are modules you can use to access other system environment variables, which you can find by searching the Internet for Python Modules.
Single Character Input
There are a lot of times you may need to ask a question, for example, a Yes or No question, to a user. Getting a single character answer can reduce the time a user spends on your program can help. Choosing 'y' or 'n' or even a single number or letter of any sort can help with a program's rhythm. A user can accomplish more with single characters than a lot of typing. For a good example, look at the article 'BASH Dice Game'. You play the entire game of Yahtzee using single characters.
Now, we can get single characters from Python, but you'll need to keep in mind that a user can enter the alphabetic characters as upper- or lower-cased letters. We can fix this in the next section of this article, but for now, we will assume they could be one or the other.
There are two methods we can use for a single key entry. The first uses the modules 'sys' and 'tty'.
Here, I set up the key input from a function. This is basic and does not check for the character to be 'y' or 'n'. If you noticed, I made the 'Y' choice the default. We can check for just the 'ENTER' key being pressed and force the response to be 'y'.
The second option is to use the module 'click' and the function 'getchar'. Here, I am showing the coding for the checking of the character to be 'y' or 'n' and also make 'y' the default.
As you can see, this is coding that only allows the choice of 'y', 'n' or 'ENTER' and will continue to loop until the user makes one of the proper choices. Looking back, you can see that the choices are only lowercase. I'll address this soon.
The first choice to check the key pressed is if it is a 'y'. The second check is for an 'n'. The third choice is to check the ordinal (ord) number of the key pressed. The 'Enter' key is '13', but keep in mind that the ordinal number for the 'ENTER' using the 'sys' and 'tty' example will produce '10'. This is the difference in how the modules get the key from the keyboard. Ordinal 10 is a 'Line Feed' while '13' is a 'Carriage Return'. If needed, you can test for either number.
Getting the ordinal (ord) number of the variable 'c' is just getting the ASCII value of the character. If you have the ASCII value and want to convert it back to a character, then use 'chr' just as you do 'ord'.
Converting Input
As I mentioned, we can have a key pressed by a user and it might be uppercase or lowercase if it is alphabetic.
There are four methods I will cover to change characters:
The output is:
Now, let's look at these. The capitalize method will lowercase all the letters and then uppercase the very first letter of each sentence. This works well for normal sentences, but if a proper name is in the sentence and not the very first word, then it will be lowercase.
The Title Test shows that every word has its first letter uppercase while all the rest is lowercase. This works well for titles of books and movies, but if a 'word' is all caps, like USA, then it will not work correctly.
The Upper Test will change all letters to uppercase.
If you look over the Lower Test, it performs the same as 'upper', but lowercase instead of uppercase.
Looking at the original strings, you can see that they will change or remain the same, depending on the test.
Be aware that if you pass an integer, such as 'e = 1234', to these methods then you will get an error, but if the numbers are a string, 'f = "1234"', then no error will occur and no change to the string is made by any method since the characters are not alphabetic.
Now, let's look at the tests for the strings. The code follows, but you'll notice I remarked out the integer variable since it gives an error on every test. The variable content must be a string and you can convert it using a 'str()' command:
The output is as follows:
So, variables 'a', 'b' and 'c' are all considered alphabetic. All letters are between 'a' and 'z', no matter the case. Variables 'e' and 'f' contain numbers, so they are not completely alphabetic.
The 'isnumeric' test is only true for the variable 'e' since it is a string made up of all numbers.
Checking for uppercase with 'isupper()' only is true for variable 'b' since all alphabetic characters are uppercase. Now, if the variable 'f' was 'f = "A1B2C3D4"' and not 'f = "A1b2C3d4"', then it would be true since all alphabetical characters were uppercase.
Looking at the results for the 'islower' test, you can see that the only true result is from variable 'c' since all the alphabetic characters are lowercase. Again, if variable 'f' were 'f = "a1b2c3d4"', then it would produce a 'True' response.
Conclusion
You can see that there are different methods to getting input, whether a character or multiple characters, in Python.
Once you have a string, you can perform conversions on it. After converting it, you can more easily test the input to make conversions as you need.
This article is not strictly on getting the information from the user, but managing that information and manipulating the input. These are some very basic tasks, but ones that you may need to know.
input()
Before we can manipulate the input, we need to get the input from the user. Getting information from the user is a very basic command using 'input()'. Within the parenthesis, we can place a prompt to show what input needs to be entered.
For example, let's ask the user for a name:
Code:
name=input("Enter your name: ")
Whatever the user enters, we can place into the variable 'name'. If we wanted, we can print a prompt, then just accept an input:
Code:
print("Enter your name: ")
name=input()
The prompt section of the input command is empty, so there is no prompt from the 'input' command, but it comes from the previous print command. Be aware that this will use a line for the print statement and then a second line for the user's input.
We can also ask the user a question and expect a response, such as 'Y/N' for Yes and No. Single character input I will cover soon.
This input is visible to the screen, but what if we want the user input hidden, like a password?
getpass()
The 'getpass' command will let us get input from the user, but keep the input hidden. The input is blank. There aren't even asterisks that can show the length of the password.
The 'getpass' is a separate module that needs importing, but not installed. The 'getpass' module is usually in the Python package.
NOTE: If you come across a module that is not available on your system, go to a Terminal and use the command 'pip3 install <module_name>'. Using 'pip3', you can install the module.
To load a module, you use the keyword 'import' with the module's name. If you have more than one module, you can put them on the same line and separated them with commas.
We place the 'import' statement at the beginning of a Python script, even before functions.
So, the command is:
Code:
import getpass
The 'getpass' module comprises several functions. There are two that we will look at in this section: 'getpass' and 'getuser'.
The 'getpass.getpass' (module.function) performs a hidden input. The command is like 'input()':
Code:
password=getpass.getpass("Enter your password: ")
When we use the command, the prompt will appear and as the user types their input, nothing appears on the screen. With my example, the variable 'password' will contain what they typed and you can use it to compare to a database or file and verify that the password is correct. Otherwise, you can give the password to a program that will verify it.
The second function I want to bring up from 'getpass' is an input take from the system environment. Of course, this works best on Linux systems that store the current username in the system variable '$USER'. The command is:
Code:
current_user = getpass.getuser()
There are no parameters to pass in the parenthesis so all you specify is the variable to place in the username value.
There are modules you can use to access other system environment variables, which you can find by searching the Internet for Python Modules.
Single Character Input
There are a lot of times you may need to ask a question, for example, a Yes or No question, to a user. Getting a single character answer can reduce the time a user spends on your program can help. Choosing 'y' or 'n' or even a single number or letter of any sort can help with a program's rhythm. A user can accomplish more with single characters than a lot of typing. For a good example, look at the article 'BASH Dice Game'. You play the entire game of Yahtzee using single characters.
Now, we can get single characters from Python, but you'll need to keep in mind that a user can enter the alphabetic characters as upper- or lower-cased letters. We can fix this in the next section of this article, but for now, we will assume they could be one or the other.
There are two methods we can use for a single key entry. The first uses the modules 'sys' and 'tty'.
Code:
import sys
import tty
def getkey():
while True:
keypressed = (ord(sys.stdin.read(1)))
return keypressed
tty.setcbreak(sys.stdin)
print ("Continue (Y/n)? ")
key = getkey()
Here, I set up the key input from a function. This is basic and does not check for the character to be 'y' or 'n'. If you noticed, I made the 'Y' choice the default. We can check for just the 'ENTER' key being pressed and force the response to be 'y'.
The second option is to use the module 'click' and the function 'getchar'. Here, I am showing the coding for the checking of the character to be 'y' or 'n' and also make 'y' the default.
Code:
import click
d = 0
print('Continue? [Yn] ')
while d == 0:
c = click.getchar() # Gets a single character
if c == 'y':
d = 1
elif c == 'n':
d = 1
elif (ord(c)) == 13:
d = 1
c = 'y'
print (f'You pressed: {c}')
As you can see, this is coding that only allows the choice of 'y', 'n' or 'ENTER' and will continue to loop until the user makes one of the proper choices. Looking back, you can see that the choices are only lowercase. I'll address this soon.
The first choice to check the key pressed is if it is a 'y'. The second check is for an 'n'. The third choice is to check the ordinal (ord) number of the key pressed. The 'Enter' key is '13', but keep in mind that the ordinal number for the 'ENTER' using the 'sys' and 'tty' example will produce '10'. This is the difference in how the modules get the key from the keyboard. Ordinal 10 is a 'Line Feed' while '13' is a 'Carriage Return'. If needed, you can test for either number.
Getting the ordinal (ord) number of the variable 'c' is just getting the ASCII value of the character. If you have the ASCII value and want to convert it back to a character, then use 'chr' just as you do 'ord'.
Converting Input
As I mentioned, we can have a key pressed by a user and it might be uppercase or lowercase if it is alphabetic.
There are four methods I will cover to change characters:
- Capitalize
- Title
- Upper
- Lower
- isalpha
- isnumeric
- isupper
- islower
Code:
a = "this is all lower case."
b = "THIS IS ALL UPPERCASE."
c = "ThIs Is A MiX oF CaSe."
print (" ")
#Capitalize Test
print (f"Capitalize Test")
print (a.capitalize())
print (b.capitalize())
print (c.capitalize())
print (" ")
#Title Test
print (f"Title Test")
print (a.title())
print (b.title())
print (c.title())
print (" ")
#Upper Test
print (f"Upper Test")
print (a.upper())
print (b.upper())
print (c.upper())
print (" ")
#Lower Test
print (f"Lower Test")
print (a.lower())
print (b.lower())
print (c.lower())
The output is:
Code:
Capitalize Test
This is all lower case.
This is all uppercase.
This is a mix of case.
Title Test
This Is All Lower Case.
This Is All Uppercase.
This Is A Mix Of Case.
Upper Test
THIS IS ALL LOWER CASE.
THIS IS ALL UPPERCASE.
THIS IS A MIX OF CASE.
Lower Test
this is all lower case.
this is all uppercase.
this is a mix of case.
Now, let's look at these. The capitalize method will lowercase all the letters and then uppercase the very first letter of each sentence. This works well for normal sentences, but if a proper name is in the sentence and not the very first word, then it will be lowercase.
The Title Test shows that every word has its first letter uppercase while all the rest is lowercase. This works well for titles of books and movies, but if a 'word' is all caps, like USA, then it will not work correctly.
The Upper Test will change all letters to uppercase.
If you look over the Lower Test, it performs the same as 'upper', but lowercase instead of uppercase.
Looking at the original strings, you can see that they will change or remain the same, depending on the test.
Be aware that if you pass an integer, such as 'e = 1234', to these methods then you will get an error, but if the numbers are a string, 'f = "1234"', then no error will occur and no change to the string is made by any method since the characters are not alphabetic.
Now, let's look at the tests for the strings. The code follows, but you'll notice I remarked out the integer variable since it gives an error on every test. The variable content must be a string and you can convert it using a 'str()' command:
Code:
a = "AbCdEf"
b = "ABCDEF"
c = "abcdef"
d = 12345
e = "12345"
f = "A1b2C3d4"
print (" ")
#isalpha
print ("isalpha Test")
print (a.isalpha())
print (b.isalpha())
print (c.isalpha())
#print (d.isalpha())
print (e.isalpha())
print (f.isalpha())
print (" ")
#isnumeric
print ("isnumeric Test")
print (a.isnumeric())
print (b.isnumeric())
print (c.isnumeric())
#print (d.isnumeric())
print (e.isnumeric())
print (f.isnumeric())
print (" ")
#isupper
print ("isupper Test")
print (a.isupper())
print (b.isupper())
print (c.isupper())
#print (d.isupper())
print (e.isupper())
print (f.isupper())
print (" ")
#islower
print ("islower Test")
print (a.islower())
print (b.islower())
print (c.islower())
#print (d.islower()))
print (e.islower())
print (f.islower())
The output is as follows:
Code:
isalpha Test
True
True
True
False
False
isnumeric Test
False
False
False
True
False
isupper Test
False
True
False
False
False
islower Test
False
False
True
False
False
So, variables 'a', 'b' and 'c' are all considered alphabetic. All letters are between 'a' and 'z', no matter the case. Variables 'e' and 'f' contain numbers, so they are not completely alphabetic.
The 'isnumeric' test is only true for the variable 'e' since it is a string made up of all numbers.
Checking for uppercase with 'isupper()' only is true for variable 'b' since all alphabetic characters are uppercase. Now, if the variable 'f' was 'f = "A1B2C3D4"' and not 'f = "A1b2C3d4"', then it would be true since all alphabetical characters were uppercase.
Looking at the results for the 'islower' test, you can see that the only true result is from variable 'c' since all the alphabetic characters are lowercase. Again, if variable 'f' were 'f = "a1b2c3d4"', then it would produce a 'True' response.
Conclusion
You can see that there are different methods to getting input, whether a character or multiple characters, in Python.
Once you have a string, you can perform conversions on it. After converting it, you can more easily test the input to make conversions as you need.