Python brython библиотека для front-end

Python print() function

The print() function in Python is used to print a specified message on the screen. The print command in Python prints strings or objects which are converted to a string while printing on a screen.

Syntax:

print(object(s))

How to Print a simple String in Python?

More often then not you require to Print strings in your coding construct.

Here is how to print statement in Python 3:

Example: 1

To print the Welcome to Guru99, use the Python print statement as follows:

print ("Welcome to Guru99")

Output:

Welcome to Guru99

In Python 2, same example will look like

print "Welcome to Guru99"

Example 2:

If you want to print the name of five countries, you can write:

print("USA")
print("Canada")
print("Germany")
print("France")
print("Japan")

Output:

USA
Canada
Germany
France
Japan

How to print blank lines

Sometimes you need to print one blank line in your Python program. Following is an example to perform this task using Python print format.

Example:

Let us print 8 blank lines. You can type:

print (8 * "\n")

or:

print ("\n\n\n\n\n\n\n\n\n")

Here is the code

print ("Welcome to Guru99")
print (8 * "\n")
print ("Welcome to Guru99")

Output

Welcome to Guru99







Welcome to Guru99

Print end command

By default, print function in Python ends with a newline. This function comes with a parameter called ‘end.’ The default value of this parameter is ‘\n,’ i.e., the new line character. You can end a print statement with any character or string using this parameter. This is available in only in Python 3+

Example 1:

print ("Welcome to", end = ' ') 
print ("Guru99", end = '!')

Output:

Welcome to Guru99!

Example 2:

# ends the output with ‘@.’

print("Python" , end = '@')

Output:

Python@

Основные операторы

Оператор

Краткое описание

+

Сложение (сумма x и y)

Вычитание (разность x и y)

*

Умножение (произведение x и y)

Деление
Внимание! Если x и y целые, то результат всегда будет целым числом! Для получения вещественного результата хотя бы одно из чисел должно быть вещественным. Пример: 40/5 → 8, а вот 40/5.0 → 8.0

=

Присвоение

+=

y+=x; эквивалентно y = y + x;

-=

y-=x; эквивалентно y = y — x;

*=

y*=x; эквивалентно y = y * x;

/=

y/=x; эквивалентно y = y / x;

%=

y%=x; эквивалентно y = y % x;

==

Равно

!=

не равно

Больше

=

больше или равно

Часть после запятой отбрасывается
4 // 3 в результате будет 125 // 6 в результате будет 4

**

Возведение в степень
5 ** 2 в результате будет 25

and

логическое И

or

логическое ИЛИ

not

логическое отрицание НЕ

‘is’ и ‘==’ в Python

В Python есть два похожих оператора, предназначенных для сравнения объектов. Эти оператор и . Их часто путают, потому они одинаково сравнивают типы данных и :

x = 5
s = "example"

print("x == 5: " + str(x == 5))
print("x is 5: " + str(x is 5))
print("s == 'example': " + str(s == "example"))
print("s is 'example': " + str(s is "example"))

Результат выполнения кода:

x == 5: True
x is 5: True
s == 'example': True
s is 'example': True

Это доказывает, что и при таком сравнении возвращают . Но если сравнить более сложные структуры данных, то получим следующее:

some_list = 

print("some_list == : " + str(some_list == ))
print("some_list is : " + str(some_list is ))

Результат выполнения кода:

some_list == : True
some_list is : False

Разница заключается в том, что сравнивает идентичность объектов, а проверяет равенство значений.

Пример, который показывает разницу между этими двумя операторами.

some_list1 = 
some_list2 = 
some_list3 = some_list1

print("some_list1 == some_list2: " + str(some_list1 == some_list2))
print("some_list1 is some_list2: " + str(some_list1 is some_list2))
print("some_list1 == some_list3: " + str(some_list1 == some_list3))
print("some_list1 is some_list3: " + str(some_list1 is some_list3))

Результат выполнения:

some_list1 == some_list2: True
some_list1 is some_list2: False
some_list1 == some_list3: True
some_list1 is some_list3: True

some_list1 равен some_list2 по значению (]). Но они не идентичны. Но some_list1одновременно равен и идентичен some_list3, так как они ссылаются на один и тот же объект в памяти.

Printing to a newline

Check out this example code.

When you have multiple print statements, Python by default prints it to a newline.

In Python 2, a character is added to the end whereas, in Python 3, there is an argument that is set to by default.

However, you can change this default behavior.

To print multiple expressions to the same line, you can end the print statement in Python 2 with a comma ().

You can set the argument to a whitespace character string to print to the same line in Python 3.

With Python 3, you do have the added flexibility of changing the argument to print on the same line. For e.g.

In the above example, an asterisk() is being used for the argument.

There is no clean way to do that in Python 2. In order to achieve the above with Python 2, you would have to add the to the end of every line.

Python print String Format

We are using the print function along with conversion types. Within the first print statement, we used two %s in between a string follows by a tuple with variables. It means print function replace those two %s items with those tuple values.

Here, Python print function uses the same order that we specified. I mean, first, %s is replaced by a person variable, and the second %s replaced by name variable value. Here, print(person +’ is working at ‘+ name) statement is to concat three items.

print function and string formatting output

Python print format Example

It is an example of a Python print format function. In this example, we are using the format function inside the print function. It allows us to format values. I suggest you refer to the Python format Function article.

print and format functions output

print() function

The print statement has been replaced with a print() function, with keyword arguments to replace most of the special syntax of the old print statement.

The print statement can be used in the following ways :

  • print(«Good Morning»)
  • print(«Good», <Variable Containing the String>)
  • print(«Good» + <Variable Containing the String>)
  • print(«Good %s» % <variable containing the string>)

In Python, single, double and triple quotes are used to denote a string. Most use single quotes when declaring a single character. Double quotes when declaring a line and triple quotes when declaring a paragraph/multiple lines.

Commands

print(<el_1>, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
  • Use ‘file=sys.stderr’ for errors.
  • Use ‘flush=True’ to forcibly flush the stream.

Pretty Print

from pprint import pprint
pprint(<collection>, width=80, depth=None)

Levels deeper than ‘depth’ get replaced by ‘…’.

Double Quotes Use:

Example:

Output:

Python is very simple language

Single Quotes Use:

Example:

Output:

Hello

Triple Quotes Use:

Example:

Output:

Python is very Popular Language.
It is also friendly language.

Variable Use:

Strings can be assigned to variable say string1 and string2 which can called when using the print statement.

Example:

Output:

Wel come

Example:

Output:

Welcome Python

String Concatenation:

String concatenation is the «addition» of two strings. Observe that while concatenating there will be no space between the strings.

Example:

Output:

WelcomePython:

Using as String:

%s is used to refer to a variable which contains a string.

Example:

Output:

Welcome Python

Using other data types:

Similarly, when using other data types

  • %d -> Integer
  • %e -> exponential
  • %f -> Float
  • %o -> Octal
  • %x -> Hexadecimal

This can be used for conversions inside the print statement itself.

Using as Integer:

Example:

Output:

Actual Number = 15

Using as Exponential:

Example:

Output:

Exponential equivalent of the number = 1.500000e+01

Using as Float:

Example:

Output:

Float of the number = 15.000000

Using as Octal:

Example:

Output:

Octal equivalent of the number = 17

Using as Hexadecimal:

Example:

Output:

Hexadecimal equivalent of the number = f

Using multiple variables:

When referring to multiple variables parenthesis is used.

Example:

Output:

Python World :

Other Examples of Print Statement:

The following are other different ways the print statement can be put to use.

Example-1:

% is used for %d type word

Output:

Welcome to %Python language

Example-2:

\n is used for Line Break.

Output:

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Example-3:

Any word print multiple times.

Output:

-w3r-w3r-w3r-w3r-w3r

Example-4:

\t is used for tab.

Output:

Language:
        1 Python
        2 Java
        3 JavaScript

Precision Width and Field Width:

Field width is the width of the entire number and precision is the width towards the right. One can alter these widths based on the requirements.

The default Precision Width is set to 6.

Example-1:

Notice upto 6 decimal points are returned. To specify the number of decimal points, ‘%(fieldwidth).(precisionwidth)f’ is used.

Output:

5.123457

Example-2:

Notice upto 5 decimal points are returned

Output:

5.12346

Example-3:

If the field width is set more than the necessary than the data right aligns itself to adjust to the specified values.

Output:

  5.12346

Example-4:

Zero padding is done by adding a 0 at the start of fieldwidth.

Output:

000000005.12346

Example-5:

For proper alignment, a space can be left blank in the field width so that when a negative number is used, proper alignment is maintained.

Output:

 5.123457
-5.123457

Example-6:

‘+’ sign can be returned at the beginning of a positive number by adding a + sign at the beginning of the field width.

Output:

+5.123457
-5.123457

Example-7:

As mentioned above, the data right aligns itself when the field width mentioned is larger than the actually field width. But left alignment can be done by specifying a negative symbol in the field width.

Output:

5.1235   

Test your Python skills with w3resource’s quiz

Изменяемые и неизменяемые типы данных

Только почему операторы is и == одинаково сравнивают неименованные значения intи string (например, 5 и «example»). Но при этом не ведут себя так же с неименованными списками (например, )?

В Python есть две разновидности типа данных:

  • Изменяемые — те, которые можно изменять
  • Неизменяемые – остаются неизменными (имеют одинаковое расположение в памяти, что is и проверяет) после их создания.

Изменяемые типы данных: list, dictionary, set и определяемые пользователем классы. Неизменяемые типы данных: int, float, decimal, bool, string, tuple, и range.

Python обрабатывает неизменяемые типы данных иначе. То есть сохраняет их в памяти только один раз.

Применим Python-функцию id(), которая вызывает уникальный идентификатор для каждого объекта:

s = "example"
print("Id of s: " + str(id(s)))
print("Id of the String 'example': " + str(id("example")) + " (note that it's the same as the variable s)")
print("s is 'example': " + str(s is "example"))

print("Change s to something else, then back to 'example'.")
s = "something else"
s = "example"
print("Id of s: " + str(id(s)))
print("s is 'example': " + str(s is "example"))
print()

list1 = 
list2 = list1
print("Id of list1: " + str(id(list1)))
print("Id of list2: " + str(id(list2)))
print("Id of : " + str(id()) + " (note that it's not the same as list1!)")
print("list1 == list2: " + str(list1 == list2))
print("list1 is list2: " + str(list1 is list2))

print("Change list1 to something else, then back to the original () value.")
list1 = 
list1 = 
print("Id of list1: " + str(id(list1)))
print("list1 == list2: " + str(list1 == list2))
print("list1 is list2: " + str(list1 is list2))

Выполнение кода выдаст следующий результат:

Id of s: 22531456
Id of the String 'example': 22531456 (note that it's the same as the variable s)
s is 'example': True
Change s to something else, then back to 'example'.
Id of s: 22531456
s is 'example': True

Id of list1: 22103504
Id of list2: 22103504
Id of : 22104664 (note that it's not the same as list1!)
list1 == list2: True
list1 is list2: True
Change list1 to something else, then back to the original () value.
Id of list1: 22591368
list1 == list2: True
list1 is list2: False

В первой части примера переменная возвратит тот же объект , которым она была инициализирована в начале, даже если мы изменим ее значение.

Но не возвращает тот же объект, значение которого равно . При этом создается новый объект, даже если он имеет то же значение, что и первый .

При выполнении кода вы получите разные идентификаторы для объектов, но они будут одинаковыми.

Method 4: Use the logging module

We can use Python’s logging module to print to the file. This is preferred over Method 2, where explicitly changing the file streams is not be the most optimal solution.

import logging

# Create the file
# and output every level since 'DEBUG' is used
# and remove all headers in the output
# using empty format=''
logging.basicConfig(filename='output.txt', level=logging.DEBUG, format='')

logging.debug('Hi')
logging.info('Hello from AskPython')
logging.warning('exit')

This will, by default, append the three lines to . We have thus printed to the file using , which is one of the recommended ways of printing to a file.

Flushing in print

This is probably one of the most ignored concepts. Probably because we don’t see any direct impact while we are printing. But it is an important concept.

Usually, Python buffers the messages that you want to print until it gets a newline().

What is Buffer?

A buffer temporarily stores data that is being transmitted from one place to another in the main memory.

The argument ensures that everything in the buffer is immediately sent to the destination.

Let’s see this through an example. Instead of the default value for the argument (), we are going to leave it empty.

When you run the above snippet, the print message will only show up after the 5 seconds of sleep is over. Why? because print expects a or a newline at the end of every print statement. Hence, your message is in the buffer.

Using the argument, in Python 3, you can directly print the message to the standard output stream without having to wait for the sleep time to finish.

Try this out.

Наследование класса в Python

Создавая новые классы не обязательно их создавать с нуля. Новый класс может наследовать свои атрибуты (переменные) и методы (функции принадлежащие классам) от ранее определенного исходного класса ( суперкласса ). Также исходный класс называют родителем, а новый класс — потомком или подклассом. В класс-потомок можно добавлять собственные атрибуты и методы. Напишем новый класс , который будет создан на базе класса :

class Car():
    «»»Описание автомобиля»»»
    def __init__(self, brand, model, years):
        «»»Инициализирует атрибуты brand и model»»»
        self.brand = brand
        self.model = model
        self.years = years
        self.mileage = 0

    def get_full_name(self):
        «»»Автомобиль»»»
        name = f»Автомобиль {self.brand} {self.model} {self.years}»
        return name.title()

    def read_mileage(self):
        «»»Пробег автомобиля»»»
        print(f»Пробег автомобиля {self.mileage} км.»)

    def update_mileage(self, new_mileage):
        «»»Устанавливает новое значение пробега»»»
        self.mileage = new_mileage
    
    def add_mileage(self, km):
        «»»Добавляет пробег»»»
        self.mileage += km

class ElectricCar(Car):
    «»»Описывает электромобиль»»»
    def __init__(self, brand, model, years):
        «»»Инициализирует атрибуты класса родителя»»»
        super().__init__(brand, model, years)
        # атрибут класса-потомка
        self.battery_size = 100

    def battery_power(self):
        «»»Выводит мощность аккумулятора авто»»»
        print(«Мощность аккумулятора {self.battery_size} кВт⋅ч»)

Мы создали класс на базе класса. Имя класса-родителя в этом случае ставится в круглые скобки( class ElectricCar(Car) ). Метод __init__  в классе потомка (подклассе) инициализирует атрибуты класса-родителя и создает экземпляр класса . Функция super() .- специальная функция, которая приказывает Python вызвать метод __init__() родительского класса Car, в результате чего экземпляр ElectricCar получает доступ ко всем атрибутам класса-родителя. Имя super как раз и происходит из-за того, что класс-родителя называют суперклассом, а класс-потомок — подклассом.          

Далее мы добавили новый атрибут и присвоили исходное значение 100. Этот атрибут будет присутствовать во всех экземплярах класса . Добавим новый метод battery_power(), который будет выводить информацию о мощности аккумулятора.         

Создадим экземпляр класса  и сохраним его в переменную tesla_1

tesla_1 = ElectricCar(‘tesla’, ‘model x’, 2021)
print(tesla_1.get_full_name())
tesla_1.battery_power()

При вызове двух методов мы получим:

Автомобиль Tesla Model X 2021
Мощность аккумулятора 100 кВт⋅ч

В новый класс  мы можем добавлять любое количество атрибутов и методов связанных и не связанных с классом-родителем .    

3.1. Переопределение методов класса-родителя

Методы, которые используются в родительском классе можно переопределить в классе-потомке (подклассе). Для этого в классе-потомке определяется метод с тем же именем, что и у класса-родителя. Python игнорирует метод родителя и переходит на метод, написанный в классе-потомке (подклассе). Переопределим метод def get_full_name() чтобы сразу выводилась мощность аккумуляторов. 

class ElectricCar(Car):
    «»»Описывает электромобиль»»»
    def __init__(self, brand, model, years):
        «»»Инициализирует атрибуты класса родителя»»»
        super().__init__(brand, model, years)
        # атрибут класса-потомка
        self.battery_size = 100

    def battery_power(self):
        «»»Выводит мощность аккумулятора авто»»»
        print(«Мощность аккумулятора {self.battery_size} кВт⋅ч»)

    def get_full_name(self):
        «»»Автомобиль»»»
        name = f»Автомобиль {self.brand} {self.model} {self.years} {self.battery_size}-кВт⋅ч »
         name.
 

В результате при запросе полного названия автомобиля Python проигнорирует метод def get_full_name() в классе-родителя и сразу перейдет к методу def get_full_name() написанный в классе .          

tesla_1 = ElectricCar(‘tesla’, ‘model x’, 2021)
print(tesla_1.get_full_name())

Автомобиль Tesla Model X 2021 100-Квт⋅Ч

Please enable JavaScript to view the comments powered by Disqus.

Кавычки

Одинарные кавычки

Строку можно указать, используя одинарные кавычки, как например, ‘Это строка’.  Любой одиночный символ в кавычках, например,  ‘ю’  — это строка. Пустая строка » — это тоже строка. То есть строкой мы считаем всё, что находится внутри кавычек.

Двойные кавычки

Запись строки в одинарных кавычках  это не единственный способ. Можно использовать и двойные кавычки, как например, »Это строка».  Для интерпретатора разницы между записями строки в одинарных и двойных кавычках нет.  

ВниманиеЕсли  строка началась с двойной кавычки — значит и закончиться должна на двойной кавычке. Если внутри строки мы хотим использовать двойные кавычки, то саму строку надо делать в одинарных кавычках. 

Театр »Современник»print(‘Театр »Современник»’)

Тройные кавычки

Строка, занимающая несколько строк,  должна быть обрамлена тройными кавычками (» » »  или »’).  Например:

Список

Список (list) представляет тип данных, который хранит набор или последовательность элементов. Для создания списка в квадратных скобках через запятую перечисляются все его элементы.

Создание пустого списка

numbers = [] 

Создание списка чисел:

numbers =  # имя списка numbers, он содержит 5 элементов

Создание списка слов:

words =  # имя списка words, он  содержит 4 элемента

Создание списка из элементов разного типа

listNum =  # имя списка listNum,    список     содержит целые числа и строки

Для управления элементами списки имеют целый ряд методов. Некоторые из них:

append(item): добавляет элемент item в конец списка
insert(index, item): добавляет элемент item в список по индексу index
remove(item): удаляет элемент item. Удаляется только первое вхождение элемента. Если элемент не найден, генерирует исключение ValueError
clear(): удаление всех элементов из списка
index(item): возвращает индекс элемента item. Если элемент не найден, генерирует исключение ValueError
pop(): удаляет и возвращает элемент по индексу index. Если индекс не передан, то просто удаляет последний элемент.
count(item): возвращает количество вхождений элемента item в список
sort(): сортирует элементы. По умолчанию сортирует по возрастанию. Но с помощью параметра key мы можем передать функцию сортировки.
reverse(): расставляет все элементы в списке в обратном порядке

Кроме того, Python предоставляет ряд встроенных функций для работы со списками:

len(list): возвращает длину списка
sorted(list, ): возвращает отсортированный список
min(list): возвращает наименьший элемент списка

Встроенные функции

print (x, sep = 'y') печатает x объектов, разделенных y
len (x) возвращает длину x (s, L или D)
min (L ) возвращает минимальное значение в L
max (L) возвращает максимальное значение в L
sum (L) возвращает сумму значений в диапазоне L
range(n1,n2,n) (n1, n2, n) возвращает последовательность чисел от n1 до n2 с шагом n
abs (n) возвращает абсолютное значение n
round (n1, n) возвращает число n1, округленное до n цифр
type (x) возвращает тип x (string, float, list, dict…)
str (x) преобразует x в string 
list (x) преобразует x в список
int (x) преобразует x в целое число
float (x) преобразует x в число с плавающей запятой
help (s) печатает справку о x
map (function, L) Применяет функцию к значениям в L

Examples

For..Else

for x in range(3):
    print(x)
else:
    print('Final x = %d' % (x))

Strings as an iterable

string = "Hello World"
for x in string:
    print(x)

Lists as an iterable

collection = 
for x in collection:
    print(x)

Loop over Lists of lists

list_of_lists = , , ]
for list in list_of_lists:
    for x in list:
        print(x)

Creating your own iterable

class Iterable(object):

    def __init__(self,values):
        self.values = values
        self.location = 0

    def __iter__(self):
        return self

    def next(self):
        if self.location == len(self.values):
            raise StopIteration
        value = self.values
        self.location += 1
        return value

Your own range generator using yield

def my_range(start, end, step):
    while start <= end:
        yield start
        start += step

for x in my_range(1, 10, 0.5):
    print(x)

Printing multiple elements to the same line

We can use print to write multiple elements in a single line.

Print adds a whitespace between each object before writing it to the standard output. In Python 3, you can see a argument. It has been set to by default.

Both the below statements produce the same result.

The same thing happens with Python 2. However, there is no argument in Python 2. White space is added in between objects by default.

You can also pass in a different value to the argument in Python 3. For e.g., you could also use `|` as a separator while printing.

The above can’t be achieved with Python 2 using a print statement. However, you can use the built-in method in Python 2 to emulate the print function in Python 3.

Применение lambda в sort, filter, map, reduce

На практике сортировка – одна из самых популярных манипуляций с данными. Например, имеется список слов, которые нужно отсортировать по последней букве. Для этого нужно указать аргумент  – функцию, с помощью которой будет происходить сравнение элементов. Этой функцией может служить наша lambda:

>>> words = 
>>> sorted(words, key=lambda x: x)

В качестве индекса мы указали -1, обозначающий последний элемент строки (str), т.е. последней буквы.

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

>>> nums = 
>>> even = filter(lambda x: x % 2 == 0, nums)
>>> list(even)

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

Третий пример – это использование lambda-функций в отображениях нового пространства. Требуется из заданного списка чисел получить список кубов этих чисел. С помощью  это будет выглядеть так:

>>> nums = 
>>> cubes = map(lambda x: x**3, nums)
>>> list(cubes)

 принимает первым аргументом функцию, отображающую список в новом пространстве. Здесь была использована анонимная функция, которая возводит элемент в 3-ю степень.

Четвертый пример, где используется lambda-функции – это . Если необходимо получить из списка одно значение, то используется  из Python-модуля . Получение произведения чисел в списке будет выглядеть следующим образом:

>>> nums = 
>>> reduce(lambda x, y: x * y, nums)
5040

Алгоритм выполнения reduce можно записать как . Каждый момент итерирования сопровождается обновлением первого аргумента lambda-функции x, таким образом, становясь результатом произведения.

Стоит отметить, не всегда lambda-функции являются уместными из-за их неочевидного интерфейса. Например, и могут быть переписаны через List comprehension, о котором мы говорили тут. Как использовать lambda-функции и List comprehension в реальных проектах Data Science, вы узнаете на наших практических курсах по Python в лицензированном учебном центре обучения и повышения квалификации ИТ-специалистов в Москве.

Смотреть расписание
Записаться на курс

Источники

Writing a Hello World program

Let’s begin with a program.

YES. It is that easy.

You can notice that you need to pass in your messages inside a bracket in Python 3 compared to Python 2. It’s because print is a function in Python 3. It was a statement in Python 2.

A statement in Python is a line of code that provides instruction or commands for Python to perform. A statement never returns any value.

Functions on the other hand are a collection of statements that when called perform an intended action. They are organized and reusable in nature. Functions always return a value.

Now the above example is required when you are within an IDE. If you are running your Python code on the command line, you don’t even need to use print.

Print by default provides an interface to the standard output() object. When you use print, you are asking your Python interpreter to echo your message to standard output. For example, you can also print a message, without using print.

You use the method in sys.stdout to output your message to the standard output stream.

However, Print is just easier to use.

Строки

Строка – это последовательность символов. Чаще всего строки – это просто некоторые наборы слов. Слова могут быть как на английском языке, так и  почти на любом языке мира.

Операции со строками

string извлекает символ в позиции i
string извлекает последний символ
string извлекает символы в диапазоне от i до j

Методы работы сос строками

string.upper() преобразует строку в верхний регистр
String.lower() преобразует в строку в нижний регистр
string.count(x) подсчитывает, сколько раз появляется x
string.find(x) позиция первой строки вхождения x
string.replace(x, y) заменяет x на y
string.strip(x) удаляет как начальные, так и конечные символы x
string.join (List) объединяет список строк

Conversion Types in Python Print function

The list of conversion types that are available in the Python print function. 

  • %c – Returns a Single character.
  • %d – Returns a Decimal Integer
  • %i – for Long integer
  • %u – Returns an unsigned decimal integer
  • %e, %E – Returns the floating-point value in exponential notation. 
  • %f – Returns the floating-point value in fixed-point notation. 
  • %g – Returns the shorter value of %f and %e
  • %G – Returns the shorter value of %f and %E
  • %c – Returns a Single character
  • %o – Returns an Octal value
  • %r – Generates string with repr()
  • %s – Converts the value to a string using str() function.
  • %x, %X – Returns the Hexadecimal integer.

Let me use all the available conversion types. For this, we declared a few variables with a numeric value, string, decimal value, and a character.

print function conversion types output

Python print file example

Here, we are opening a file pythonSample.txt (if it exists). Otherwise, it creates that text file in the default directory. Next, the print function prints the statement inside that text file.

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

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

Adblock
detector