Главная страница » Что значит int input

Что значит int input

  • автор:

Ввод и вывод данных

Переменной в программировании называется именованный контейнер для некоторого значения. Представьте себе ящик с наклееным на него стикером. Вы кладете что-нибудь в ящик и пишете на стикере короткое имя без пробелов и знаков препинания, начинающееся с буквы английского алфавита, примерно так же работает переменная в программировании.

a и А — это разные переменные, регистр ввода имеет значение

Типы данных

Информация получаемая нами с помощью различных органов чувств делится на зрительную, слуховую, обонятельную, осязательную и другие. В программировании так же есть свое разделение, разделение на типы данных. Примитивных типов данных в Python 4:

int — целочисленный тип (1, 192, 781287)

float — вещественный (дробный) (1.12312, 1231.12378718)

str — строковый тип (обязательно пишется в кавычках) (‘Hello world’)

bool — булевый тип (имеет всего два значения: True и False)

Приведение типов

Приведением типов данных называется преобразование одного типа в другой, например, строку в число, число в строку, число в булеву переменную, строку в дробь и так далее.

a = 10
b = str (a) # b — это строка
с = int (b) # c — это снова число
d = 10.78
e = int (d) # e равно 10

Функция print

Функция print выводит переданные в неё аргументы в стандартный поток вывода. Что же такое стандартный поток вывода? Standart output или stdout называется потоком вывода, местом, куда мы выводим наш текстовый контент. По умолчанию стандартный поток вывода равен sys.stdout и поэтому вывод осуществляется в консоль.

Функция print все переданные в неё аргументы в стандартный поток вывода. Например:

print ( 1 )
print ( ‘Hello world!’ )
print ( False )
print ( 1.5 , 2.0 , 10 , True , ‘username’ )
print ( ‘Hello’ + ‘ ‘ + ‘world’ + ‘!’ )
# 1
# Hello world!
# False
# 1.5 2.0 10 True username
# Hello world!

На этом тривиальном примере мы видим две вещи. Во-первых, каждый print переносит поток вывода на новую строчку. Во-вторых, аргументы, переданные в функцию print выводятся через пробел.

# Во-первых:
print ( 1 )
print ( 2 )
# 1
# 2
# Во-вторых:
print ( ‘Hello’ , ‘world’ )
# Hello world

В обоих случаях мы можем изменить стандартное поведение. Рассмотрим первый параметр функции print — end, в него передается строка, которая напечатается после всех аргументов функции print.

print ( 1 , end = ‘ ‘ )
print ( 2 , end = ‘ ‘ )
print ( 3 , end = ‘ ‘ )
# 1 2 3

print ( 1 , end = » — » )
print ( 2 , end = ‘-‘ )
print ( 3 , end = » — » )
# 1-2-3-

print ( 1 , end = ‘-я выведусь после первого print-‘ )
print ( 2 , end = ‘-a я после второго-‘ )
print ( 3 , end = ‘-я выведусь после третьего-‘ )
# 1-я выведусь после первого print-2-a я после второго-3-я выведусь после третьего-

Рассмотрим второй параметр функции print — sep, sep от английского separator (разделитель). По умолчанию параметр sep равен ‘ ‘. Время для экспериментов ╰(▔∀▔)╯.

print ( 1 , 2 , 3 , 4 )
print ( 1 , 2 , 3 , 4 , sep = ‘+++’ )
print ( 1 , 2 , 3 , 4 , sep = ‘разделитель’ )
print ( 1 , 2 , 3 , 4 , sep = ‘(◕‿◕)’ )
print ( 1 , 2 , 3 , 4 , sep = ‘(ノ◕ヮ◕)ノ*:・゚✧’ )
# 1 2 3 4
# 1+++2+++3+++4
# 1разделитель2разделитель3разделитель4
# 1(◕‿◕)2(◕‿◕)3(◕‿◕)4
# 1(ノ◕ヮ◕)ノ*:・゚✧2(ノ◕ヮ◕)ノ*:・゚✧3(ノ◕ヮ◕)ノ*:・゚✧4

Функция input

Функция input является функцией стандартного ввода (stdin). Ее главная задача — это передача введенных пользователем данных в функцию.

name = input ()
print ( ‘Hello, ‘ + name)

Функция input может принимать всего лишь один аргумент — строку, которая выведется перед кареткой ввода

name = input ( ‘Enter your name: ‘ )
print ( ‘Hello, ‘ + name)

Функция input возвращает строковый тип данных

Строки можно складывать друг с другом — это называется конкатенацией или объединением

number = input ()
print (type(number))
#

Поэтому если мы напишем такой код, то он будет работать некорректно:

number1 = input ()
number2 = input ()
print (number1 + number2)
# Ввод:
# 1
# 2
# Вывод:
# 12

Поэтому необходимо преобразовать строковый тип в целочисленный (str в int)

number1 = int ( input ())
number2 = int ( input ())
print (number1 + number2)
# Ввод:
# 1
# 2
# Вывод:
# 3

Всегда проверяйте тип полученных данных, это поможет вам избежать большого количества ошибок. К слову, если вы что-то напутали с типами переменных, то Python выдаст ошибку TypeError (ошибка типа)

Решение задач

1. Поэкспериментируйте с переводом в различные типы данных

2. Пользователь вводит свое имя и фамилию. Выведите:

Hello, имя фамилия
# На месте слов с % должны быть введенные данные

3. Посчитайте сумму трех введенных целых чисел

4. Посчитайте сумму трех введенных дробных чисел. Подумайте в какой тип данных нужно преобразовать значение, возвращенное функцией input

5. Дано число, выведите предыдущее и следущее за ним числа в таком формате:

# Число равно 10
Число предшествующее числу 10 равно 9
Число следующее за числом 10 равно 11

6. Вводятся имя и возраст. Выведите, где введенное имя = Максим, а возраст = 20

Python Input

Now, you know how to print something on the screen and not just that, you also know about the different data types available in Python and how to use them. Let’s move forward with this chapter and learn a new Python concept.

Till now, we have assigned values to variables in the code. However, there can be times when we want the user to enter the value which has to be assigned to a variable. Take an example of a calculator in which the user enters the values to be added or subtracted.

input() function is used to take input from the user. So, let’s see how to take values entered by the user.

The statement in the above code will read the value entered by the user (xyz) and will assign it to the variable name .

We can also print a message on the screen while asking the user for input by passing that message to the input() function.

In this example, the message “What is your name >>>” will get printed on the screen and the value entered by the user after that will be assigned to the variable name . The message displayed on the screen while taking input is helpful to understand what type of input the user is expected to enter. Therefore, it is a good practice to display such messages while taking input.

Python Input – How to Read Single and Multiple Inputs

With Python, input can be requested from the user by typing input() . This input will usually be assigned to a variable, and it’s often best to have a user-friendly prompt when requesting the input.

If you’re expecting a specific type of input, such as an integer, it’s useful to perform an explicit conversion on the input before storing it in your variable.

For example, an explicit conversion to an int :

integer_input = int(input(«Please enter an integer between 1 and 10»))

Throughout this guide, you’ll find a wide range of code samples for retrieving input from a user.

Single Input

Retrieving a single input from the user is a good starting point. The code below shows how to request a single input, convert it, and assign it to a variable. We’ll then confirm that the conversion was successful by checking the data type of the variable.

Example 1: Simple single input requests from user

Multiple Inputs

There are many situations where you may need to read in multiple inputs from a user. One example is where a user will enter a number on the first line, representing how many lines of data they plan to enter next.

This is a common feature of Python coding questions on sites such as HackerRank, so we’ll build up to demonstrating one of these in our examples.

Multiple Inputs on a Single Line

By comma separating multiple calls to input() , we’re able to display multiple prompts to the user, and store the responses in variables.

Example 1 shows two inputs; one integer and one string. The integer is assigned to var1 and the string is assigned to var2 .

Example 1: Retrieve 2 inputs from the user and assign to variables

Example 2 shows two inputs; one integer and one being a collection of strings separated by spaces. The integer is assigned to var1 and the collection of strings is split into a list, before being assigned to var2 .

Example 2: Retrieve 2 inputs, one being a collection of strings

Multiple Inputs from Multiple Lines

Now we’re going to look at a more complex example. This is taken from the Collections.namedtuple() problem on HackerRank.

Collections.namedtuple() Task:

HackerRank Collections.namedtuple() Task

In short, we’re looking for 3 main inputs:

  • Input 1: The number of lines of data to be entered
  • Input 2: The column names for the data
  • Input 3: The data

So, using what we’ve learned about input() , let’s look at how this can be solved.

Step 1: Get Input 1 and Input 2

The first input will be the number of lines of data to accept after the column names. We’ll store this in the students variable.

The second input will be a series of space-separated strings, to be used as the column names. We’ll store this in the column_names variable.

Step 2: Create a namedtuple() and use Input 2 as a source for the field names

The list we created by splitting Input 2 now contains the column names. We can pass this to the field_names parameter of our named tuple.

You can find out more about named tuples and their use cases in our guide to the Python collections module.

Step 3: Prompt user for data rows

This is the step that requires most of the logic.

We know how many lines of data to expect from Input 1, which we stored in the students variable. This is how many times we’ll need to send the input prompt to the user.

We also know how many fields of data to expect, and that we can split the input on white space, same as we did for the field names.

So, all that’s left is to:

  • Iterate students number of times
  • At each iteration, prompt the user for input
  • At each iteration, split this input and assign values to the fields of our Grade named tuples
  • Store the MARKS values in an object that can easily be used to find the average

This can all be done with a single line:

Step 4: Calculate the average grade

So, now we have a list containing all our MARKS, the easy part is calculating the average, by dividing the sum by the len .

Step 5: Full solution

So, let’s combine steps 1 to 4 and check that our code produces the correct output.

About Daniel Andrews

Passionate about all things data and cloud. Specializing in Python, AWS and DevOps, with a Masters degree in Data Science from City University, London, and a BSc in Computer Science.

Python Input: Take Input from User

In Python, Using the input() function, we take input from a user, and using the print() function, we display output on the screen. Using the input() function, users can give any information to the application in the strings or numbers format.

After reading this article, you will learn:

  • Input and output in Python
  • How to get input from the user, files, and display output on the screen, console, or write it into the file.
  • Take integer, float, character, and string input from a user.
  • Convert the user input to a different data type.
  • Command-line input
  • How to format output.

Also, Solve

Table of contents

Python Input() function

In Python 3, we have the following two built-in functions to handle input from a user and system.

  1. input(prompt) : To accept input from a user.
  2. print() : To display output on the console/screen.

In Python 2,we can use the following two functions:

  1. input([prompt])
  2. raw_input([prompt])

The input() function reads a line entered on a console or screen by an input device such as a keyboard, converts it into a string. As a new developer, It is essential to understand what is input in Python.

What is the input?

The input is a value provided by the system or user. For example, suppose you want to calculate the addition of two numbers on the calculator, you need to provide two numbers to the calculator. In that case, those two number is nothing but an input provided by the user to a calculator program.

python input() function

There are different types of input devices we can use to provide data to application. For example: –

  • Stems from the keyboard: User entered some value using a keyboard.
  • Using mouse click or movement: The user clicked on the radio button or some drop-down list and chosen an option from it using mouse.

In Python, there are various ways for reading input from the user from the command line environment or through the user interface. In both cases, the user is sending information using the keyboard or mouse.

Python Example to Accept Input From a User

Let see how to accept employee information from a user.

  • First, ask employee name, salary, and company name from the user
  • Next, we will assign the input provided by the user to the variables
  • Finally, we will use the print() function to display those variables on the screen.

Output:

How input() Function Works

syntax

  • The prompt argument is optional. The prompt argument is used to display a message to the user. For example, the prompt is, “Please enter your name.”
  • When the input() function executes, the program waits until a user enters some value.
  • Next, the user enters some value on the screen using a keyboard.
  • Finally, The input() function reads a value from the screen, converts it into a string, and returns it to the calling program.

Note: If you enter an integer or float number, still, it will convert it into a string. If you want to number input or input in other data types, you need to perform type conversion on the input value.

Let’s understand this with an example.

Example to check data type of input value

Output:

As you know whatever you enter as input, the input() function always converts it into a string.

Take an Integer Number as input from User

Let’s see how to accept an integer value from a user in Python. We need to convert an input string value into an integer using an int() function.

Example:

Output:

Note: As you can see, we explicitly added a cast of an integer type to an input function to convert an input value to the integer type.

Now if you print the type of first_number you should get integer type. type(first_number ) will return <class ‘int’>

Take Float Number as a Input from User

Same as integer, we need to convert user input to the float number using the float() function

Output:

Practice Problem

Accept one integer and one float number from the user and calculate the multiplication of both the numbers.

Get Multiple inputs From a User in One Line

In Python, It is possible to get multiple values from the user in one line. We can accept two or three values from the user.

For example, in a single execution of the input() function, we can ask the user his/her name, age, and phone number and store it in three different variables.

Let’ see how to do this.

  • Take each input separated by space
  • Split input string using split() get the value of individual input

Output:

Also, you can take the list as input from the user to get and store multiple values at a time.

Accept Multiline input From a User

As you know, the input() function does not allow the user to provide values separated by a new line.

If the user tries to enter multiline input, it reads only the first line. Because whenever the user presses the enter key, the input function reads information provided by the user and stops execution.

Let’s see how to gets multiple line input.

We can use a loop. In each iteration of the loop, we can get input strings from the user and join them. You can also concatenate each input string using the + operator separated by newline ( \n ).

Example:

Output:

Python Input() vs raw_input()

  • The input() function works differently between Python 3 and Python 2.
  • In Python 2, we can use both the input() and raw_input() function to accept user input.
  • In Python 3, the raw_input() function of Python 2 is renamed to input() and the original input() function is removed.

The difference between the input() and raw_input() functions is relevant only when using Python 2.

  • The main difference between those two functions is input() function automatically converts user input to the appropriate type. i.e., If a user-entered string input() function converts it into a string, and if a user entered a number, it converts to an integer.
  • The raw_input() convert every user input to a string.

Let’s see how to use raw_input() in Python 2.

Example 1: Python 2 raw_input() function to take input from a user

Output:

Note: As you can see, raw_input() converted all user values to string type.

Example 2: Python 2 input() function to take input from a user

Output:

Note: As you can see, input() converted all user values to appropriate data type.

Note: To get the this behavior of input() in Python 3, use eval(input(‘Enter Value’))

Command Line input

A command line interface (CLI) is a command screen or text interface called a shell that allows users to interact with a program.

For example, On windows, we use the Command Prompt and Bash on Linux. command line or command-line interface is a text-based application for viewing, handling, and manipulating files on our computer. The command line also called cmd, CLI, prompt, console, or terminal.

On command-line, we execute program or command by providing input/arguments to it. Also, output and error are displayed A command line.

We can run Python programs on the command line. The command line input is an argument that we pass to the program at runtime.

Python provides following modules to work with command-line arguments.

  1. sys module
  2. getopt m odule
  3. argsparse module
  4. fire module
  5. docotp module

Python sys module

The Python sys module is the basic module that implements command-line arguments in a simple list structure named sys.argv .

  • sys.argv[0] : The first argument is always the program/script name.
  • sys.argv : Returns the list of command line arguments.
  • len(sys.argv) : Count of command line arguments.

Steps:

Write the below code in a file and save it as a sample.py

Run the below command on the command line

Output

Here 10, 20, 30 are command-line arguments passed to the program. Each input represents a single argument.

  • The first argument, i.e., sys.argv[0] , always represents the Python program name ( .py ) file
  • The other list elements i.e., sys.argv[1] to sys.argv[n] are command-line arguments. Space is used to separate each argument.

Note: argv is not an array. It is a list. This is a straightforward way to read command-line arguments as a string. See the following example to check the type of argv

Example

Now let’s see another example where we display all command-line arguments passed to the program.

Example : To Display command line argumnets

Run the below command on the command line

Output

Note : The space is separator between command line arguments.

In Python, by default, command-line arguments are available in string format. Based on our requirement, we can convert it into the corresponding type by using the typecasting method.

See the following example where we change the data type of arguments using the int() method.

Example

Output

If we try to access arguments with out of the range index on the command line, we will get an error.

Output

Output in Python

Python has a built-in print() function to display output to the standard output device like screen and console.

Example 1: Display output on screen

Output:

Example 2: Display Output by separating each value

Output:

Output Formatting

Most of the time, we need to format output instead of merely printing space-separated values. For example, we want to display the string left-justified or in the center. We want to show the number in various formats.

You can display output in various styles and formats using the following functions.

  • str.format()
  • repr()
  • str.rjust() , str.ljust() , and str.center() .
  • str.zfill()
  • The % operator can also use for output formatting

Now, Let see each one by one.

str.format() to format output

  • The str is the string on which the format method is called. It can contain text or replacement fields delimited by braces <>.
  • Each replacement field contains either the numeric index of a positional argument present in the format method or the name of a keyword argument.
  • The format method returns a formatted string as an output. Each replacement field gets replaced with the actual string value of the corresponding argument present in the format method. i.e., args.

Let see this with an example:

Note: Here <0>and <1>is the numeric index of a positional argument present in the format method. i.e., <0>= Ault and <1>= Kelly. Anything that not enclosed in braces <> is considered a plain literal text.

python output formatting options

Python output formatting options

Let see different ways to display output using a format() method. You can find various Formatting options here.

Format Output String by its positions

Output:

Accessing Output String Arguments by name

Output:

Output Alignment by Specifying a Width

Output:

Specifying a Sign While Displaying Output Numbers

Output:

Display Output Number in Various Format

Output:

Display Numbers as a float type

Output:

Output String Alignment

Let’s see how to use str.rjust() , str.ljust() and str.center() to justify text output on screen and console.

Output:

Next Steps

To practice what you learned in this article, I have created a Quiz and Exercise.

References:

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Comments

What’s up friends, how is the whole thing, and what you desire to say on the topic of this paragraph,
in my view its actually amazing for me.

Feel free to surf to my page; www bong88

thank u for sharing this straightforward course, it was so helpful
so I would like to share another solution like :
instead of putting this code below :

It is possible to get input without having to end with an enter? I saw msvcrt is used, but it isn’t working in my code

mainak mallik says

How to ged rid of input question in output?

Understood the concepts easily.
Do you have link for file input ?

Pallavi Bothra says

Could you please explain why did u do while: True …. else : break. I didn’t get this part.

Ans:- inside while loop if condition enters to ‘if’ statement and finds True then it skip that part and continue the loop again.

It keeps on skipping the value which holds true inside if condition.

Rubén Valencia says

Cómo puedeo eliminar el salto de linea \n después de un input, para evaluar la entrada y agregar un resultado en la misma linea:

Rubén Valencia says

Cómo puedo eliminar el salto de línea después de un input?

Md Nabid Ul Hasan says

When I try to take input , I can only take integers as input …No alphabets are working …How can I fix it .

Hey, Can you please post your code so I can look into it

Inputs are by-default strings, are you mentioning int before input ?

Yash Pandey says

Sir can we hide while writing the input.
I mean let’s say :

#after running it

Anyone can see the password while I’m printing it so can I hide it too while writing.

Aglomasa Bill Clinton says

Python example to accept input from a user.

With this assignment, the last code

print (name, salary, company)

Will not work in python 3.6
However

print (f», , «) will work.

As f”” results in filling the inputs that the variable name, salary and company hold.

This article made me understand the input() and the input ([prompt]) better. Thank you.

Thank you Aglomasa Bill Clinton for your feedback and suggestion. I have tested code using 3.7 and it’s working as expected

Franco A. Crispo says

Hi Vishal, with your Pynative, you did an excellent job .I’m from Italy, not longer a young boy �� and i like Python and i would like to learn it well. I searched for tutorials in every corner and i must admit that yours is the best around. Continue on this path and….congratulations.

Thank you Franco A. Crispo for your kind words

Bro, where are the steps for parsing inputs from files as discussed in the title?
Thanks for the above explanations regarding manual inputs.

How do I write a statement that only allows letters not numbers?

this was what I write but it doesn’t give me errors for inputing numbers when my intention was to allow only letters.

Sina Sarsharpour says

When you use the method str() . it can take anything. When you have an integer it makes it a string. So your problem is there is no error for that

ANIL KUMAR says

can you please demonstrate the code for taking the dataFrame as input.

while using the input are there any other types which we can use other than int, float, string

Eeliena Wang says

Vishal
Thanks you so much. It is a really helpful resource for Python beginner.
Best Wishes.
Eeliena

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *