Цей підручник зосереджений на двох вбудованих функціях print () та input () для виконання завдання вводу-виводу в Python. Крім того, ви навчитеся імпортувати модулі та використовувати їх у своїй програмі.
Відео: Python Take User Input
Python надає численні вбудовані функції, які нам легко доступні в підказці Python.
Деякі функції люблять input()
та print()
широко використовуються для стандартних операцій введення та виведення відповідно. Давайте спочатку ознайомимося з вихідним розділом.
Виведення Python за допомогою функції print ()
Ми використовуємо print()
функцію для виведення даних на стандартний пристрій виведення (екран). Ми також можемо виводити дані у файл, але це буде обговорено пізніше.
Приклад його використання наведено нижче.
print('This sentence is output to the screen')
Вихідні дані
Це речення виводиться на екран
Інший приклад наведено нижче:
a = 5 print('The value of a is', a)
Вихідні дані
Значення а дорівнює 5
У другому print()
твердженні ми можемо помітити, що між рядком та значенням змінної a додано пробіл. Це за замовчуванням, але ми можемо це змінити.
Фактичний синтаксис print()
функції:
друк (* об'єкти, sep = '', end = ' n', файл = sys.stdout, flush = False)
Тут objects
наведено значення (и), яке слід надрукувати.
sep
Сепаратор використовується між значеннями. За замовчуванням це простір.
Після друку всіх значень, end
друкується. За замовчуванням це новий рядок.
Це file
об’єкт, де значення друкуються, а значенням за замовчуванням є sys.stdout
(екран). Ось приклад, щоб проілюструвати це.
print(1, 2, 3, 4) print(1, 2, 3, 4, sep='*') print(1, 2, 3, 4, sep='#', end='&')
Вихідні дані
1 2 3 4 1 * 2 * 3 * 4 1 # 2 # 3 # 4 &
Вихідне форматування
Іноді ми хотіли б відформатувати наш результат, щоб він виглядав привабливо. Це можна зробити за допомогою str.format()
методу. Цей метод видно будь-якому рядковому об'єкту.
>>> x = 5; y = 10 >>> print('The value of x is () and y is ()'.format(x,y)) The value of x is 5 and y is 10
Тут фігурні дужки ()
використовуються як заповнювачі. Ми можемо вказати порядок їх друку, використовуючи цифри (індекс кортежу).
print('I love (0) and (1)'.format('bread','butter')) print('I love (1) and (0)'.format('bread','butter'))
Вихідні дані
Я люблю хліб і масло Я люблю масло і хліб
Ми навіть можемо використовувати аргументи ключових слів для форматування рядка.
>>> print('Hello (name), (greeting)'.format(greeting = 'Goodmorning', name = 'John')) Hello John, Goodmorning
We can also format strings like the old sprintf()
style used in C programming language. We use the %
operator to accomplish this.
>>> x = 12.3456789 >>> print('The value of x is %3.2f' %x) The value of x is 12.35 >>> print('The value of x is %3.4f' %x) The value of x is 12.3457
Python Input
Up until now, our programs were static. The value of variables was defined or hard coded into the source code.
To allow flexibility, we might want to take the input from the user. In Python, we have the input()
function to allow this. The syntax for input()
is:
input((prompt))
where prompt
is the string we wish to display on the screen. It is optional.
>>> num = input('Enter a number: ') Enter a number: 10 >>> num '10'
Here, we can see that the entered value 10
is a string, not a number. To convert this into a number we can use int()
or float()
functions.
>>> int('10') 10 >>> float('10') 10.0
This same operation can be performed using the eval()
function. But eval
takes it further. It can evaluate even expressions, provided the input is a string
>>> int('2+3') Traceback (most recent call last): File "", line 301, in runcode File "", line 1, in ValueError: invalid literal for int() with base 10: '2+3' >>> eval('2+3') 5
Python Import
When our program grows bigger, it is a good idea to break it into different modules.
A module is a file containing Python definitions and statements. Python modules have a filename and end with the extension .py
.
Definitions inside a module can be imported to another module or the interactive interpreter in Python. We use the import
keyword to do this.
For example, we can import the math
module by typing the following line:
import math
We can use the module in the following ways:
import math print(math.pi)
Output
3.141592653589793
Тепер усі визначення всередині math
модуля доступні в нашій області. Ми також можемо імпортувати лише певні атрибути та функції, використовуючи from
ключове слово. Наприклад:
>>> from math import pi >>> pi 3.141592653589793
Під час імпорту модуля Python переглядає кілька місць, визначених у sys.path
. Це список розташувань каталогів.
>>> import sys >>> sys.path ('', 'C:\Python33\Lib\idlelib', 'C:\Windows\system32\python33.zip', 'C:\Python33\DLLs', 'C:\Python33\lib', 'C:\Python33', 'C:\Python33\lib\site-packages')
Ми також можемо додати своє місцезнаходження до цього списку.