Ask user in python

A Python program to ask the user to enter name

Here I am going to explain a Python program to ask the user to enter a name. The task is going to be a very easy one. I will explain to you about the commands used in this program and how to write this program using a function.

A simple program to ask for the name in Python

NAME=str(input("enter the name: ")) print("hello",NAME)

output

enter the name: user hello user

The general description of this program is to ask a user name and save the data in “NAME” and to print the name using the variable where the data is stored.”NAME” is just a variable where the data is stored. Since we are asking name where no numbers are allowed so I am using string data type.

Ask the user to enter name in Python using a function

Let’s create our simple custom Python function and then call it:

def hello(): name=str(input("enter the name : ")) print("hello " + str(name)) return hello()

Run this code online
And the output will be like you can see below:

enter the name : user hello user

Here I had altered the general program by using a function. The hello() is a user-defined function used in this program and the function generated in a custom way. In this function, it is programmed to get the user name and to print the user name with a string “hello”.

So you can see that the same functionality is done by defining our own function.

conclusion

I hope that I had demonstrated the program using function and in a simple way for your understanding.

Источник

How to Ask for User Input in Python: A Complete Guide

To ask for user input in Python, use the built-in input() function.

name = input("Enter your name: ") print(f"Hello ")
Enter your name: Jack Hello Jack

In addition to asking for simple string input like this, you also want to learn how to:

To learn more about these, keep on reading.

How to Ask for Multiple Inputs in Python

To ask for multiple inputs in Python, use the input().split() method.

Ask for Multiple Inputs Separated by Blank Spaces

For example, let’s ask a user the first name and the last name and store them on different variables:

fname, lname = input("Enter your full name: ").split() print(f"Hello ")
Enter your full name: Jack Jones Hello Jack Jones

This works because the split() method splits the input based on a blank space by default.

Читайте также:  Регулярные выражения правила php

Ask for Multiple Inputs Separated by Custom Character

To split the input based on some other character, specify the separator character in the split() call.

For example, let’s ask a user for a list of three numbers:

a, b, c = input("Enter three comma-separated values: ").split(",") print(f"The values were , , and ")
Enter three comma-separated values: 1,2,3 The values were 1, 2, and 3

How to Ask for Input Again in Python

To ask for user input until they give valid input, use an endless while loop with some error handling.

For example, let’s create a program that asks the user’s age.

If the user does not enter an integer, we print an error message and ask again. This process continues until the user inputs an integer.

while True: try: age = int(input("Enter your age: ")) except ValueError: print("This is not a valid age.") continue else: break print(f"You are years old")
Enter your age: test This is not a valid age. Enter your age: 4.2 This is not a valid age. Enter your age: 30 You are 30 years old

This code works such that:

  • It starts an endless loop with while True .
  • It then tries to convert user input to an integer in the try block.
  • If it fails (due to a value error), it prints an error message in the except block and continues the endless while loop.
  • If it succeeds, the else block is executed which breaks the loop and continues to the next statements.

If you are new to Python, this may not ring a bell. If you want to learn more about error handling in Python, check this article.

Conclusion

Today you learned how to ask for user input in Python using the input() function.

In addition to asking for a single input, you now know how to

Further Reading

Источник

How to ask user for input in python

But that’s a mouthful, so you can also do this, which will check whether is in the set of correct answers: Solution 2: The best choice for check membership is using that has so you can use the following instead your statement : from python wiki : Solution 3: You should do this: import datetime Solution 1: You have: While that makes sense to a human being, Python thinks you mean this: and are non-empty strings, so they’re always true, so this whole expression is always true and it doesn’t make any difference what you enter.

How to make my code ask the user for input again python

import math done = 'n' while done == 'n': user_choice = input("Choose a shape") if user_choice == "rectangle" or "square": a = input("enter your length in centimeters here") b = input("enter your width in centimeters here") area = int(a) * int (b) print(area, "cm²") else print("Sorry, you may have made a spelling error, or have chose a shape that we cannot calculate. Please try again") done = input("Done? (Y/N)").lower() 

How can I get user input in a python discord bot?, Here is my code: import discord, datetime, time from discord.ext import commands from datetime import date, datetime prefix = «!!» client = commands.Bot (command_prefix=prefix, case_insensitive=True) times_used = 0 @client.event async def on_ready (): print (f»I am ready to go — …

Читайте также:  Uwsgi run python module

How to do user input in Python

Hey everyone,In this video, I will be talking about user input and how you can ask the user for specific input a.k.a «interacting» with the user . WATCH THIS

How do I ask the user to input time

The strptime function may help you. It throws an exception if the input text is not a good datetime. import datetime

def get_input_time(): while True: input = raw_input("What time is it now?\n") try: # strptime throws an exception if the input doesn't match the pattern input_time = datetime.datetime.strptime(input, "%H:%M") break except: print("Use Format Hours:Minutes (HH:MM)") return input_time #test the function input_time = get_input_time() print("Time is %s:%s" % (input_time.hour, input_time.minute)) 

How to ask user for integer input using Python tkinter, How can I get the right integer value input from user in Python tkinter? python python-3.x tkinter tkinter-entry tkinter-text. Share. Follow edited May 29 at 2:14. with a method which is both simpler and also better suited to get an integer input from user as it checks the user input and asks the user again in case of …

Ask user to input a correct response in Python? [duplicate]

if pres == 'Bush' or 'Obama' or 'Clinton': 

While that makes sense to a human being, Python thinks you mean this:

if (pres == 'Bush') or ('Obama') or ('Clinton'): 

‘Obama’ and ‘Clinton’ are non-empty strings, so they’re always true, so this whole expression is always true and it doesn’t make any difference what you enter.

You need to be explicit about what you mean:

if pres == 'Bush' or pres == 'Obama' or pres == 'Clinton': 

But that’s a mouthful, so you can also do this, which will check whether pres is in the set of correct answers:

The best choice for check membership is using set that has O(1) so you can use the following instead your if statement :

The sets module provides classes for constructing and manipulating unordered collections of unique elements. Common uses include membership testing , removing duplicates from a sequence, and computing standard math operations on sets such as intersection, union, difference, and symmetric difference.

if pres == 'Bush' or pres == 'Obama' or pres == 'Clinton': 

How to make my code ask the user for input again python, import math user_choice = input («choose a shape») if user_choice == «rectangle» or «square»: a = input («enter your length in centimeters here») b = input («enter your width in centimeters here») area = int (a) * int (b) print (area, «cm²») else print»sorry, you may have made a spelling error, or have chose a shape that we …

Condition checking in python with user input [duplicate]

Your input variable is a string. You need to cast it to an integer to correctly compare it to 6.

raw_input returns a string. abc is a string, and a string will never be equal with an integer. Try casting abc or the return value of raw_input() . Or, you can make 6 a string.

Читайте также:  Узнать номер элемента массива java

Casting the return value of raw_input() :

abc = int( raw_input('Enter a 2 digit number') ) 

Casting abc :

Changing 6 to string :

>>> abc= raw_input("Enter a 2 digit number") Enter a 2 digit number6 >>> if int(abc) == 6: print "Its party time. " Its party time. >>> 

Python — How to ask for user input within a function and, Also, since you are using Python 2.x, it would be safer to use raw_input() and then convert the string to the correct type. For example, you could do: s = raw_input(«Enter the value for what range to find prime numbers: «) n = int(s) # or fancier processing if you want to allow a wider range of inputs

Источник

In Python, how to ask for user to input a list, and then to be able to work with it, whatever data type, in a function

I am a pretty much complete beginner to Python, and I need to know how to ask the user to input a list which I can then work with. I know how to get a user to input ints, floats etc. and strings and then work with those, but I need help with getting a user to enter a list which is then changed to the, if not already, correct format of a list which I can then work with the values of in a function. Efficient code is good, but I’d prefer simple code which may take longer so I can understand it easier as a beginner. Any help is hugely appreciated!

3 Answers 3

So do you want the user to input a bunch of items in one command and then add these all to a list?

If so then what you are looking for is the str.split() method. What this does is it gets a string and then splits this string into a list containing lots of substrings.

It has two arguments (the second is how many times to split, this should be left as default), the first being the delimiter. This is the string which the code should look for when splitting the string. By default, this value is a space, but you will probably want to change it.

To put all of this into perspective, here is an example which splits a string which is a list separated by commas and spaces:

inputtedListAsString = str(input("Please enter the items, separated by commas: ")) inputtedListAsArray = inputtedListAsString.split(", ") 

If someone entered ‘a, b, c, d, e’ then it would return an array with 5 items, ‘a’, ‘b’, ‘c’, ‘d’ and ‘e’. If you were to enter ‘a, b, c, d, e, ‘ then this would return a list with 6 items, the sixth element in the list being an empty string.

Here is a more concise, one line example:

inputtedList = str(input("Please enter the items, separated by commas: ")).split(", ") 

Also, to show you how the second argument in str.split() works, here is an example which will split a string with a delimiter of ‘ ‘, but limit it to split the string into only 3 parts:

limitedList = "Hello my name is Bob.".split(" ", 2) 

This will return a list containing: ‘Hello’, ‘my’ and ‘name is Bob.’ Be aware that if you specify 2 as the second argument, the list will contain a maximum of 3 items, because the array counting starts at 0.

Источник

Оцените статью