- Get User Entry Python
- How to get the current username in Python
- Python Tkinter Entry – How to use
- Python Tkinter Entry get()
- Getpass() and getuser() in Python (Password without echo)
- Python Tkinter – Entry Widget
- Python User Input from Keyboard – input() function
- How to Get User Input in Python [With Examples]
- Python User Input from Keyboard – input() function
- Getting User Input in Python
- What is the type of user entered value?
- How to get an Integer as the User Input?
- Python user input and EOFError Example
- Python User Input Choice Example
- Quick word on Python raw_input() function
- Conclusion
- References:
Get User Entry Python
We can use the input() method to take user input in python. The input() method, when executed, takes an option string argument which is shown as a prompt to the user. After taking input, the input() method returns the value entered by the user as a string. Even if the user enters a number or a punctuation mark, the input() method will always
value = input("Please input a number:") print("The data type of <> is <>".format(value, type(value))) Please input a number:1243 The data type of 1243 is import re flag = True input_value = None while flag: input_value = input("Please input a number:") match_val = re.match("[-+]?\\d+$", input_value) if match_val is None: print("Please enter a valid integer.") else: flag = False number = int(input_value) print("The input number is:", number) Please input a number:Aditya Please enter a valid integer. Please input a number:PFB Please enter a valid integer. Please input a number:123.4 Please enter a valid integer. Please input a number:+1234 The input number is: 1234 import re flag = True input_value = None while flag: input_value = input("Please input a number:") match_val = re.match("[-+]?\\d+([/.]\\d+)?$", input_value) if match_val is None: print("Please enter a valid decimal number.") else: flag = False number = float(input_value) print("The input number is:", number) Please input a number:Aditya Please enter a valid decimal number. Please input a number:PFB Please enter a valid decimal number. Please input a number:-123.456 The input number is: -123.456
How to get the current username in Python
Method 1: Using OS library. getlogin () method of OS library is used to get the current username. Syntax : os.getlogin ( ) In order to use this function we need to …
'KRISHNA KARTHIKEYA' 'C:\\Users\\KRISHNA KARTHIKEYA' 'KRISHNA KARTHIKEYA' 'KRISHNA KARTHIKEYA' 'root'
Python Tkinter Entry – How to use
Python tkinter Entry widgets are used to take user input. It is a widely used widget and can be found on any application irrespective of the programming languages. It is called TextField in java. It is a one-liner box wherein the user can type something. Unlike java, Tkinter does not have separate multiple line entry widgets.
from tkinter import * ws = Tk() info_Tf = Entry(ws) info_Tf.insert(END, 'You email here') info_Tf.pack() ws.mainloop() from tkinter import * ws = Tk() name = StringVar(ws, value='not available') nameTf = Entry(ws, textvariable=name).pack() ws.mainloop() from tkinter import * def chooseOne(res): userInput.delete(0, END) userInput.insert(0, res) return ws = Tk() ws.title("find the ring") ws.geometry("400x250") frame = Frame(ws) userInput = Entry(frame, width=40, justify=CENTER) userInput.grid(row=0, columnspan=3, padx=5, pady= 10) Button(frame,text="Box 1",command=lambda:chooseOne("Nada!, try again")).grid(row=1, column=0) Button(frame,text="Box 2 ",command=lambda:chooseOne("Great! You found the ring")).grid(row=1, column=1) Button(frame,text="Box 3",command=lambda:chooseOne("Nada! try again")).grid(row=1, column=2) frame.pack() ws.mainloop() from tkinter import * from tkinter import messagebox ws = Tk() ws.title('get text demo') ws.geometry('200x200') def welcomeMessage(): name = name_Tf.get() return messagebox.showinfo('message',f'Hi! , Welcome to python guides.') Label(ws, text="Enter Name").pack() name_Tf = Entry(ws) name_Tf.pack() Button(ws, text="Click Here", command=welcomeMessage).pack() ws.mainloop() from tkinter import * ws = Tk() ws.geometry("400x250") text_area = Text(ws, height=10, width=30).pack() ws.mainloop() from tkinter import * ws = Tk() name = StringVar(ws, value='not available') nameTf = Entry(ws, textvariable=name).pack() ws.mainloop() from tkinter import * from tkinter import messagebox ws = Tk() ws.title('pythonguides') ws.geometry('250x200') def welMsg(name): name = name_Tf.get() return messagebox.showinfo('pythonguides', f'Hi! , welcome to pythonguides' ) Label(ws, text='Enter Name & hit Enter Key').pack(pady=20) name_Tf = Entry(ws) name_Tf.bind('',welMsg) name_Tf.pack() ws.mainloop()
Python Tkinter Entry get()
The button’s command closes the window and does the get () function: from Tkinter import * def close_window (): global entry entry = E.get () root.destroy () root = Tk () E = tk.Entry (root) E.pack (anchor = CENTER) B = Button (root, text = «OK», command = close_window) B.pack (anchor = S) root.mainloop () And that returned the desired value
from Tkinter import * root = Tk() E1 = Entry(root) E1.pack() entry = E1.get() root.mainloop() print "Entered text:", entry from Tkinter import * def close_window(): global entry entry = E.get() root.destroy() root = Tk() E = tk.Entry(root) E.pack(anchor = CENTER) B = Button(root, text = "OK", command = close_window) B.pack(anchor = S) root.mainloop() import Tkinter as tk def on_change(e): print e.widget.get() root = tk.Tk() e = tk.Entry(root) e.pack() # Calling on_change when you press the return key e.bind("", on_change) root.mainloop() from tkinter import * import tkinter as tk root =tk.Tk() mystring =tk.StringVar(root) def getvalue(): print(mystring.get()) e1 = Entry(root,textvariable = mystring,width=100,fg="blue",bd=3,selectbackground='violet').pack() button1 = tk.Button(root, text='Submit', fg='White', bg= 'dark green',height = 1, width = 10,command=getvalue).pack() root.mainloop()
Getpass() and getuser() in Python (Password without echo)
etpass () prompts the user for a password without echoing. The getpass module provides a secure way to handle the password prompts where programs interact with the users via the terminal. This module provides two functions : getpass () getpass. getpass (prompt=’Password: ‘, stream=None) The getpass () function is used to prompt to users using
getpass.getpass(prompt='Password: ', stream=None) $ python3 getpass_example1.py Password: ('Password entered:', 'aditi') $ python3 getpass_example2.py Your favorite flower? Welcome. $ python3 getpass_example2.py Your favorite flower? The answer entered by you is incorrect. $ python3 getpass_example3.py User Name : bot Welcome. $ python3 getpass_example3.py User Name : bot The password you entered is incorrect.
Python Tkinter – Entry Widget
Python Tkinter – Entry Widget. Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using Tkinter is an easy task.
pip install tkinter entry = tk.Entry(parent, options)
Python User Input from Keyboard – input() function
Python user input from the keyboard can be read using the input () built-in function. The input from the user is read as a string and can be assigned to a variable. After entering the value from the keyboard, we have to press the “Enter” button. Then the input () function reads the value entered by the user. The program halts indefinitely
input(prompt) value = input("Please enter a string:\n") print(f'You entered ') value = input("Please enter a string:\n") print(f'You entered and its type is ') value = input("Please enter an integer:\n") print(f'You entered and its type is ') Please enter a string: Python You entered Python and its type is Please enter an integer: 123 You entered 123 and its type is value = input("Please enter an integer:\n") value = int(value) print(f'You entered and its square is ') value = input("Please enter an integer:\n") print(f'You entered ') Please enter an integer: ^D Traceback (most recent call last): File "/Users/pankaj/Documents/PycharmProjects/PythonTutorialPro/hello-world/user_input.py", line 1, in value = input("Please enter an integer:\n") EOFError: EOF when reading a line value1 = input("Please enter first integer:\n") value2 = input("Please enter second integer:\n") v1 = int(value1) v2 = int(value2) choice = input("Enter 1 for addition.\nEnter 2 for subtraction.\nEnter 3 for Multiplication.:\n") choice = int(choice) if choice == 1: print(f'You entered and and their addition is ') elif choice == 2: print(f'You entered and and their subtraction is ') elif choice == 3: print(f'You entered and and their multiplication is ') else: print("Wrong Choice, terminating the program.") ~ python2.7 Python 2.7.10 (default, Feb 22 2019, 21:55:15) [GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.37.14)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> value = raw_input("Please enter a string\n") Please enter a string Hello >>> print value Hello
How to Get User Input in Python [With Examples]
Get User Input in Python 2. If you’re still using Python 2, you will use the raw_input () function instead: myText = raw_input («Enter some text:») print «You entered the text: «, myText # Python 2 uses different syntax to print output.
myText = input("Enter some text:") print("You entered the text: " + myText) myText = raw_input("Enter some text:") print "You entered the text: ", myText # Python 2 uses different syntax to print output myText = input("Enter some text, it will be converted to a number variable:") myInteger = int(myText) # Converts the input text to an integer myFloat = float(myText) # Converts the input text to a float number try: myText = input("Enter some text, it will be converted to a number variable:") myInteger = int(myText) # Converts the input text to an integer myFloat = float(myText) # Converts the input text to a float number except ValueError: print("User has input in invalid number that could not be converted")
Python User Input from Keyboard – input() function
The prompt string is printed on the console and the control is given to the user to enter the value. You should print some useful information to guide the user to enter the expected value.
Getting User Input in Python
Here is a simple example of getting the user input and printing it on the console.
value = input("Please enter a string:\n") print(f'You entered ')
What is the type of user entered value?
The user entered value is always converted to a string and then assigned to the variable. Let’s confirm this by using type() function to get the type of the input variable.
value = input("Please enter a string:\n") print(f'You entered and its type is ') value = input("Please enter an integer:\n") print(f'You entered and its type is ')
Please enter a string: Python You entered Python and its type is Please enter an integer: 123 You entered 123 and its type is
How to get an Integer as the User Input?
There is no way to get an integer or any other type as the user input. However, we can use the built-in functions to convert the entered string to the integer.
value = input("Please enter an integer:\n") value = int(value) print(f'You entered and its square is ')
Python user input and EOFError Example
When we enter EOF, input() raises EOFError and terminates the program. Let’s look at a simple example using PyCharm IDE.
value = input("Please enter an integer:\n") print(f'You entered ')
Please enter an integer: ^D Traceback (most recent call last): File "/Users/pankaj/Documents/PycharmProjects/PythonTutorialPro/hello-world/user_input.py", line 1, in value = input("Please enter an integer:\n") EOFError: EOF when reading a line
Python User Input Choice Example
We can build an intelligent system by giving choice to the user and taking the user input to proceed with the choice.
value1 = input("Please enter first integer:\n") value2 = input("Please enter second integer:\n") v1 = int(value1) v2 = int(value2) choice = input("Enter 1 for addition.\nEnter 2 for subtraction.\nEnter 3 for Multiplication.:\n") choice = int(choice) if choice == 1: print(f'You entered and and their addition is ') elif choice == 2: print(f'You entered and and their subtraction is ') elif choice == 3: print(f'You entered and and their multiplication is ') else: print("Wrong Choice, terminating the program.")
Here is a sample output from the execution of the above program.
Quick word on Python raw_input() function
The raw_input() function was used to take user input in Python 2.x versions. Here is a simple example from Python 2.7 command line interpreter showing the use of raw_input() function.
~ python2.7 Python 2.7.10 (default, Feb 22 2019, 21:55:15) [GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.37.14)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> value = raw_input("Please enter a string\n") Please enter a string Hello >>> print value Hello
This function has been deprecated and removed from Python 3. If you are still on Python 2.x versions, it’s recommended to upgrade to Python 3.x versions.
Conclusion
It’s very easy to take the user input in Python from the input() function. It’s mostly used to provide choice of operation to the user and then alter the flow of the program accordingly.
However, the program waits indefinitely for the user input. It would have been nice to have some timeout and default value in case the user doesn’t enter the value in time.