Как написать простой код на python

В этом разделе мы обсудим основной синтаксис и разберем пример Python – запустим простую программу для печати Hello World на консоли.

Python предоставляет нам два способа запуска программы:

  • Использование подсказки интерактивного помощника.
  • Использование файла сценария.

Давайте подробно обсудим каждый из них.

Интерактивная подсказка помощника

Python предоставляет нам возможность выполнять инструкции интерактивного помощника. Это предпочтительнее в том случае, когда нас беспокоит вывод каждой строки программы Python.

Чтобы использовать интерактивный режим, откройте терминал(или командную строку) и введите python(python3 в случае, если в вашей системе установлены Python2 и Python3).

Откроется следующее приглашение, в котором мы можем выполнить оператор Python и проверить влияние на консоль.

Первый способ

После написания отчета о печати нажмите клавишу Enter.

Результат "Hello World!"

Здесь мы получаем сообщение “Hello World!” на консоли.

Использование файла сценария(Программирование в режиме сценария)

Подсказка интерпретатора лучше всего подходит для выполнения однострочных операторов кода. Однако мы не можем писать код каждый раз на терминале. Не рекомендуется писать несколько строк кода.

Используя режим сценария, мы можем записать многострочный код в файл, который может быть выполнен позже. Для этого нам нужно открыть редактор, например блокнот, создать файл с именем и сохранить его с расширением .py, что означает «Python». Теперь мы реализуем приведенный выше пример, используя режим скрипта.

print("hello world"); #here, we have used print() function to print the message on the console.  

Чтобы запустить этот файл с именем first.py, нам нужно запустить следующую команду на терминале.

Режим скрипта

Шаг – 1: Откройте интерактивную оболочку Python и нажмите «Файл», затем выберите «Создать», откроется новый пустой скрипт, в котором мы можем написать наш код.

Создание нового файла

Шаг 2: Теперь напишите код и нажмите «Ctrl + S», чтобы сохранить файл.

Результат Hello World

Шаг – 3: После сохранения кода мы можем запустить его, нажав «Выполнить» или «Выполнить модуль». Он отобразит вывод в оболочку.

Выполнить модуль

Результат будет показан следующим образом.

Hello World

Шаг – 4: Кроме того, мы также можем запустить файл с помощью терминала операционной системы. Но мы должны знать путь к каталогу, в котором мы сохранили наш файл.

  • Откройте командную строку и перейдите в каталог.

Командная строка

  • Нам нужно ввести ключевое слово python, затем имя файла и нажать Enter, чтобы запустить файл Python.

Ввод ключевого слова и имени файла

Многострочные операторы

Многострочные операторы записываются в блокнот как редактор и сохраняются с расширением .py. В следующем примере мы определим выполнение нескольких строк кода с помощью скрипта Python.

Код:

name = "Andrew Venis"
branch = "Computer Science"
age = "25"
print("My name is: ", name, )
print("My age is: ", age)

Файл сценария:

Результат

Первая программа на Python

Плюсы и минусы режима сценария

Режим сценария также имеет несколько преимуществ и недостатков. Давайте разберемся в следующих преимуществах запуска кода в режиме скрипта:

  • Мы можем запускать несколько строк кода.
  • Отладка выполняется легко в режиме сценария.
  • Подходит как для новичков, так и для экспертов.

Посмотрим на недостатки скриптового режима:

  • Нужно сохранять код каждый раз, если мы вносим в него какие-либо изменения.
  • Когда мы запускаем одну или несколько строк кода, это может быть утомительно.

Начало работы с PyCharm

В нашей первой программе мы использовали gedit в CentOS в качестве редактора. В Windows у нас есть альтернатива, например блокнот или блокнот ++, для редактирования кода. Однако эти редакторы не используются в качестве IDE для Python, поскольку они не могут отображать предложения, связанные с синтаксисом.

JetBrains предоставляет самую популярную и широко используемую кроссплатформенную IDE PyCharm для запуска программ Python.

Установка PyCharm

Как мы уже говорили, PyCharm – это кроссплатформенная IDE, поэтому ее можно установить в различных операционных системах. В этом разделе руководства мы рассмотрим процесс установки PyCharm в Windows, MacOS, CentOS и Ubuntu.

Windows

Установить PyCharm в Windows очень просто. Чтобы установить PyCharm в операционной системе Windows, перейдите по ссылке https://www.jetbrains.com/pycharm/download/download-thanks.html?platform=windows, чтобы загрузить установщика. Дважды щелкните файл установки(.exe) и установите PyCharm, нажимая «Далее» на каждом шаге.

Чтобы создать первую программу для Pycharm, выполните следующий шаг.

Шаг – 1. Откройте редактор Pycharm. Нажмите на «Создать новый проект», чтобы создать новый проект.

Работа с PyCharm

Шаг – 2. Выберите место для сохранения проекта.

  1. Мы можем сохранить созданный проект в  выбранном по желанию месте памяти или оставить расположение файла как есть, но, по крайней мере, изменить имя проекта по умолчанию без названия на «FirstProject» или что-то значимое.
  2. Pycharm автоматически найдет установленный интерпретатор Python.
  3. После изменения имени нажмите кнопку «Создать».

Шаг 2

Шаг – 3. Щелкните меню «Файл» и выберите «Новый». При нажатии на опцию «Новый» он покажет различные форматы файлов. Выберите «Файл Python».

Выбор файла Python

Шаг – 4. Теперь введите имя файла Python и нажмите «ОК». Мы написали «Первую программу».

Шаг 4

Шаг – 5. Теперь введите первую программу – print(«Hello World»), затем нажмите меню «Выполнить», чтобы запустить программу.

Запуск первой программы на Python

Шаг – 6. Результат появится внизу экрана.

Шаг 6 - результат работы

Отступы в Python

Отступы – наиболее важная концепция языка программирования Python. Неправильное использование отступов приведет к ошибке “IndentationError” в нашем коде.

Отступы – это не что иное, как добавление пробелов перед оператором, когда это необходимо. Без отступа Python не знает, какой оператор выполнять следующим. Отступ также определяет, какие операторы принадлежат какому блоку. Если нет отступа или  отступ неправильный, отобразится «IndentationError» и прервет наш код.

Отступы на Python

Отступы Python определяют, какая группа операторов принадлежит конкретному блоку. В языках программирования, таких как C, C ++, java, для определения блоков кода используются фигурные скобки {}.

В Python операторы, находящиеся на одном уровне справа, принадлежат одному блоку. Мы можем использовать четыре пробела для определения отступа. Давайте посмотрим на следующие строки кода.

Пример –

list1 = [1, 2, 3, 4, 5]
for i in list1:
    print(i)
    if i==4:
       break
print("End of for loop")

Выход:

1
2
3
4
End of for loop

Объяснение:

В приведенном выше коде цикл for имеет блоки кода, если оператор имеет блок кода внутри цикла for. Оба с четырьмя пробелами с отступом. Последний оператор print() без отступа; это означает, что он не принадлежит циклу for.

Комментарии в Python

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

В Python мы можем применять комментарии, используя символ решетки #. Интерпретатор Python полностью игнорирует строки, за которыми следует символ решетки. Хороший программист всегда использует комментарии, чтобы сделать код стабильным. Давайте посмотрим на следующий пример комментария.

name  = "Thomas"   # Assigning string value to the name variable 

Мы можем добавить комментарий в каждую строку кода Python.

Fees = 10000      # defining course fees is 10000
Fees = 20000      # defining course fees is 20000

Хорошая идея – добавить код в любую строку раздела кода, цель которого неочевидна. Это лучший способ изучить при написании кода.

Типы комментариев

Python предоставляет возможность писать комментарии двумя способами – однострочный комментарий и многострочный комментарий.

Однострочный комментарий начинается с символа решетки #, за которым следует текст для дальнейшего объяснения.

# defining the marks of a student 
Marks = 90

Мы также можем написать комментарий рядом с оператором кода. Рассмотрим следующий пример.

Name = "James"   # the name of a student is James
Marks = 90            # defining student's marks
Branch = "Computer Science"   # defining student branch

Многострочные комментарии – Python не имеет явной поддержки многострочных комментариев, но мы можем использовать символ решетки # для нескольких строк. Например –

# we are defining for loop
# To iterate the given list.
# run this code.

Мы также можем использовать другой способ.

" " " 
This is an example
Of multi-line comment
Using triple-quotes 
" " "

Это основное введение в комментарии. Просмотрите наш урок по комментариям Python, чтобы изучить его подробно.

Идентификаторы Python

Идентификаторы Python относятся к имени, используемому для идентификации переменной, функции, модуля, класса, модуля или других объектов. Есть несколько правил, которым нужно следовать при присвоении имени переменной Python.

  • Имя переменной должно начинаться с английской буквы или символа подчеркивания(_).
  • Имя переменной не может начинаться с числа.
  • В имени переменной нельзя использовать специальные символы.
  • Имя переменной чувствительно к регистру.

Пример –

number = 10
print(num)

_a = 100
print(_a)

x_y = 1000
print(x_y)

Выход:

10
100
1000

Мы определили базовый синтаксис языка программирования Python. Мы должны ознакомиться с основной концепцией любого языка программирования. Как только мы запомним концепции, упомянутые выше, изучение Python станет проще.

Изучаю Python вместе с вами, читаю, собираю и записываю информацию опытных программистов.


Загрузить PDF


Загрузить PDF

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

Шаги

  1. Изображение с названием 1291077 1 2

    1

    Откройте новое окно в оболочке Python. Для этого нажмите Ctrl+N или откройте меню «File» (Файл) и выберите «New window» (Новое окно).

  2. Изображение с названием 1291077 2 2

    2

    Добавьте вводное предложение. Для этого воспользуйтесь функцией «print». Введите первую строку кода:

    print("Вычислим, сколько дней, минут и секунд вы живете.")
    
  3. Изображение с названием 1291077 3 2

    3

    Чтобы узнать имя пользователя, введите вторую строку кода:

    • Переменной «name» будет присвоено имя пользователя.
  4. Изображение с названием 1291077 4 2

    4

    Чтобы узнать возраст, воспользуйтесь функцией «int», потому что пользователь введет цифру:

    print("Введите свой возраст")
    age = int(input("возраст: "))
    
    • Переменой «age» будет присвоен возраст пользователя.
  5. Изображение с названием 1291077 5 2

    5

    Преобразуйте веденный возраст.

    days = age * 365
    minutes = age * 525948     
    seconds = age * 31556926
    
    • Эти строки автоматически вычислят количество дней, минут и секунд на основании введенного возраста.
  6. Изображение с названием 1291077 6 2

    6

    Выведите информацию на экран.

    print(name, "прожил(а)", days, "дней", minutes, "минут и", seconds, "секунд!")
    
  7. Изображение с названием 1291077 7 2

    7

    Поздравьте себя, потому что вы написали программный код, который работает! Сохраните его и запустите; для этого нажмите «Run» (Запустить) > «Run module» (Запустить модуль).

    Реклама

Об этой статье

Эту страницу просматривали 64 310 раз.

Была ли эта статья полезной?

In this article, you will find a comprehensive list of Python code examples that cover most of the basics.

This list of 100 useful Python examples is intended to support someone who is:

  • Preparing for a coding interview.
  • Preparing for an examination.
  • Exploring what programming is.
  • Teaching Python and wants to find useful examples

Without further ado, let’s get coding!

1. Print ‘Hello World!’ in the Console

The simplest and probably the most common example of Python is the “Hello world” program.

Here is how it looks:

print("Hello World!")

Output:

Hello World!

2. Ask User Their Name and Greet Them

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

For instance, you can store user input to a variable and use that variable in a greeting.

Here is the code:

name = input("Please, enter your name: ")

print(f"Hello, {name}!")

Output:

Please, enter your name: Jack
Hello, Jack!

3. Create a List of Names in Python

To create a list in Python, add comma-separated values between braces.

For instance, here is a list of names in Python:

names = ["Alice", "Bob", "Charlie"]

4. Merge Two Lists

Given two or more lists in Python, you may want to merge them into a single list.

This is easy in Python. Use the + operator you would use when summing up numbers. In the case of lists, this merges the lists into one.

For instance:

numbers1 = [1, 2, 3]
numbers2 = [4, 5, 6]

merged = numbers1 + numbers2

print(merged)

Output:

[1, 2, 3, 4, 5, 6]

5. Loop Through a List of Names and Print Each

A powerful feature of Python lists is that they are iterable.

In other words, you can easily loop through the items on the list to do something for them.

For example, let’s create a list of names and print each name into the console:

names = ["Alice", "Bob", "Charlie"]

for name in names:
    print(name)

Output:

Alice
Bob
Charlie

6. Get Rid of Spaces in Python String

To get rid of spaces in a Python string, replace all blank spaces with an empty string.

You can do this with the replace() method.

For instance:

sentence = "Hello, this is a sentence."

no_spaces = sentence.replace(" ", "")

print(no_spaces)

Output:

Hello,thisisasentence.

7. Calculate the Number of Spaces in a String

A Python string has a built-in method count(). You can use it to count how many times a substring occurs in a string.

For instance, let’s calculate how many blank spaces there are in a string:

sentence = "Hello, this is a sentence."

num_spaces = sentence.count(" ")

print(f"There are {num_spaces} spaces in the sentence.")

Output:

There are 4 spaces in the sentence.

8. Check If a String Is a Palindrome

To check if a string is a palindrome in Python, that is, the same when reversed:

  • reverse the string and compare it with the original string.

For example:

def is_palindrome(word):
    if word == word[::-1]:
        print(f"The word {word} is a palindrome.")
    else:
        print(f"The word {word} is not a palindrome.")

is_palindrome("redivider")

Output:

The word redivider is a palindrome.

9. Find a Substring in a String

To find a specific substring inside a string in Python, use the built-in find() method of a string.

For example:

sentence = "This is just a test"
target = "just"

idx = sentence.find(target)

print(f"The word '{target}'' starts at index {idx} in '{sentence}'")

Output:

The word 'just' starts at index 8 in 'This is just a test'

10. Add Two Numbers

To create a function that adds two numbers:

  • Create a function that takes two number arguments
  • Sum up the arguments
  • Return the result

For example:

def sum(a, b):
    return a + b

print(sum(1,2))

Output:

3

11. Find Maximum of Two Numbers in Python

To find the maximum value between two (or more) numbers in Python, use the built-in max() function.

For instance:

n1 = 10
n2 = 100

maximum = max(n1, n2)

print(f"The maximum number is {maximum}")

Output:

The maximum number is 100

12. Find the Minimum of Two Numbers in Python

To find the minimum value between two (or more) numbers in Python, use the built-in min() function.

For instance:

n1 = 10
n2 = 100

minimum = min(n1, n2)

print(f"The minimum number is {minimum}")

Output:

The minimum number is 10

13. Find the Average of a List of Numbers in Python

To compute the average of something, you need to know two things:

  1. The number of elements.
  2. The sum of all the elements.

Given these, you can calculate the average by sum/length.

In Python, you can do it like this:

nums = [1, 2, 3, 4, 5]

total = sum(nums)
length = len(nums)

average = total / length

print(f"The average of {nums} is {average}")

Output:

The average of [1, 2, 3, 4, 5] is 3.0

14. Check If a Year Is a Leap Year in Python

By definition, a leap year is a year that:

  • Is divisible by 4…
  • And not divisible by 100…
  • Unless also divisible by 400.

In Python, you can write a function that implements these three checks to find if a given year is a leap year.

Here is how:

# A function that checks if a year is a leap year
def is_leap(year):
    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

# Example
year = 2020

if is_leap(year):
    print(f"The year {year} is a leap year")
else:
    print(f"The year {year} is not a leap year")

Output:

The year 2020 is a leap year

15. Find The Maximum Value of a Python Dictionary

To find the maximum value of a dictionary, you need:

  1. To access all the values of the dictionary using the dict.values() method.
  2. Find the greatest value using max() function.
data = {"Alice": 23, "Bob": 54, "Charlie": 12}

ages = data.values()

max_age = max(ages)

print(f"The oldest person is {max_age} years old.")

Output:

The oldest person is 54 years old.

16. Merge Two Python Dictionaries

To merge two dictionaries in Python, use the double-asterisk notation to unpack the dictionary items into one dictionary.

For example, here is a function that does it for you:

# Merger function
def merge(d1, d2):
    return {**d1, **d2}
    
# Example code
data1 = {"Alice": 23, "Bob": 32}
data2 = {"Charlie": 77, "David": 19}

both = merge(data1, data2)

print(both)

Output:

{'Alice': 23, 'Bob': 32, 'Charlie': 77, 'David': 19}

17. Check If a Key Exists in a Python Dictionary

To check if a key exists in a dictionary, you can use the in operator.

For instance:

data1 = {"Alice": 23, "Bob": 32}

exists = "Alice" in data1

print(exists)

Output:

True

18. Delete an Element from a Python Dictionary

To delete an entry from a dictionary, use the del operator.

For example:

data1 = {"Alice": 23, "Bob": 32}

del data1["Alice"]

print(data1)

Output:

{'Bob': 32}

Learn more about dictionaries in Python.

19. Find the Distance Between Two 2D Points in Python

To calculate the distance between two points, use the Pythagorean theorem.

For example, here is a function that calculates the distance between two 2D points.

from math import sqrt

def distance(p1, p2):
    return sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2)
    
start = (1, 1)
end = (2, 2)

dist = distance(start, end)

print(f"The distance between {start} and {end} is {dist}")

Output:

The distance between (1, 1) and (2, 2) is 1.4142135623730951

Notice that there is a built-in function dist() in the math module that does the exact same for you:

from math import sqrt, dist

start = (1, 1)
end = (2, 2)

dist = dist(start, end)

print(f"The distance between {start} and {end} is {dist}")

Output:

The distance between (1, 1) and (2, 2) is 1.4142135623730951

20. Read a File Line by Line in Python

To open a file, and read it line by line in Python, you need to:

  1. Open a file behind a path.
  2. Read and store the lines of the file.
  3. Close the file.

To do this, use a context manager. A context manager automatically closes the file once processing has been completed.

To open the file with a context manager, use the with statement.

Given a file example.txt in the same folder that looks like this:

This is a test
The file contains a bunch of words
Bye!

You can read the file line by line with a context manager using the following code:

with open("example.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        print(line)

Output:

This is a test

The file contains a bunch of words

Bye!

21. Check If a File Contains a Specific Word

To check if a file has a specific word, you need to:

  1. Open the file behind the path.
  2. Read the contents of the file in memory.
  3. Test if a specific word is found in the content.
  4. Close the file.

To do this, use a context manager. A context manager automatically closes the file once processing has been completed.

To open the file with a context manager, use the with statement.

Given a file called example.txt with contents like this:

This is a test
The file contains a bunch of words
Bye!

You can check if a specific word exists in that file with this piece of code:

with open("example.txt", "r") as file:
    has_word = "test" in file.read()
    if has_word:
        print("The file has the word 'test'")

Output:

The file has the word 'test'

22. Count the Frequency of a Word in a File

To count the frequency of a specific word in a text file in Python:

  1. Open the file behind the path.
  2. Read the contents of the file in memory.
  3. Count the number of occurrences of a string.
  4. Close the file.

To do this, use a context manager. A context manager automatically closes the file once processing has been completed.

To open the file with a context manager, use the with statement.

Given a file called example.txt with contents like this:

This is a test
The file contains a bunch of test words
Bye!

You can check many times the word “test” occurs in a file by:

with open("example.txt", "r") as file:
    n = file.read().count("test")
    print(n)

Output:

2

23. Swap Two Values without a Third

This is one is a classic examination question.

Is there a way to swap two variables without a third helper variable?

The answer is yes. You can use tuple unpacking to achieve this.

For example:

a = 1
b = 2

a, b = b, a

print(a, b)

Output:

2 1

24. Check If a Given Number Is a Prime Number

A prime number is any positive non-zero number that is only divisible by itself or by 1.

For example, 11 is a prime number.

To create a Python program that finds if a number is a prime number, you need to:

  1. Have a target number.
  2. Ensure the number is more than 1.
  3. Loop through all the numbers that are less than half the target number.
  4. Check if any number divides the target evenly.

For example, to check if 11 is a prime number, you need to check if any of the following numbers divides it evenly: 2, 3, 4, 5.

Here is a Python program that checks if a given number is a prime number:

def is_prime(number):
    if number > 1:
        for i in range(2, int(number / 2) + 1):
            if number % i == 0:
                print(f"{number} is not a prime number.")
                break
        else:
            print(f"{number} is a prime number.")
    else:
        print(f"{number} is not a prime number.")
        
is_prime(11)
is_prime(7)
is_prime(16)

Output:

11 is a prime number.
7 is a prime number.
16 is not a prime number.

25. Calculate Simple Interest in Python

Simple Interest is calculated using the following formula:

SI = (P × R × T) / 100

Where:

  • P = Principal amount of money.
  • R = Rate of Interest (e.g. 7%).
  • T = Time period.

The principal is the sum of money that remains constant every year in the case of simple interest.

Here is a Python program to figure out the simple interest:

def simple_interest(p, t, r):
    """
    p = principal amount
    t = time interval
    r = rate of interest
    
    si = simple interest given p, t, r
    """
      
    si = (p * t * r)/100
      
    print("The Simple Interest is", si)
    return si
    
simple_interest(1200, 10, 7)

Output:

The Simple Interest is 840.0

This returns the earnings during the period. To get the total amount of money, add this result to the principal amount.

26. Ask a Word from the User and Reverse It

In Python, you can reverse a string by calling string[::-1].

For example, to ask the user a word and reverse it, use the following piece of code:

word = input("Give a word, I will reverse it: ")

print(word[::-1])

Example run:

Give a word, I will reverse it: testing
gnitset

27. Ask User a Sequence of Numbers and Reverse Them

To create a program that asks the user for a sequence of numbers and reverses it:

  1. Ask user for comma-separated number input.
  2. Split the resulting string by commas. This creates a list of strings that represent numbers.
  3. Convert the list of number strings to a list of integers.
  4. Call the built-in reversed() function on the list of integers to reverse the order.

Here is the code for you:

# 1
num_strs = input("Give a comma-separated numbers: ")

# 2
num_str_list = num_strs.split(",")

# 3
num_ints = [int(num_str) for num_str in num_str_list]

# 4
reversed_nums = list(reversed(num_ints))

print(reversed_nums)

Output:

Give a comma-separated numbers: 1,2,3
[3, 2, 1]

28. Calculate BMI Index in Python

BMI or Body Measurement Index measures leanness or corpulence given height and weight.

The formula for BMI index given height in centimeters and weight in kilos is:

BMI = weight / (height/100)²

Here is a Python program that asks the user for weight and height and outputs their BMI:

weight = float(input("Enter your weight in kilos: "))
height = float(input("Enter your height in centimeters: "))

BMI = weight / (height/100)**2

print(f"Your weigh {weight}kg and you are {height}cm tall. This gives you BMI index of {BMI}")

Example input:

Enter your weight in kilos: 92
Enter your height in centimeters: 191
Your weigh 92.0kg and you are 191.0cm tall. This gives you BMI index of 25.218606946081522

29. Emit a Beep Sound in Python

On Windows, you can use the winsound module of Python to make a beeping sound.

For example, here is a program that produces a single high-pitch beep that lasts one second:

import winsound

frequency = 2500  # High pitch 2500HZ beep
duration = 1000  # Duration of the beep is 1s

winsound.Beep(frequency, duration)

30. Copy One File to Another in Python

Given a file called example.txt in your project’s folder, you can copy-paste its contents to another.txt file using shutil module’s copyfile function.

from shutil import copyfile

copyfile("example.txt", "another_example.txt")

31. Compute the Factorial of an Integer in Python

In mathematics, factorial is marked with an exclamation mark. Factorial means to multiply the number by all numbers from 1 to the number.

The factorial tells you how many ways there is to arrange n elements.

For example, to figure out how many ways there are to arrange 5 persons in a line, calculate the factorial of five: 5! = 5*4*3*2*1 = 120.

Here is a Python program that calculates the factorial given a number input. It starts with the target number. Then it subtracts one from the target and multiplies the target by this number. It does this until number 1 is reached.

def factorial(number):
    result = 1
    while number >= 1:
        result *= number
        number -= 1
    return result
    
print(factorial(5))

Output:

120

32. Find the Longest Word in a List

Python has a built-in function max(). If you call this function on a list of values, by default it returns the greatest element.

  • In the case of numbers, it returns the largest number.
  • In the case of strings, it returns the string with the highest ASCII value. Not the one with the greatest length!

To make the max() function return the longest string, you need to specify the max() function a second argument, key=len. This shows the max() function that we are interested in the maximum length, not the maximum ASCII value.

For instance:

names = ["Alice", "Bob", "Charlie"]

longest = max(names, key=len)

print(f"The longest name is {longest}")

Output:

The longest name is Charlie

33. Create Pyramid from Asterisks ‘*’

An asterisk pyramid may not be the most useful example, but it surely tests your understanding of loops and maths in Python.

To create a pyramid, you need to start with 1 asterisk. On the next line you have 3, then 5,7, and so on. In other words, the number of asterisks is 2*i + 1, where i is the row number (or the height) of the pyramid.

Now you got the number of asterisks.

Then you need to know how many spaces you need to the left of the asterisks to make it look like a pyramid.

In the first row, the number of spaces is the same as the height of the pyramid. Then on the second row, it is one less. On the third one less again. So you need to add one less space for each row of asterisks. In other words, the number of spaces is h-i-1, where h is the pyramid height and i is the row number.

def pyramid(rows):
    for i in range(rows):
        print(" "*(rows-i-1) + "*"*(2*i+1))

pyramid(12)

Output:

           *
          ***
         *****
        *******
       *********
      ***********
     *************
    ***************
   *****************
  *******************
 *********************
***********************

See also how to create a diamond pattern with asterisks.

34. Find the Intersection of Two Lists in Python

An intersection between two groups refers to the common elements among the groups.

To find the intersection between two lists:

  1. Loop through the other of the lists.
  2. Store the elements that are in the other list as well.
  3. Return the stored elements.

You can use a for loop, but let’s use a more compact expression called list comprehension. This is a shorthand of the for loop:

# A function that finds the intersection between two lists
def intersection(l1, l2):
    return [element for element in l1 if element in l2]

# Example run
names1 = ["Alice", "Bob", "Charlie"]
names2 = ["Alice", "Bob", "David", "Emmanuel"]

names_in_common = intersection(names1, names2)

print(f"Common names among the lists are {names_in_common}")

Output:

Common names among the lists are ['Alice', 'Bob']

35. Convert Celcius to Fahrenheit with Python

To convert temperatures from Celcius to Fahrenheit, use the following formula:

F = (9/5) * celcius + 32

To create a Python program to do this, write a function that:

  1. Takes a temperature measured in Celcius.
  2. Returns temperature in Fahrenheit with the help of the above formula.

Here is the code:

def as_fahrenheit(celcius):
    return 9/5 * celcius + 32
    
c = 37
f = as_fahrenheit(c)

print(f"{c} is {f} in Fahrenheits")

Output:

37 is 98.60000000000001 in Fahrenheits

36. Convert Kilograms to Pounds in Python

To convert weight from kilos to pounds, use the following formula:

p = kilos * 2.2048

To create a Python program to do this, write a function that:

  1. Takes a mass in kilos.
  2. Returns the weight in pounds with the help of the above formula.

Here is the code:

def as_pounds(kilos):
    return 2.2048 * kilos
    
kg = 80
pounds = as_pounds(kg)

print(f"{kg} is {pounds} in pounds")

Output:

80 is 176.38400000000001 in pounds

37. Count the Frequency of Each Letter in a String

To create a character to frequency mapping in Python:

  1. Define a target string.
  2. Create an empty character-to-frequency dictionary.
  3. Loop through the characters of the string.
  4. Add 1 to the frequency dictionary for each character.
  5. Return the dictionary.

Here is how it looks in code:

# A function tha calculates character frequencies in a string.
def letter_frequency(in_string):
    frequencies = {}
      
    for i in in_string:
        if i in frequencies:
            frequencies[i] += 1
        else:
            frequencies[i] = 1
    return frequencies

# Example run    
freqs = letter_frequency("This is just a test string")

print(freqs)

Output:

{'T': 1, 'h': 1, 'i': 3, 's': 5, ' ': 5, 'j': 1, 'u': 1, 't': 4, 'a': 1, 'e': 1, 'r': 1, 'n': 1, 'g': 1}

38. Count the Number of Seconds in a Year

In a year, there are roughly 365.25 days.

In a day there are 24 hours.

In an hour there are 60 minutes.

In a minute there are 60 seconds.

Thus, the number of seconds in a year is:

seconds = 365.25 * 24 * 60 * 60 = 31 557 600

You can calculate this in Python with:

year_seconds = 365.25 * 24 * 60 * 60

print(f"There are {year_seconds} in a year.")

Output:

There are 31557600.0 in a year.

39. Find the Number of Days Between Two Datesin Python

To work with dates in Python, use the datetime module.

To calculate the number of days between two dates (and get leap years correct):

  1. Create two datetime.date objects.
  2. Subtract the more recent date from the more past date.
  3. Call .days() method on the resulting date object to get the result.

In Python, it looks like this:

from datetime import date

d1 = date(2021, 3, 22)
d2 = date(2021, 10, 20)

diff = (d2 - d1).days

print(f"The difference between {d1} and {d2} is {diff} days")

Output:

The difference between 2021-03-22 and 2021-10-20 is 212 days

40. Generate Random Numbers Between a Range in Python

In Python, there is a built-in module for generating random numbers called random.

To generate random integers between an interval, call random.randint() method by providing it the max and min values.

For example:

from random import randint

# Print 10 random numbers between 1-100
for _ in range(10):
    print(randint(1,100))

Example output:

97
96
82
70
82
38
47
19
89
99

41. Get a Random Element from a List

The built-in random module comes in with a useful method called choice(). This method randomly selects an element from an iterable.

For example, to pick a random name at a list of strings:

from random import choice

names = ["Alice", "Bob", "Charlie", "David"]

rand_name = choice(names)

print(rand_name)

Output example:

David

42. Check If a Number Is Odd/Even

A number is even if it is evenly divisible by 2. In other words, if there is no remainder after division.

To check if a number is odd, check if it is not divisible by 2.

Here is a Python script that checks if the number 3 is odd or even:

number = 3

# Odd = not divisible by 2
# Even = divisible by 2
is_odd = True if number % 2 != 0 else False

print(is_odd)

Output:

True

43. Print a Multiplication Table of an Integer

A multiplication table is a table from where it is easy to check what times what gives what.

To produce a multiplication table of ten, for example, you want to:

  1. Select a target number.
  2. Loop from 1 to 10 and multiply the target number by each number in this range.
  3. Print the result to the console.
# Function that prints multiplication table from 1 to 10.
def mul_table(num):
    for i in range(1, 11):
       print(f"{num} x {i} = {num * i}")
       
# Example call
mul_table(9)

Output:

9 x 1 = 9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81
9 x 10 = 90

44. Print without New Line

By default, printing on a new line adds a new line in Python.

To overcome this, you need to join the printable items together separated by a blank space.

To do this, use the str.join() method in a blank space. This joins the elements of a list separated by a blank space.

Then you can print this whole string. As it is one string, it naturally gets printed on one line.

For example:

names = ["Alice", "Bob", "Charlie", "David"]

print(" ".join(names))

Output:

Alice Bob Charlie David

45. Find a Sum of any Number of Numbers

A Python function can accept any number of arguments. To do this, you need to use an asterisk in front of the argument name. This tells the Python interpreter that there is going to be an arbitrary number of arguments.

For example, let’s create a function that adds up any numbers you pass it:

# A function with * accepts any number of arguments
def sum_nums(*nums):
    # Return the sum of the arguments
    return sum(nums)

# Example usage
s1 = sum_nums(1, 2, 3)
s2 = sum_nums(5, 10, 15, 20, 25, 30)

print(s1, s2)

Output:

6 105

46. Find ASCII Value of a Character in Python

Each character and string in Python has an ASCII value behind the scenes. This value is just an integer ID of that character.

To figure out the ASCII value of a given character, use the built-in ord() function on it.

For instance:

character = "A"

char_ASCII = ord(character)

print(f"The ascii value of '{character}' is {char_ASCII}")

Output:

The ascii value of 'A' is 65

47. Find Factors of a Number

A factor of a number means a number divided by the factor leaves no remainder.

For example, factors of number 12 are 1, 2, 3, 4, and 6.

To find all factors of a number:

  1. Loop through numbers from 1 all up to the target number.
  2. Check if the number divides the target evenly.
  3. Store each factor into a list.
  4. Finally, return the factors list.

Here is how it looks in Python:

# Loop from 1 to x and check if x is divisible by i
def get_factors(x):
   return [i for i in range(1, x+1) if x % i == 0]

# Example run
number = 460
factors = get_factors(number)

print(factors)

Output:

[1, 2, 4, 5, 10, 20, 23, 46, 92, 115, 230, 460]

48. Simulate Coin Toss in Python

To simulate a coin toss, you need to randomly choose values of 0 or 1.

In Python’s random module, there is a function called choice(). This chooses a value from an iterable randomly.

To simulate coin toss, give this function a list that has 0 and 1. Then based on whether you got 0 or 1, display “Heads” or “Tails” in the console.

Here is how it looks in code:

from random import choice

# A function that randomizes between 0 and 1
def coin_toss():
    states = {1: "Heads", 0: "Tails"}
    one_or_zero = choice([0, 1])
    result = states[one_or_zero]
    print(result)

# Example run
coin_toss()

Output example:

Tails

49. Add Two Matrices in Python

Matrices are arrays of numbers that are arranged in rows and columns.

To add two matrices, you need to perform element-wise addition as described here.

In Python, you can represent matrices with lists of lists (nested lists). In this case, you can implement the matrix addition with the following piece of code:

# A function that finds the sum of two matrices
def add_matrices(X, Y):
    l = len(X[0])
    h = len(X)
    return [[X[i][j] + Y[i][j] for j in range(l)] for i in range(h)]

# Example run
X = [
    [1,7,1],
    [4,2,1],
    [7,9,9]
]

Y = [
    [1,8,1],
    [9,0,3],
    [2,4,7]
]

# Print rows to make the output readable in the console
for r in add_matrices(X, Y):
   print(r)

Output:

[2, 15, 2]
[13, 2, 4]
[9, 13, 16]

In this implementation, the 5th row is a list comprehension for loop. It represents a nested for loop where each matrix row and column is iterated through.

50. Transpose a Matrix in Python

A matrix transpose means the matrix is flipped over its diagonal.

In other words, each position (i, j) is replaced with (j, i) in the matrix.

In Python, you can use nested lists to represent matrices. When doing this, you can compute a transpose for the matrix with the following code:

# A function that transposes a matrix
def transpose(X):
    l = len(X[0])
    h = len(X)
    return [[X[j][i] for j in range(h)] for i in range(l)]

# Example run
X = [
    [1,7,1],
    [4,2,1],
    [7,9,9]
]

# Print rows to make the output readable in the console
for r in transpose(X):
   print(r)

Output:

[1, 4, 7]
[7, 2, 9]
[1, 1, 9]

In this implementation, the 5th row is a list comprehension for loop. It represents a nested for loop where each matrix row and column is iterated through.

51. Multiply Two Matrices in Python

To multiply two matrices, you need to implement the matrix multiplication algorithm.

Matrix multiplication means:

  1. Take a row from matrix A and a column on matrix B.
  2. Multiply the corresponding elements by one another.
  3. Sum up the results of the multiplications.
  4. Add the result to the result matrix at a corresponding position.
  5. Repeat until no rows are left.

An image is worth a thousand words, so here is one:

How to Multiply Matrices

Image Source: Math is fun

Here is how the algorithm looks in code:

# A function that multiplies two matrices
def multiply_matrices(X, Y):
    return [[sum(a * b for a, b in zip(X_row, Y_col)) for Y_col in zip(*Y)] for X_row in X]

# Example run
X = [
    [1,7,1],
    [4,2,1],
    [7,9,9]
]

Y = [
    [1,8,1],
    [9,0,3],
    [2,4,7]
]

# Print rows to make the output readable in the console
for r in multiply_matrices(X, Y):
   print(r)

Output:

[66, 12, 29]
[24, 36, 17]
[106, 92, 97]

In this implementation, the 3rd row is a list comprehension for loop. It is a nested loop where there are three inner for loops that implement the algorithm described above.

52. Track the Index in a For Loop

Sometimes when you perform a for loop, you wish there was an easy way to track the index of the current element. By default, this is not possible.

But using the built-in enumerate() function, you can relate each list element with an index.

This makes it easy for you to loop through the list and know the index at each loop.

Here is how it looks in code:

names = ["Alice", "Bob", "Charlie", "David"]

for index, name in enumerate(names):
    print(f"At position {index} is {name}")

Output:

At position 0 is Alice
At position 1 is Bob
At position 2 is Charlie
At position 3 is David

Learn more about enumerate() function in Python.

53. Flatten a Nested Python List

Given a list of lists, you can easily flatten the list to a 1D list with a for loop.

To do this:

  1. Loop through the list of lists.
  2. For each list, place each element in the list in a result list.
  3. Return the list.

Instead of using a nested for loop, you can use a one-liner list comprehension to make the code shorter. In case you find it hard to read, you can convert the comprehension back to a nested for loop.

Anyway, here is the implementation:

def flatten(nested_list):
    return [item for sublist in nested_list for item in sublist]

# Example run
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

numbers = flatten(matrix)

print(numbers)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

54. Convert String to Date in Python

Python has a built-in datetime module for dealing with date objects reliably.

The datetime module comes in with a datetime.strptime() function. You can use this to create a date object given a date as a string. To do this:

  1. Import the datetime from datetime.
  2. Create a date string in some format.
  3. Convert the string to a date object with the given format.

For example:

from datetime import datetime

date_time_str = '20/10/21 03:59:44'

date_time_obj = datetime.strptime(date_time_str, '%d/%m/%y %H:%M:%S')

print ("The date is", date_time_obj)

Output:

The date is 2021-10-20 03:59:44

55. Count the Frequency of Items in a List

To count the frequencies of list items in Python, you need to:

  1. Have a list full of elements.
  2. Create a frequency dictionary to map item -> item frequency.
  3. Loop through the list.
  4. On each element, increment its counter in the frequency dictionary.

Here is how it looks in code:

# A function that counts frequencies of the list items
def item_frequency(in_list):
    frequencies = {}
      
    for i in in_list:
        if i in frequencies:
            frequencies[i] += 1
        else:
            frequencies[i] = 1
    return frequencies

# Example run       
freqs = item_frequency(["Alice", "Bob", "Bob", "Charlie", "Bob"])

print(freqs)

Output:

{'Alice': 1, 'Bob': 3, 'Charlie': 1}

56. Add a Word to the End of an Existing File

To add a word to the end of an existing file:

  1. Open the file in write mode.
  2. Write a string to the file.
  3. Close the file.

You can use a context manager to open the file. This means you don’t have to worry about closing the file.

Given a list named example.txt with the following contents:

This is a test
The file contains a bunch of words
Bye!

You can write a new string to the end of it with a context manager like this:

with open("example.txt", "w") as file:
    file.write("A new string")

Output:

This is a test
The file contains a bunch of words
Bye!
A new string

57. Parse the File Extension from a File Name

To get the file extension from a path or file name, use the os.path.splitext function. This splits the file into two parts into a list:

  1. The path.
  2. The extension.

To get the extension, just access the second element of the list.

Here is how it looks in code:

import os.path

file = "example.py"
extension = os.path.splitext(file)[1]

print(f"The extension of file '{file}' is '{extension}'")

Output:

The extension of file 'example.py' is '.py'

58. Parse the File Name from the Path

To get the name of the file from a path, use os.path.basename() function.

For example:

import os

file_path = "Example/Directory/With/python_program.py"
file_name = os.path.basename(file_path)

print(file_name)

Output:

python_program

59. A Function That Takes a Default Argument

In Python, you can give function default arguments. This means you can call the function with or without an argument.

As this task does not state what kind of function to create, you can use your imagination.

For instance, let’s create a function greet() that says “Hello, there” by default. But once a name is given, the function greets the name.

Here is how:

def greet(name="there"):
    print(f"Hello, {name}!")
    
greet()
greet("Alice")

Output:

Hello, there!
Hello, Alice!

Learn more about default arguments in Python.

60. Count the Number of Files in the Present Directory

To count how many files are in the present directory, use os module.

  1. Use os.listdir(".") to list everything in the present directory.
  2. Call os.path.isfile() function for each item to verify it is a file.
  3. Return/print the result.
import os

print(len([file for file in os.listdir('.') if os.path.isfile(file)]))

Output:

9

61. Check the File Size in Python

To check the file size of a specific file, use the os.path.getsize() function.

For example:

import os

size = os.path.getsize("example.txt") 
print(f"The size of file is {size} bytes")

Output:

The size of file is 74 bytes

62. Calculate the Power of a Number

In Python, you can compute the power with the double-asterisk operator.

For example, 10^3 can be calculated with:

num = 10

power = num ** 3

print(power)

Output:

1000

63. Snake-Casify Strings in Python

Snake case means a writing style where each blank space is replaced by an underscore _.

To create a Python program that converts a string into a snake case, replace each space with a “_”.

This is possible using the built-in replace() method of a string.

string = "This is a test"

snake = string.replace(" ", "_")

print(snake)

Output:

This_is_a_test

64. Camel-Casify Strings in Python

Camel case means writing style where there are no spaces between words. Instead, each word begins with a capital first letter and is connected to the next word.

To write a Python program that camel casifies a string:

  1. Split the words into a list by blank space.
  2. Convert each string into a title case (first letter capital).
  3. Join the parts without spaces.

Here is how it looks:

# A program that converts a string to camel-case
def camel(string):
    words = string.split(" ")
    parts_upper = [word.title() for word in words]
    return "".join(parts_upper)

# Example run
string = "this is a test"
camel = camel(string)

print(camel)

Output:

ThisIsATest

65. Get All Combinations of a List

To get combinations of length r in a list, use itertools.combinations() function.

To get all the combinations of any length:

  1. Loop through numbers from 1 to the length of the list.
  2. Create a combination of the given length and add it to the results list.

Here is a script that computes all combinations of the list [1, 2, 3]:

import itertools
numbers = [1, 2, 3]

combinations = []
for r in range(len(numbers)+1):
    for combination in itertools.combinations(numbers, r):
        combinations.append(combination)

print(combinations)

Output:

[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]

Learn more about combinations and powersets in Python.

66. Remove Duplicates from a List

To remove duplicates from a Python list:

  1. Have a list of items.
  2. Create an empty result list.
  3. Loop through the list of items.
  4. Add each item to the result list if it is not already there.
  5. Return the result.

Here is how it looks in code:

# A function that removes duplicates from a list
def de_dupe(items):
    result = []
    for item in items:
        if item not in result:
            result.append(item)
    return result


# Example run
numbers = [1, 2, 2, 2, 3, 1, 2, 5, 5]

de_duped_nums = de_dupe(numbers)

print(de_duped_nums)

Output:

[1, 2, 3, 5]

67. Python Program to Replace Characters of a String

Python string has a built-in method called replace().

This function takes two parameters:

  1. A character to be replaced.
  2. A character to be inserted as the replacement.

You can use this method to replace the characters of that string.

For example, let’s replace all “s” characters with “z”:

sentence = "This is a test"

new_sentence = sentence.replace("s", "z")

print(new_sentence)

Output:

Thiz iz a tezt

68. Round Floats to Two Decimals

Python comes in with a built-in function round().

This function takes two arguments:

  1. A number to round.
  2. The number of desired decimal places.

The function rounds the number to the given decimal places.

For example, let’s round pi to 2 decimals:

from math import pi

print(f"Pi is {round(pi, 2)} when rounded to 2 decimals.")

Output:

Pi is 3.14 when rounded to 2 decimals.

69. Accept Any Number of Keyword Arguments

A keyword argument in Python is a function argument that has a name label attached to it.

An example call to a function with a keyword argument can look like this:

my_func(name="Jack")

Let’s for example implement a function that takes student info as its argument. You can give it as many keyword arguments as you wish. As a result, it prints the student’s data in a nicely formatted fashion.

Here is the example code:

# An example function that takes any number of keyword arguments
def info(**students):
    print("This year students info:")
    for name, major in students.items():
        print(f"- {name}: {major}")
    print("n")

# Example run
info(Alice="Physics", Bob="Maths")

info(Alice="Applied Physics", Bob="Maths",
     Charlie="Pharmaseutics", David="Fluid Mechanics")

Output:

This year students info:
- Alice: Applied Physics
- Bob: Maths
- Charlie: Pharmaseutics
- David: Fluid Mechanics

Learn more about keyword arguments in Python.

70. Sum a List

To sum a list of numbers in Python:

  1. Initialize the result at 0.
  2. Loop through the list of numbers.
  3. Add each number to the result.
  4. Return the result.

Here is the code:

# A function that calculates the sum of numbers
def total(numbers):
    result = 0
    for number in numbers:
        result += number
    return result


# Example run
numbers = [1, 2, 3, 4, 5]

sum = total(numbers)

print(sum)

Output:

15

71. Split a String

Python string has a built-in method called split(). This function takes one argument which is the delimiter according to which you want to split the string.

Here are some examples:

sentence = "This is a test. It demonstrates splitting strings."

split_by_spaces = sentence.split()
split_by_dot = sentence.split(".")
split_by_letter_s = sentence.split("s")

print(f"Split by spaces: {split_by_spaces}")
print(f"Split by dots: {split_by_dot}")
print(f"Split by letter 's': {split_by_letter_s}")

Output:

Split by spaces: ['This', 'is', 'a', 'test.', 'It', 'demonstrates', 'splitting', 'strings.']
Split by dots: ['This is a test', ' It demonstrates splitting strings', '']
Split by letter 's': ['Thi', ' i', ' a te', 't. It demon', 'trate', ' ', 'plitting ', 'tring', '.']

72. Get Current Time in Python

You can use Python’s built-in datetime module to obtain the current time.

To do this:

  1. Import the datetime from datetime module.
  2. Get the current date object.
  3. Grab the time from the current date in a specific format.

Here is how it looks in code:

from datetime import datetime

today_date = datetime.now()

time_now = today_date.strftime("%H:%M:%S")
print(f"The current time is {time_now}")

Output:

The current time is 09:35:26

73. Add Quotes in a String

To add quotation marks inside a string in Python, you have two options:

  1. Use double quotation marks as the string markers and single quotation marks as the quotes.
  2. Use single quotes as the string marker and double quotation marks as the quotes.

Here are both ways in code:

quote1 = "Then he said 'I will miss you'."
quote2 = 'Then he said "I will miss you".'

print(quote1)
print(quote2)

Output:

Then he said 'I will miss you'.
Then he said "I will miss you".

Learn more about quotes and strings in Python.

74. Document a Function Using a Docstring

In Python, you have a special syntax for documenting your code. This is called a docstring.

A docstring is a triple-quote string that can be spread across multiple lines.

The purpose of the docstring is to provide useful information about a function, class, or module. In Python, it is possible to call help() on any function, class, or module. When you do this, the docstring description is printed into the console.

Here is an example:

# Document a function with a docstring """ """
def add(a, b):
    """
    This function adds two numbers and returns the result.
        - a is an integer
        - b is an integer

        - res is the result
    """
    res = a + b
    return res


# Example use:
help(add)

Output:

Help on function add in module __main__:

add(a, b)
    This function adds two numbers and returns the result.
        - a is an integer
        - b is an integer
    
        - res is the result

Learn more about Python docstrings.

75. Python Program to Parse a JSON String

To convert a JSON object into a Python dictionary, use json.loads() function. Remember to import the json module before doing this.

Here is an example:

import json

# JSON string:
data_JSON = '{ "name": "John", "age": 23, "major": "Physics" }'

# JSON to Python Object (it becomes a dictionary)
data = json.loads(data_JSON)

# Use the data dict like any other dict in Python:
print(data["major"])

Output:

Physics

76. Generate a Textual Representation of an Object

When you print an object in Python, you may get a verbose result like this:

<__main__.Student object at 0x105a264c0>

But this is not readable and you can make no sense of it.

To fix this, implement a special method called __str__ in your class.

For example, let’s create a Student class. Furthermore, let’s make printing student objects produce a readable result by implementing the __str__ method.

class Student:
    def __init__(self, name, major):
        self.name = name
        self.major = major

    # String representation
    def __str__(self):
        return f"I am {self.name} and I study {self.major}"


# Example run
student = Student("Alice", "Chemistry")

print(student)

Output:

I am Alice and I study Chemistry

77. Read a File Into a List

To read a file into a list in Python:

  1. Open a file.
  2. Initialize an empty list to store the lines.
  3. Read the lines one by one and store each line on the list.
  4. Close the file.

A great way to deal with files is using context managers. A context manager auto-closes the file after being used. This saves you a little bit of overhead and lines of code. A context manager is used with the with statement.

Given a file called example.txt with the following contents:

This is a test
Let's read a file into Python
Let's see how it plays out...

You can read the lines in this file to a list with a context manager as follows:

with open("example.txt", "r") as file:
    lines = []
    for line in file.readlines():
        lines.append(line.strip("n"))
    print(lines)

Output:

['This is a test', "Let's read a file into Python", "Let's see how it plays out..."]

78. Check If a Number Is an Armstrong Number

An Armstrong number is a number whose digits to the power of the length of the number equals the number.

For instance, 1634 is an Armstrong number because: 1^4 + 6^4 + 3^4 + 4^4.

To create a Python program to check if a given number is an Armstrong number:

  1. Have a target number.
  2. Initialize an empty sum.
  3. Go through each digit, raise it to the length power, and add to the result.
  4. Check if the result equals the original number.

Here is how it looks in code:

# A function that checks if a given number is an armstrong number
def is_armstrong(number):
    order = len(str(number))
    sum = 0
    temp = number
    while temp > 0:
        digit = temp % 10
        sum += digit ** order
        temp //= 10
    if number == sum:
        print(f"{number} is an Armstrong number")
    else:
        print(f"{number} is not an Armstrong number")


# Example run
print(is_armstrong(1634))

Output:

1634 is an Armstrong number

79. Capitalize a String

Python string comes with a built-in upper() method. This method capitalizes the whole string.

For example:

name = "alice"

name_cap = name.upper()

print(name_cap)

Output:

ALICE

80. Break Out of a For Loop

Breaking a loop means jumping out of a loop before the loop is exhausted.

Here is an example of a function that checks if the number matches the target. When it does, the loop is escaped:

def find(target):
    for number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
        print(f"{number} in inspection...")
        if number == target:
            print("Target found!")
            break


find(3)

Output:

1 in inspection...
2 in inspection...
3 in inspection...
Target found!

Learn more about the break and other control flow statements here.

81. Check a Condition with One Line of Code

In Python, you can replace short if-else statements with one-liners. This is possible using a ternary conditional operator.

Here is an example of how:

age = 20

age_group = "adult" if age >= 18 else "minor"

print(age_group)

Output:

adult

Learn more about one-liner conditional operators in Python.

82. Calculate Remainder in Division

In Python, you can use the % operator to calculate the remainder in the division.

For example, dividing 11 slices of pizza with 3 guests means 2 leftover slices.

pizza_slices = 11
participants = 3

left_overs = pizza_slices % participants

print(f"{left_overs} slices are left over.")

Output:

2 slices are left over.

Learn more about remainders and modulo in Python.

83. Unpack a List to Separate Variables

In Python, it is possible to unpack iterables.

This means you can tear apart iterables to separate variables by comma separating the variables and using assignment operator on the iterable.

For example:

numbers = [1, 2, 3]

x, y, z = numbers

print(x)
print(y)
print(z)

Output:

1
2
3

84. Square a List of Numbers

To square a list of numbers in Python:

  1. Have a list of numbers.
  2. Initialize an empty result list.
  3. Loop through each number.
  4. Raise each number to the second power.
  5. Add the result to the result list.

Here is how it looks in code:

# A function that squares a list of numbers
def square(numbers):
    result = []
    for number in numbers:
        result.append(number ** 2)
    return result


# Example run
numbers = [1, 2, 3]
squared = square(numbers)
print(squared)

Output:

[1, 4, 9]

85. Filter Even Numbers

To filter even numbers in Python:

  1. Have a list of numbers.
  2. Initialize an empty result list.
  3. Loop through each number.
  4. Check if the number is even.
  5. Add the result to the result list.

Here is how it looks in code:

# A function that filters even numbers
def filter_even(numbers):
    result = []
    for number in numbers:
        if number % 2 == 0:
            result.append(number)
    return result


# Example run
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_nums = filter_even(numbers)

print(even_nums)

Output:

[2, 4, 6, 8, 10]

Learn more about list filtering in Python here.

86. Join Two or More Strings

Python string comes with a built-in join() method.

This function takes one argument, which is the separator character.

For example, to join strings with empty space as a separator:

s1 = "This"
s2 = "is"
s3 = "a test"

sentence = " ".join([s1, s2, s3])

print(sentence)

Output:

This is a test

Learn more about joining strings and other string methods from here.

87. Remove Specific Values from a List

You can use the filter() function to filter out values based on a criterion.

The filter() function takes two arguments:

  1. A filtering function. This is usually a lambda expression.
  2. An iterable, such as a list to be filtered.

The filter() function applies the filtering function on each element of the list to produce the result.

For example, let’s filter out integers from a list:

items = ["Alice", 2, 3, "Bob", "Charlie", 30]

# Let's remove numbers

names = filter(lambda x: not isinstance(x, int), items)

print(list(names))

Output:

['Alice', 'Bob', 'Charlie']

88. Add Values to the Beginning of a List

Python list has a built-in method insert(). It takes two arguments:

  1. A target index.
  2. A string to be placed into the target index.

You can use the insert() method to add an element to the beginning of a list.

For example:

names = ["Bob", "Charlie", "David"]

names.insert(0, "Alice")

print(names)

Output:

['Alice', 'Bob', 'Charlie', 'David']

Learn more about adding and removing values from Python lists here.

89. Calculate HCF in Python

The Highest Common Factor (HCF) of two numbers is the highest number that evenly divides both numbers.

For example, the HCF of 12 and 36 is 12.

To calculate the HCF in Python:

  1. Take two numbers.
  2. Determine the smallest number of the two.
  3. Loop through numbers from 1 to the smallest number.
  4. Check on each value if it factors the greatest number.
  5. Keep track of the highest such number.
  6. At the end of the loop, return the highest factor.

Here is a Python program to find the HCF between two numbers:

# A function that finds the HCF
def compute_hcf(x, y):
    if x > y:
        smaller = y
    else:
        smaller = x
    for i in range(1, smaller + 1):
        if x % i == 0 and y % i == 0:
            hcf = i
    return hcf


# Example run
n1 = 81
n2 = 36
print(f"The H.C.F. between {n1} and {n2} is {compute_hcf(81, 36)}")

Output:

The H.C.F. between 81 and 36 is 9

90. Show N Fibonacci Numbers

A Fibonacci sequence is a series of numbers where the next number is the sum of the previous two.

For example, 0,1,1,2,3,5,8,13,21,34.

To find a Fibonacci sequence of length n in Python:

# A function to print a fibonacci sequence
def show_fib(n_terms):
    n1, n2 = 0, 1
    count = 0
    if n_terms <= 0:
        print("Enter a positive integer")
    else:
        print("Fibonacci sequence:")
        while count < n_terms:
            print(n1)
            nth = n1 + n2
            n1 = n2
            n2 = nth
            count += 1


# Example run
show_fib(10)

Output:

0
1
1
2
3
5
8
13
21
34

91. Python Program to Calculate Age

To calculate the age given a date object in Python:

  1. Subtract the beginning year from the current year.
  2. Remove 0 if the month/day of the beginning date precedes the current month/day.

Here is how it looks in code:

from datetime import date


def age(birthdate):
    today = date.today()
    age = today.year - birthdate.year - 
        ((today.month, today.day) < (birthdate.month, birthdate.day))
    return age


birthdate = date(1996, 2, 27)

print(f"With birth date of {birthdate}, you are {age(birthdate)} years old")

Output:

With birth date of 1996-02-27, you are 25 years old

The above program knows how to handle leap years too. Check out this article to learn more.

92. Simulate Throwing a Dice in Python

When you throw a dice, you get 1, 2, 3, 4, 5, or 6.

To simulate dice toss in Python, randomize a number between 1 and 6. You can achieve this using the random module’s randint() function.

Here is how it looks in code:

from random import randint

def throw_dice():
    return randint(1, 6)

print(throw_dice())

Output example:

2

93. Find Out How Far Is the Horizon

This involves a bit of basic trigonometry.

To calculate the distance to the horizon, you need to realize the horizon distance is the “opposite” a side of a right triangle formed by:

  1. Earth’s radius + your height.
  2. Earth’s radius.
  3. The distance to the horizon.

How far is the horizon

Here is how you can implement the equation in your Python program:

from math import sqrt

# A function that calculates distance to horizon in meters given height in meters
def horizon_distance(h):
    R = 6_371_000
    return sqrt(2 * R * h + h ** 2)


airplane_height = 12_000
d_horizon = horizon_distance(airplane_height)
print(
    f"You can see ~{round(d_horizon / 1000)}km from a commercial flight.")

Output:

You can see ~391km from a commercial flight.

94. Calculate the Area of a Circle

The area of a circle is given by A = pi * r^2.

To write a Python program to calculate the area of a circle, import pi from math module and calculate the area with the above formula:

from math import pi

# A function to find the area of a circle
def circle_area(r):
    return pi * r ** 2

radius = 5

print(f"A circle of radius {radius} takes {circle_area(radius)} square meters of space.")

Output:

A circle of radius 5 takes 78.53981633974483 square meters of space.

95. Find the Volume of a Cube

Given a cube of side length a, the volume V = a^3.

Here is a Python code example on how to calculate the volume of a cube:

from math import pi

# A function to find the volume of a cube
def volume_cube(s):
    return s ** 3


side = 5

print(f"A cube of sides {side} takes {volume_cube(side)} cubic meters of room.")

Output:

A cube of sides 5 takes 125 cubic meters of room.

96. Measure Elapsed Time

To measure the runtime of a program, import the time module into your project and:

  1. Store the start time in memory.
  2. Run a piece of code.
  3. Store the end time into memory.
  4. Calculate the time difference between the start and end.

Here is how it looks in code:

import time

# Example function that takes some time
def sum_to_million():
    sum = 0
    for i in range(1_000_000):
        sum += i


# Let's see how long summing numbers up to one million takes in Python:
start = time.time()
sum_to_million()
end = time.time()

# Not too long...
print(f"The time to sum numbers up to million took {end - start} seconds")

Output:

The time to sum numbers up to million took 0.06786799430847168 seconds

97. Check If a Set Is a Subset of Another Set in Python

In set theory, set A is a subset of B if all the elements in set A are also in set B.

In Python, you can use the built-in issubset() method to check if a set A is a subset of set B.

For example:

A = {1, 2, 3}
B = {1, 2, 3, 4, 5, 6}

print(A.issubset(B))

Output:

True

Learn more about sets and the issubset() method here.

98. Find N Longest Strings in a Python List

To find n longest strings in a list:

  1. Sort the list of strings based on length.
  2. Pick the n last elements of the sorted list. These are the longest strings.

Here is how it looks in code:

# A function that finds n longest words in a list of strings
def find_longest(strings, n):
    l = len(strings)
    # If n is more or equal to the list length, return the whole list.
    if n >= l:
        return strings
    else:
        sorted_strings = sorted(strings, key=len)
        return sorted_strings[-n:]


# Example run
names = ["Alice", "Bob", "Charlie", "David", "Emmanuel", "Frank", "Gabriel"]

print(find_longest(names, 3))

Output:

['Charlie', 'Gabriel', 'Emmanuel']

99. Clone a Python List Independently

To take an independent copy of a list, use the deepcopy() method from the copy module.

For example:

import copy

names = ["Alice", "Bob", "Charlie"]

names_clone = names.deepcopy()

print(names_clone)

Output:

['Alice', 'Bob', 'Charlie']

Read more about copying lists in Python.

100. Break List Into N-Sized Chunks

If you want to break. alist into n-sized chunks:

  1. Create an empty result list.
  2. Loop through the original list by taking the chunk-sized steps.
  3. At each step, add the current element and the next i elements to the result list.
  4. When there are no values left, return the list.

Here is how it looks in code:

# A program that groups a list into chunks
def chunks(elements, chunk_size):
    result = []
    for i in range(0, len(elements), chunk_size):
        result.append(elements[i:i + chunk_size])
    return result


# Example run
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

parts = chunks(numbers, 4)

print(parts)

Output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10]]

Conclusion

That is a lot of Python examples. I hope you find it useful where ever you go.

Happy coding my friends!

Further Reading

Python Tricks

How to Write to a File in Python

The with Statement in Python

About the Author

I’m an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.

Recent Posts

Теги: python, пайтон, первая программа, написание программы

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

Итак, прежде чем мы приступим к написанию программы, давайте установим Python, если вы этого ещё не сделали. Для этого мы предварительно скачаем Python с официального сайта. Если у вас Windows, инсталлятор берём отсюда, выбирая нужную версию. В принципе, установка проблем не вызывает, поэтому мы не будем задерживаться на этом шаге. К тому же, в сети полно статей, где подробно и пошагово описывается инсталляция Python (кстати, его можно установить и на Unix-подобные системы: Linux, Ubuntu и прочие).

Пишем первую программу

Что нужно сделать в первую очередь? Во-первых, открыть IDLE — она представляет собой среду разработки на Python и поставляется вместе с дистрибутивом:

start_idle_1-20219-04fbfc.png

После запуска IDLE в интерактивном режиме мы можем переходить к созданию первой программы. Как уже стало доброй традицией, это будет классический «Hello world».
Чтобы написать такую простейшую программу мы используем всего одну строку кода:


После ввода этого кода в среду разработки и нажатия кнопки «Enter» мы получим соответствующий вывод:

1-20219-e3cc84.png

Элементарно, Ватсон! Теперь вы написали первую программу на Python! Впрочем, это не сделает вас программистом, ведь всё гораздо сложнее… С другой стороны, надо же с чего-то начинать.

Для закрепления можете написать другие простые программы. Например, нижеследующий код выведет в консоли 8:


Впрочем, при разработке программ на Python интерактивный режим не является основным. Чаще всего мы сохраняем код программы в файл, а потом запускаем файл. Давайте создадим в IDLE новое окно, выбрав File → New File (также можно нажать Ctrl + N):

2-20219-37c5df.png

У нас появится окно, где вводим следующий код:

name = input("Как твоё имя? ")
print("Здравствуй,", name)

Что тут происходит:
1) первая строка программы выводит в консоль вопрос, спрашивает ваше имя и ждёт ответа;
2) после того, как вы напишете имя и нажмёте «ввод», Python-программа сохранит полученное значение в переменной name;
3) вторая строка выведет на экран написанное вами имя после слова «Здравствуй». Например, «Здравствуй, Петя!».

Для запуска нашей новой программы на Python достаточно нажать F5 либо выбрать в меню IDLE Run → Run Module. Кстати, перед запуском среда разработки предложит сохранить файл (папку можете выбрать сами).

Что ж, на этом всё. Поздравляем вас с написанием первой, второй и даже третьей программы на Python. Впереди ещё много интересного, главное — не бросать начатое. Помните старую истину: «Дорогу осилит идущий».

Содержание

  1. Введение
  2. Примеры простых программ
  3. Замена значений переменных местами
  4. Написание числа в обратном порядке
  5. Преобразование разделённого запятыми списка в строку
  6. Найти среднее значение элементов массива
  7. Проверить, является ли слово палиндромом
  8. Есть ли число в списке
  9. Вывод всех чисел, кратных определенному числу, в заданном диапазоне
  10. Количества цифр в числе
  11. Суммы всех цифр данного числа
  12. Сумма цифр от 1 до n
  13. Играемся со звёздочками
  14. Получаем гласные
  15. Чуть сложнее
  16. Все перестановки трех чисел
  17. Декартово произведение
  18. Генератор чисел Фибоначчи
  19. Объединяем два словаря
  20. Проверка дубликатов
  21. Вычисляем время выполнения
  22. Разбиение на фрагменты

Введение

В данном уроке мы приведём несколько примеров небольших программ на Python. Общая рекомендация к изучению любого языка: практикуйтесь как можно больше. Чтобы достичь хоть какого-то уровня профессионализма в программировании, не достаточно только изучать теорию. Пишите код. Желательно, каждый день, хотя бы по чуть-чуть. Это важно. Ваши руки должны привыкнуть к синтаксису, а мозги – к решению стандартных задач программирования.

Примеры простых программ

Замена значений переменных местами

На большинстве других языков эта задача была бы решена следующим образом:


var_1 = 15
var_2 = 67
print('var_1:', var_1, 'var_2:', var_2)
var_temp = var_1
var_1 = var_2
var_2 = var_temp
print('var_1:', var_1, 'var_2:', var_2)
# Вывод:
var_1: 15 var_2: 67
var_1: 67 var_2: 15

Но Пайтон творит магию:


var_1, var_2 = 15, 67
print('var_1:', var_1, 'var_2:', var_2)
var_1, var_2 = var_2, var_1
print('var_1:', var_1, 'var_2:', var_2)
# Вывод:
var_1: 15 var_2: 67
var_1: 67 var_2: 15

Написание числа в обратном порядке


var_1 = 1567
reverse = 0
while var_1 > 0:
    rest = var_1 % 10
    reverse = reverse * 10 + rest
    var_1 = var_1 // 10
print("Число в обратном порядке:", reverse)
# Вывод:
Число в обратном порядке: 7651

В Питоне, несмотря на одну из его заповедей: «должно быть только одно решение», решений, как правило много. Всегда стоит задуматься о том, какой алгоритм оптимальнее. Пример, приведённый выше, работает, но его можно оптимизировать (сократить объём кода).


var_1 = 1567
var_1 = str(var_1)[::-1]
print("Число в обратном порядке:", var_1)
# Вывод:
Число в обратном порядке: 7651

Преобразование разделённого запятыми списка в строку


favorites = ["Python", "SQL", "GO"]
print("Мои любимые языки программирования:", ", ".join(favorites))
# Вывод:
Мои любимые языки программирования: Python, SQL, GO

Найти среднее значение элементов массива


var_1 = [1, 5, 6, 7]
sum = 0
for i in var_1:
    sum += i
print(sum/len(var_1))
# Вывод:
4.75

Оптимизируем код:


var_1 = [1, 5, 6, 7]
print(eval(str(var_1).replace(', ', '+'))[0]/len(var_1))
# Вывод:
4.75

Тут следует заметить, что сокращение кода, почти всегда, ведёт к ухудшению читаемости и это следует делать с большой осторожностью. К примеру, в приведённом выше варианте, читаемость «убита» полностью, хоть код сократился всего на три строки.

Проверить, является ли слово палиндромом

Палиндром – это слово, которое читается одинаково в обоих направлениях. Для разнообразия покажем, как сокращение кода из-за выбора альтернативного алгоритма повышает читаемость кода и производительность. Вот одна из худших реализаций:


var_1 = 'level'
var_2 = list(var_1)
var_2.reverse()
var_2 = str(var_2).replace('', '', '').replace('['', '').replace('']', '')
print(var_2)
if var_1 == var_2:
    print('Palindrom')
else:
    print('Simple word')
# Вывод:
Palindrome

Вариант получше:


var_1 = 'level'
ispalindrome = var_1 == var_1[::-1]
if ispalindrome:
    print('Palindrome')
else:
    print('Simple word')
# Вывод:
Palindrome

Вишенка на торте. Тоже самое в одну строку:


var_1 = 'level'
print('Palindrome') if var_1 == var_1[::-1] else print('Simple word')
# Вывод:
Palindrome

Есть ли число в списке


var_1 = 11
print(var_1 in [5, 6, 40, 126])
# Вывод:
False

Вывод всех чисел, кратных определенному числу, в заданном диапазоне


lower = int(input("Введите нижнюю границу диапазона: "))
upper = int(input("Введите верхнюю границу диапазона: "))
n = int(input("Введите делитель: "))
for i in range(lower, upper + 1):
    if(i % n == 0):
        print(i)
# Вывод:
Введите нижнюю границу диапазона: 5
Введите верхнюю границу диапазона: 30
Введите делитель: 5
5
10
15
20
25
30

Количества цифр в числе


var_1 = int(input("Введите число: "))
count = 0
while var_1 > 0:
    count = count + 1
    var_1 = var_1 // 10
print("Количество цифр равно:", count)
# Вывод:
Введите число: 123456789
Количество цифр равно: 9

Суммы всех цифр данного числа


var_1 = int(input("Введите число: "))
total = 0
while var_1 > 0:
    rest = var_1 % 10
    total = total + rest
    var_1 = var_1//10
print("Сумма цифр равна:", total)
# Вывод:
Введите число: 123456789
Сумма цифр равна: 45

Сумма цифр от 1 до n


var_1 = int(input("Введите число: "))
agregator = []
for i in range(1, var_1+1):
    print(i, sep=" ", end=" ")
    if i < var_1:
        print("+", sep=" ", end=" ")
    agregator.append(i)
print("=", sum(agregator))
# Вывод:
Введите число: 18
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18 = 171

Играемся со звёздочками

Вывести n рядов, заполненных знаком ‘*’


var_1 = int(input("Введите количество рядов: "))
for i in range(var_1, 0, -1):
    print((var_1-i) * ' ' + i * '*')
# Вывод:
Введите количество рядов: 5
*****
 ****
  ***
   **
    *

Получаем гласные


def get_vowels(word):
    return [each for each in word if each in "aeiouy"]
print(get_vowels("animal"))
print(get_vowels("sky"))
print(get_vowels("football"))
# Вывод:
['a', 'i', 'a']
['y']
['o', 'o', 'a']

Чуть сложнее

Все перестановки трех чисел

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


var_1 = int(input("Введите первое число: "))
var_2 = int(input("Введите второе число: "))
var_3 = int(input("Введите третье число: "))
agregator = []
agregator.append(var_1)
agregator.append(var_2)
agregator.append(var_3)
for i in range(0, 3):
    for j in range(0, 3):
        for k in range(0, 3):
            if(i != j & j != k & k != i):
                print(agregator[i], agregator[j], agregator[k])
# Вывод:
Введите первое число: 10
Введите второе число: 20
Введите третье число: 30
10 20 30
10 30 20
20 10 30
20 30 10
30 10 20
30 20 10

Декартово произведение

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


print([(var_1, var_2) for var_1 in ['dfa', 'eb'] for var_2 in [154, 248, 873]])
# Вывод:
[('dfa', 154), ('dfa', 248), ('dfa', 873), ('\eb', 154), ('\eb', 248), ('\eb', 873)]

Генератор чисел Фибоначчи


def fibonacci(limit):        # генератор (а не функция, т.к. оператор return заменён на yield)
    var_1, var_2 = 0, 1
    while var_1 < limit:
        yield var_1            # return a, + запоминаем место рестарта для следующего вызова
        var_1, var_2 = var_2, var_1 + var_2    # параллельное присваивание, которое выполняется одновременно и параллельно

for n in fibonacci(1000):   # используем генератор fibonacci() как итератор
    print(n, end=' ')               # печатаем все числа Фибоначчи меньшие 1000 через пробел
# Вывод:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

Объединяем два словаря


def merge(dic_1, dic_2):
    dic_3 = dic1.copy()
    dic_3.update(dic_2)
    return dic_3


dic1 = {1: "Hello", 2: "pythoninfo,"}
dic2 = {3: "Python", 4: "is awesome",}
print(merge(dic1, dic2))
# Вывод:
{1: 'Hello', 2: 'pythoninfo,', 3: 'Python', 4: 'is awesome'}

Проверка дубликатов


def check_duplicate(lst):
    return len(lst) != len(set(lst))


print(check_duplicate([51, 37, 3, 45, 5, 49, 77]))
print(check_duplicate([1, 3, 3]))
print(check_duplicate([11, 2, 88, 4, 16]))
# Вывод:
False
True
False

Вычисляем время выполнения

Очень полезный пример. Приведённый код – самый простой способ проводить профилирование Вашего кода. Позволяет понять какой блок тормозит работу программы. Здесь мы записываем текущее время перед запуском функции и после запуска. Затем сравниваем их и выводим, сколько времени заняло выполнение функции.


import time


def fun(i):
    res = lambda i: i ** i
    return res(i)


start_time = time.time()
fun(fun(5))
end_time = time.time()
timetaken = end_time - start_time
print("Время выполнения: ", timetaken)
# Вывод:
Время выполнения:  0.0009870529174804688

Разбиение на фрагменты


def chunk(ishod_list, size):
    return [ishod_list[i:i + size] for i in range(0, len(ishod_list), size)]

ishod_list = ['q', 'w', 'e', 'r', 't', 'y']
print(chunk(ishod_list, 2))
# Вывод:
[['q', 'w'], ['e', 'r'], ['t', 'y']]

Добавлено 2 апреля 2020 в 21:12

Не убегайте от проблем, не осуждайте себя и не несите своё бремя в праведном безмолвии. У вас есть проблема? Прекрасно! Это пойдёт на пользу! Радуйтесь: погрузитесь в неё и исследуйте!

Содержание главы

Погружение

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

SUFFIXES = {1000: ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
            1024: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']}

def approximate_size(size, a_kilobyte_is_1024_bytes=True):
    '''Преобразует размер файла в удобочитаемую для человека форму.

    Ключевые аргументы:
    size -- размер файла в байтах
    a_kilobyte_is_1024_bytes -- если True (по умолчанию), используются степени 1024
                                если False, используются степени 1000

    Возвращает: текстовую строку (string)

    '''
    if size < 0:
        raise ValueError('число должно быть неотрицательным')

    multiple = 1024 if a_kilobyte_is_1024_bytes else 1000
    for suffix in SUFFIXES[multiple]:
        size /= multiple
        if size < multiple:
            return '{0:.1f} {1}'.format(size, suffix)

    raise ValueError('число слишком большое')

if __name__ == '__main__':
    print(approximate_size(1000000000000, False))
    print(approximate_size(1000000000000))

Теперь давайте запустим эту программу из командной строки. В Windows это будет выглядеть примерно так:

c:homediveintopython3examples> c:python31python.exe humansize.py
1.0 TB
931.3 GiB

В Mac OS X и Linux, будет почти то же самое:

you@localhost:~/diveintopython3/examples$ python3 humansize.py
1.0 TB
931.3 GiB

Что сейчас произошло? Вы выполнили свою первую программу на Python. Вы вызвали интерпретатор Python в командной строке и передали ему имя скрипта, который хотели выполнить. В скрипте определена функция approximate_size(), которая принимает точный размер файла в байтах и вычисляет «красивый» (но приблизительный) размер. (Возможно, вы видели его в Проводнике Windows, в Mac OS X Finder, в Nautilus, Dolphin или Thunar в Linux. Если отобразить папку с документами в виде таблицы, файловый менеджер в каждой её строке покажет иконку, название документа, размер, тип, дату последнего изменения и т. д. Если в папке есть 1093-байтовый файл с названием «TODO», файловый менеджер не покажет «TODO 1093 байта»; вместо этого он скажет что-то типа «TODO 1 КБ». Именно это и делает функция approximate_size().)

Посмотрите на последние строки скрипта, вы увидите два вызова print(approximate_size(аргументы)). Это вызовы функций. Сначала вызывается approximate_size(), которой передаётся несколько аргументов, а затем возвращённое ею значение берётся и передаётся прямо в функцию print(). Функция print() встроенная, вы нигде не найдёте её явного объявления. Её можно только использовать, где угодно и когда угодно. (Есть множество встроенных функций, и ещё больше функций, которые выделены в отдельные модули. Только терпение, непоседа.)

Итак, почему при выполнении скрипта в командной строке, всегда получается один и тот же результат? Мы ещё дойдём до этого. Но сначала давайте посмотрим на функцию approximate_size().

1.2 Объявление функций

Когда вам нужна функция, просто объявите её.

В Python есть функции, как и в большинстве других языков, но нет ни отдельных заголовочных файлов, как в C++, ни конструкций interface/implementation, как в Паскале. Когда вам нужна функция, просто объявите её, например, так:

def approximate_size(size, a_kilobyte_is_1024_bytes=True):

Объявление начинается с ключевого слова def, затем следует имя функции, а за ним аргументы в скобках. Если аргументов несколько, они разделяются запятыми.

К тому же, стоит заметить, что в объявлении функции не задаётся тип возвращаемых данных. Функции в Python не определяют тип возвращаемых ими значений; они даже не указывают, существует ли возвращаемое значение вообще. (На самом деле, любая функция в Python возвращает значение; если в функции выполняется инструкция return, она возвращает указанное в этой инструкции значение, если нет – возвращает None – специальное нулевое значение.)

В некоторых языках программирования функции (возвращающие значение) объявляются ключевым словом function, а подпрограммы (не возвращающие значений) – ключевым словом sub. В Python же подпрограмм нет. Все функции возвращают значение (даже если оно None), и всегда объявляются ключевым словом def.

Функция approximate_size() принимает два аргумента: size и a_kilobyte_is_1024_bytes, но ни один из них не имеет типа. В Python тип переменных никогда не задаётся явно. Python вычисляет тип переменной и следит за ним самостоятельно.

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

1.2.1 Необязательные и именнованные аргументы

В Python аргументы функций могут иметь значения по умолчанию; если функция вызывается без аргумента, то он принимает своё значение по умолчанию. К тому же, аргументы можно указывать в любом порядке, задавая их имена.

Давайте ещё раз посмотрим на объявление функции approximate_size():

def approximate_size(size, a_kilobyte_is_1024_bytes=True):

Второй аргумент – a_kilobyte_is_1024_bytes – записывается со значением по умолчанию True. Это означает, что этот аргумент необязательный; можно вызвать функцию без него, а Python будет действовать так, как будто она вызвана с True в качестве второго параметра.

Теперь взглянем на последние строки скрипта:

if __name__ == '__main__':
    print(approximate_size(1000000000000, False))  ①
    print(approximate_size(1000000000000))         ②
  1. Строка 27. Функция approximate_size() вызывается с двумя аргументами. Внутри функции approximate_size() переменная a_kilobyte_is_1024_bytes будет False, поскольку False передаётся явно во втором аргументе.
  2. Строка 28. Функция approximate_size() вызывается только с одним аргументом. Но всё в порядке, потому что второй аргумент необязателен! Поскольку второй аргумент не указан, он принимает значение по умолчанию True, как определено в объявлении функции.

А ещё можно передавать значения в функцию по имени.

>>> from humansize import approximate_size
>>> approximate_size(4000, a_kilobyte_is_1024_bytes=False)       ①
'4.0 KB'
>>> approximate_size(size=4000, a_kilobyte_is_1024_bytes=False)  ②
'4.0 KB'
>>> approximate_size(a_kilobyte_is_1024_bytes=False, size=4000)  ③
'4.0 KB'
>>> approximate_size(a_kilobyte_is_1024_bytes=False, 4000)       ④
  File "<stdin>", line 1
SyntaxError: non-keyword arg after keyword arg
>>> approximate_size(size=4000, False)                           ⑤
  File "<stdin>", line 1
SyntaxError: non-keyword arg after keyword arg

Перевод сообщений оболочки

  File "<stdin>", line 1
SyntaxError: non-keyword arg after keyword arg

Файл «<stdin>», строка 1
SyntaxError: неименованный аргумент после именованного

  1. Строка 2. Функция approximate_size() вызывается со значением 4000 в первом аргументе и False в аргументе по имени a_kilobyte_is_1024_bytes. (Он стоит на втором месте, но это не важно, как вы скоро увидите.)
  2. Строка 4. Функция approximate_size() вызывается со значением 4000 в аргументе по имени size и False в аргументе по имени a_kilobyte_is_1024_bytes. (Эти именованные аргументы стоят в том же порядке, в каком они перечислены в объявлении функции, но это тоже не важно.)
  3. Строка 6. Функция approximate_size() вызывается с False в аргументе по имени a_kilobyte_is_1024_bytes и 4000 в аргументе по имени size. (Видите? Я же говорил, что порядок не важен.)
  4. Строка 8. Этот вызов не работает, потому что за именованным аргументом следует неименованный (позиционный). Если читать список аргументов слева направо, то как только встречается именованный аргумент, все следующие за ним аргументы тоже должны быть именованными.
  5. Строка 11. Этот вызов тоже не работает, по той же причине, что и предыдущий. Удивительно? Ведь сначала передаётся 4000 в аргументе по имени size, затем, «очевидно», можно ожидать, что False станет аргументом по имени a_kilobyte_is_1024_bytes. Но в Python это не работает. Раз есть именованный аргумент, все аргументы справа от него тоже должны быть именованными.

1.3 Написание читаемого кода

Не буду растопыривать перед вами пальцы и мучить длинной лекцией о важности документирования кода. Просто знайте, что код пишется один раз, а читается многократно, и самый важный читатель вашего кода – это вы сами через полгода после написания (т. е. всё уже забыто, и вдруг понадобилось что-то починить). В Python писать читаемый код просто. Используйте это его преимущество и через полгода вы скажете мне «спасибо».

1.3.1 Строки документации

Каждая функция заслуживает хорошую документацию.

Функции в Python можно документировать, снабжая их строками документации (англ. documentation string, сокращённо docstring). В нашей программе у функции approximate_size() есть строка документации:

def approximate_size(size, a_kilobyte_is_1024_bytes=True):
    '''Преобразует размер файла в удобочитаемую для человека форму.

    Ключевые аргументы:
    size -- размер файла в байтах
    a_kilobyte_is_1024_bytes -- если True (по умолчанию), используются степени 1024
                                если False, используются степени 1000

    Возвращает: текстовую строку (string)

    '''

Тройные кавычки (три апострофа) используются для задания строк (имеется ввиду тип данных string) содержащих многострочный текст. Всё, что находится между начальными и конечными кавычками, является частью одной строки данных, включая переводы строк, пробелы в начале каждой строки текста, и другие кавычки. Вы можете использовать их где угодно, но чаще всего будете встречать их в определениях строк документации.

Тройные кавычки – это ещё и простой способ определить строку, содержащую одинарные (апострофы) и двойные кавычки, подобно qq/.../ в Perl 5.

Всё, что находится в тройных кавычках, – это строка документации функции, описывающая, что делает эта функция. Строка документации, если она есть, должна начинать тело функции, т. е. находится на следующей строчке сразу под объявлением функции. Строго говоря, вы не обязаны писать документацию к каждой своей функции, но всегда желательно это делать. Я знаю, что вам уже все уши прожужжали про документирование кода, но Python даёт вам дополнительный стимул – строки документации доступны во время выполнения как атрибут функции.

Многие IDE для Python используют строки документации для отображения контекстной справки, и когда вы набираете название функции, её документация появляется во всплывающей подсказке. Это может быть невероятно полезно, но это всего лишь строки документации, которые вы сами пишете.

1.4 Путь поиска оператора import

Перед тем, как идти дальше, я хочу вкратце рассказать о путях поиска библиотек. Когда вы пытаетесь импортировать модуль (с помощью оператора import), Python ищет его в нескольких местах. В частности, он ищет во всех директориях, перечисленных в sys.path. Это просто список, который можно легко просматривать и изменять при помощи стандартных списочных методов. (Вы узнаете больше о списках в главе «Встроенные типы данных».)

>>> import sys                                                 ①
>>> sys.path                                                   ②
['', 
 '/usr/lib/python31.zip', 
 '/usr/lib/python3.1',
 '/usr/lib/python3.1/plat-linux2@EXTRAMACHDEPPATH@', 
 '/usr/lib/python3.1/lib-dynload', 
 '/usr/lib/python3.1/dist-packages', 
 '/usr/local/lib/python3.1/dist-packages']
>>> sys                                                        ③
<module 'sys' (built-in)>
>>> sys.path.insert(0, '/home/mark/diveintopython3/examples')  ④
>>> sys.path                                                   ⑤
['/home/mark/diveintopython3/examples', 
 '', 
 '/usr/lib/python31.zip', 
 '/usr/lib/python3.1', 
 '/usr/lib/python3.1/plat-linux2@EXTRAMACHDEPPATH@', 
 '/usr/lib/python3.1/lib-dynload', 
 '/usr/lib/python3.1/dist-packages', 
 '/usr/local/lib/python3.1/dist-packages']
  1. Строка 1. Импортирование модуля sys делает доступными все его функции и атрибуты.
  2. Строка 2.sys.path – список имён директорий, определяющий текущий путь поиска. (Ваш будет выглядеть иначе, в зависимости от вашей операционной системы, от используемой версии Python и от того, куда он был установлен.) Python будет искать в этих директориях (в заданном порядке) файл с расширением «.py», имя которого совпадает с тем, что вы пытаетесь импортировать.
  3. Строка 10. Вообще-то я вас обманул; истинное положение дел немного сложнее, потому что не все модули лежат в файлах с расширением «.py». Некоторые из них, как, например, модуль sys, являются встроенными; они впаяны в сам Python. Встроенные модули ведут себя точно так же, как обычные, но их исходный код недоступен, потому что они не были написаны на Python! (Модуль sys написан на Си.)
  4. Строка 12. Можно добавить новую директорию в путь поиска, добавив имя директории в список sys.path, во время выполнения Python, и тогда Python будет просматривать её наравне с остальными, как только вы попытаетесь импортировать модуль. Новый путь поиска будет действителен в течение всего сеанса работы Python.
  5. Строка 13. Выполнив команду sys.path.insert(0, новый_путь), вы вставили новую директорию на первое место в список sys.path, и, следовательно, в начало пути поиска модулей. Почти всегда, именно это вам и нужно. В случае конфликта имён (например, если Python поставляется со 2-й версией некоторой библиотеки, а вы хотите использовать версию 3) этот приём гарантирует, что будут найдены и использованы ваши модули, а не те, которые идут в комплекте с Python.

1.5 Всё является объектом

Если вы вдруг пропустили, я только что сказал, что функции в Python имеют атрибуты, и эти атрибуты доступны во время выполнения. Функция, как и всё остальное в Python, является объектом.

Запустите интерактивную оболочку Python и повторите за мной:

>>> import humansize                               ①
>>> print(humansize.approximate_size(4096, True))  ②
4.0 KiB
>>> print(humansize.approximate_size.__doc__)      ③
Преобразует размер файла в удобочитаемую для человека форму.

    Ключевые аргументы:
    size -- размер файла в байтах
    a_kilobyte_is_1024_bytes -- если True (по умолчанию), используются степени 1024
                                если False, используются степени 1000

    Возвращает: текстовую строку (string)
  1. Строка 1. Первая строка импортирует программу humansize в качестве модуля – фрагмента кода, который можно использовать интерактивно или из другой Python-программы. После того, как модуль был импортирован, можно обращаться ко всем его публичным функциям, классам и атрибутам. Импорт применяется как в модулях, для доступа к функциональности других модулей, так и в интерактивной оболочке Python. Это очень важная идея, и вы ещё не раз встретите её на страницах этой книги.
  2. Строка 2. Когда вы хотите использовать функцию, определённую в импортированном модуле, нужно дописать к её имени название модуля. То есть вы не можете использовать просто approximate_size, обязательно humansize.approximate_size. Если вы использовали классы в Java, то для вас это должно быть знакомо.
  3. Строка 4. Вместо того, чтобы вызвать функцию (как вы, возможно, ожидали), вы запросили один из её атрибутов – __doc__.

Оператор import в Python похож на require из Perl. После import в Python, вы обращаетесь к функциям модуля как модуль.функция; после require в Perl, для обращения к функциям модуля используется имя модуль::функция.

1.5.1 Что такое объект?

В языке Python всё является объектом, и у любого объекта могут быть атрибуты и методы. Все функции имеют стандартный атрибут __doc__, содержащий строку документации, определённую в исходном коде функции. Модуль sys – тоже объект, имеющий (кроме прочего) атрибут под названием path. И так далее.

Но мы так и не получили ответ на главный вопрос: что такое объект? Разные языки программирования определяют «объект» по-разному. В одних считается, что все объекты должны иметь атрибуты и методы. В других, что объекты могут порождать подклассы. В Python определение ещё менее чёткое. Некоторые объекты не имеют ни атрибутов, ни методов, хотя и могли бы их иметь. Не все объекты порождают подклассы. Но всё является объектом в том смысле, что может быть присвоено переменной или передано функции в качестве аргумента.

Возможно, вы встречали термин «объект первого класса» в других книгах о программировании. В Python функции – объекты первого класса. Функцию можно передать в качестве аргумента другой функции. Модули – объекты первого класса. Весь модуль целиком можно передать в качестве аргумента функции. Классы – объекты первого класса, и отдельные их экземпляры – тоже объекты первого класса.

Это очень важно, поэтому я повторю это, на случай если вы пропустили первые несколько раз: всё в Python является объектом. Строки – это объекты. Списки – объекты. Функции – объекты. Классы – объекты. Экземпляры классов – объекты. И даже модули являются объектами.

1.6 Отступы

Функции в Python не имеют ни явных указаний begin и end, ни фигурных скобок, которые бы показывали, где код функции начинается, а где заканчивается. Разделители – только двоеточие (:) и отступы самого кода.

def approximate_size(size, a_kilobyte_is_1024_bytes=True):     ①
    if size < 0:                                               ②
        raise ValueError('число должно быть неотрицательным')  ③
                                                               ④
    multiple = 1024 if a_kilobyte_is_1024_bytes else 1000
    for suffix in SUFFIXES[multiple]:                          ⑤
        size /= multiple
        if size < multiple:
            return '{0:.1f} {1}'.format(size, suffix)

    raise ValueError('число слишком большое')
  1. Строка 1. Блоки кода определяются по их отступам. Под «блоками кода» я подразумеваю функции, блоки if, циклы for и while и т. д. Увеличение отступа начинает блок, а уменьшение – заканчивает. Ни скобок, ни ключевых слов. Это означает, что важное значение имеют пробелы, и их количество тоже. В этом примере код функции имеет отступ в четыре пробела. Здесь не обязательно должно быть именно четыре пробела, просто их число должно быть постоянным. Первая встретившаяся строчка без отступа будет означать конец функции.
  2. Строка 2. За оператором if должен следовать блок кода. Если в результате вычисления условного выражения оно окажется истинным, то выполнится блок, выделенный отступом, в противном случае произойдёт переход к блоку else (если он есть). Обратите внимание, что нет скобок вокруг выражения.
  3. Строка 3. Эта строка находится внутри блока if. Оператор raise вызывает исключение (типа ValueError), но только если size < 0.
  4. Строка 4. Это ещё не конец функции. Совсем пустые строки не считаются. Они могут повысить читаемость кода, но не могут служить разделителями блоков кода. Блок кода функции продолжается на следующей строке.
  5. Строка 6. Оператор цикла for тоже начинает блок кода. Блоки кода могут содержать несколько строк, а именно – столько, сколько строк имеют такую же величину отступа. Этот цикл for содержит три строки кода. Других синтаксических конструкций для описания многострочных блоков кода нет. Просто делайте отступы, и будет вам счастье!

После того, как вы переборете внутренние противоречия и проведёте пару ехидных аналогий с Фортраном, вы подружитесь с отступами и начнёте видеть их преимущества. Одно из главных преимуществ – то, что все программы на Python выглядят примерно одинаково, поскольку отступы – требование языка, а не вопрос стиля. Благодаря этому становится проще читать и понимать код на Python, написанный другими людьми.

В Python используются символы возврата каретки для разделения операторов, а также двоеточие и отступы для разделения блоков кода. В C++ и Java используются точки с запятой для разделения операторов и фигурные скобки для блоков кода.

1.7 Исключения

Исключения (англ. exceptions – нештатные, исключительные ситуации, требующие специальной обработки) используются в Python повсюду. Буквально каждый модуль в стандартной библиотеке Python использует их, да и сам Python вызывает их во многих ситуациях. Вы ещё неоднократно встретите их на страницах этой книги.

Что такое исключение? Обычно это ошибка, признак того, что что-то пошло не так. (Не все исключения являются ошибками, но пока это не важно.) В некоторых языках программирования принято возвращать код ошибки, который вы потом проверяете. В Python принято использовать исключения, которые вы обрабатываете.

Когда происходит ошибка в оболочке Python, она выводит кое-какие подробности об исключении и о том, как это случилось, и всё. Это называется необработанным исключением. Когда это исключение было вызвано, не нашлось никакого программного кода, чтобы заметить его и обработать должным образом, поэтому оно всплыло на самый верхний уровень – в оболочку Python, которая вывела немного отладочной информации и успокоилась. В оболочке это не так уж страшно, однако если это произойдёт во время работы настоящей программы, то, если исключение не будет обработано, вся программа с грохотом упадёт. Может быть это то, что вам нужно, а может, и нет.

В отличие от Java, функции в Python не содержат объявлений о том, какие исключения они могут вызывать. Вам решать, какие из возможных исключений необходимо отлавливать.

Результат исключения – это не всегда полный крах программы. Исключения можно обработать. Иногда исключения возникают из-за настоящих ошибок в вашем коде (например, доступ к переменной, которая не существует), но порой исключение – это нечто, что вы можете предвидеть. Если вы открываете файл, он может не существовать. Если вы импортируете модуль, он может быть не установлен. Если вы подключаетесь к базе данных, она может быть недоступна или у вас может быть недостаточно прав для доступа к ней. Если вы знаете, что какая-то строка кода может вызвать исключение, то его следует обработать с помощью блока try...except.

Python использует для обработки исключений блоки try...except, а для их генерации – оператор raise. Java и C++ используют для обработки исключений блоки try...catch, а для их генерации – оператор throw.

Функция approximate_size() вызывает исключение в двух разных случаях: если переданный ей размер (size) больше, чем функция может обработать, или если он меньше нуля.

if size < 0:
    raise ValueError('число должно быть неотрицательным')

Синтаксис вызова исключений достаточно прост. Надо написать оператор raise, за ним название исключения и опционально, поясняющую строку для отладки. Синтаксис напоминает вызов функции. (На самом деле, исключения реализованы как классы, и оператор raise просто создаёт экземпляр класса ValueError и передаёт в его метод инициализации строку ‘число должно быть неотрицательным‘. Но мы забегаем вперёд!)

Нет необходимости обрабатывать исключение в той функции, которая его вызвала. Если одна функция не обработает его, исключение передаётся в функцию, вызвавшую эту, затем в функцию, вызвавшую вызвавшую, и т. д. «вверх по стеку». Если исключение нигде не будет обработано, то программа упадёт, а Python выведет «раскрутку стека» (англ. traceback) в стандартный поток ошибок – и на этом конец. Повторяю, возможно, это именно то, что вам нужно, – это зависит от того, что делает ваша программа.

1.7.1 Отлов ошибок импорта

Одно из встроенных исключений Python – ImportError (ошибка импорта), которое вызывается, если не удаётся импортировать модуль. Это может случиться по нескольким причинам, самая простая из которых – отсутствие модуля в пути поиска, оператора import. Вы можете использовать это для включения в программу опциональных возможностей. Например, библиотека chardet предоставляет возможность автоматического определения кодировки символов. Предположим, ваша программа хочет использовать эту библиотеку в том случае, если она есть, или спокойно продолжить работу, если пользователь не установил её. Можно сделать это с помощью блока try...except.

try:
  import chardet
except ImportError:
  chardet = None

После этого можно проверять наличие модуля chardet простым if:

if chardet:
  # что-то сделать
else:
  # продолжить дальше

Другое частое применение исключения ImportError – выбор из двух модулей, предоставляющих одинаковый интерфейс (API), причём применение одного из них предпочтительнее другого (может, он быстрее работает или требует меньше памяти). Для этого можно попытаться импортировать сначала один модуль, и если это не удалось , то импортировать другой. К примеру, в главе XML рассказывается о двух модулях, реализующих один и тот же API, так называемый ElementTree API. Первый – lxml – сторонний модуль, который необходимо скачивать и устанавливать самостоятельно. Второй – xml.etree.ElementTree – медленнее, но входит в стандартную библиотеку Python 3.

try:
    from lxml import etree
except ImportError:
    import xml.etree.ElementTree as etree

При выполнении этого блока try...except будет импортирован один из двух модулей под именем etree. Поскольку оба модуля реализуют один и тот же API, то в последующем коде нет необходимости проверять, какой из этих модулей был импортирован. И раз импортированный модуль в любом случае именуется как etree, то не придётся вставлять лишние if для обращения к разноимённым модулям.

1.8 Несвязанные переменные

Взглянем ещё раз на вот эту строку функции approximate_size():

multiple = 1024 if a_kilobyte_is_1024_bytes else 1000

Мы нигде не объявляли переменную multiple (множитель), мы только присвоили ей значение. Всё в порядке, Python позволяет так делать. Что он не позволит сделать, так это обратиться к переменной, которой не было присвоено значение. Если попытаться так сделать, возникнет исключение NameError (ошибка в имени).

>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> x = 1
>>> x
1

Перевод сообщения оболочки

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

Раскрутка стека (список последних вызовов):
Файл «<stdin>», строка 1, <модуль>
NameError: имя ‘x’ не определено

Однажды вы скажете Python «спасибо» за это.

1.9 Всё чувствительно к регистру

Все имена в Python чувствительны к регистру – имена переменных, функций, классов, модулей, исключений. Всё, что можно прочитать, записать, вызвать, создать или импортировать, чувствительно к регистру.

>>> an_integer = 1
>>> an_integer
1
>>> AN_INTEGER
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'AN_INTEGER' is not defined
>>> An_Integer
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'An_Integer' is not defined
>>> an_inteGer
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'an_inteGer' is not defined

Перевод сообщений оболочки

Раскрутка стека (список последних вызовов):
Файл «<stdin>», строка 1, <модуль>
NameError: имя ‘<имя>’ не определено

1.10 Запуск скриптов

В Python всё является объектом.

Модули Python – это объекты, имеющие несколько полезных атрибутов. И это обстоятельство можно использовать для простого тестирования модулей, при их написании, путём включения специального блока кода, который будет выполняться при запуске файла из командной строки. Взгляните на последние строки humansize.py:

if __name__ == '__main__':
    print(approximate_size(1000000000000, False))
    print(approximate_size(1000000000000))

Как и в C, в Python оператор == используется для проверки на равенство, а оператор = используется для присваивания. Но в отличие от C, Python не поддерживает присваивание внутри другого выражения, поэтому у вас не получится случайно присвоить значение вместо проверки на равенство.

Итак, что же делает этот блок if особенным? У всех модулей, как у объектов, есть встроенный атрибут __name__ (имя). И значение этого атрибута зависит от того, как модуль используется. Если модуль импортируется, то __name__ принимает значение равное имени файла модуля, без расширения и пути к каталогу.

>>> import humansize
>>> humansize.__name__
'humansize'

Но модуль можно запустить и напрямую, как самостоятельную программу, в этом случае __name__ примет специальное значение по умолчанию, __main__. Python вычислит значение условного выражения в операторе if, определит его истинность, и выполнит блок кода if. В данном случае, будут напечатаны два значения.

c:homediveintopython3> c:python31python.exe humansize.py
1.0 TB
931.3 GiB

И это ваша первая программа на Python!

1.11 Материалы для дальнейшего чтения

  • PEP 257: Docstring Conventions объясняет, чем отличается хорошая строка документации от великолепной.
  • Python Tutorial: Documentation Strings также касается данного вопроса.
  • PEP 8: Style Guide for Python Code обсуждает хороший стиль расстановки отступов.
  • Python Reference Manual объясняет, что означают слова «в Python всё является объектом», потому что некоторые люди – педанты, которые любят длиннющие обсуждения вещей такого рода.

Время на прочтение
5 мин

Количество просмотров 38K

Это сделает Python великим

Оригинал «25 Useful Python One-Liners That You Should know» от Abhay Parashar

Перед прочтением: в руках каждого разработчика должны быть удобные и практичные инструменты. Однострочники, как и синтаксический сахар, — это пример грамотного написания кода, который повышает вашу продуктивность и качество в глазах коллег, но при этом не требует каких-то сверхестественных усилий. Надеюсь, перевод данной статьи окажется полезным.

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

1. Сменка двух переменных

# a = 4 b = 5
a,b = b,a
# print(a,b) >> 5,4

Давайте начнем с чего-то более простого, например, поменяем местами две переменные друг с другом. Этот метод — один из самых простых и интуитивно понятных методов, который вы можете написать без необходимости использовать временную переменную или применять арифметические операции.

2. Множественные присвоения переменных

a,b,c = 4,5.5,'Hello'
#print(a,b,c) >> 4,5.5,hello

Вы можете использовать запятые и переменные, чтобы назначать нескольким переменным значения за раз. Используя этот метод, вы даже можете назначить несколько типов данных var за раз. Вы можете использовать список для присвоения значений переменным. Ниже приведен пример присвоения нескольких значений разным переменным из списка.

a,b,*c = [1,2,3,4,5]
print(a,b,c)
> 1 2 [3,4,5]

3. Сумма четных чисел в списке

Для этого может быть много способов, но лучший и самый простой способ — использовать индексирование списка и функцию суммирования.

a = [1,2,3,4,5,6]
s = sum([num for num in a if num%2 == 0])
print(s)
>> 12

4. Удаление нескольких элементов из списка

del — ключевое слово, используемое в Python для удаления объектов из списка.

#### Удаляем все четные числа
a = [1,2,3,4,5]
del a[1::2]
print(a)
>[1, 3, 5]

5. Чтение файлов

lst = [line.strip() for line in open('data.txt')]
print(lst)

Здесь мы используем понимание того, как устроен список. Сначала мы открываем текстовый файл и с помощью цикла for читаем строку за строкой. В итоге с помощью strip убираем все лишнее пространство. Но есть один более простой и короткий способ сделать то же самое, используя только функцию списка.

list(open('data.txt'))
##Использование with также закроет файл после использования
with open("data.txt") as f: lst=[line.strip() for line in f]
print(lst)

6. Запись данных в файл

with open("data.txt",'a',newline='n') as f: f.write("Python is awesome")

Приведенный выше код сначала создаст файл data.txt, если его еще нет, а затем напишет в этом файле Python is awesome.

7. Создание списков

lst = [i for i in range(0,10)]
print(lst)
> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

или

lst = list(range(0,10))
print(lst)

Мы также можем создать список строк, используя тот же метод.

lst = [("Hello "+i) for i in ['Karl','Abhay','Zen']]
print(lst)
> ['Hello Karl', 'Hello Abhay', 'Hello Zen']

8. Mapping списков, или изменение типа данных в списке

Иногда в нашем проекте нам нужно изменить типы данных всех элементов в списке. Первый способ, который приходит вам в голову, — использовать цикл, а затем получить доступ ко всем элементам из списка, а затем один за другим изменить тип данных элементов. Этот метод предназначен для старой школы в Python. У нас есть функция map, которая может делать эту работу за нас.

list(map(int,['1','2','3']))
> [1, 2, 3]
list(map(float,[1,2,3]))
> [1.0, 2.0, 3.0]

# А вот как делалось раньше
[float(i) for i in [1,2,3]]
> [1.0, 2.0, 3.0]

9. Создание набора

Метод, который мы использовали для создания списков, также можно использовать для создания наборов. Давайте создадим набор с помощью метода, который возвращает квадратный корень всех четных чисел в диапазоне.

# Квадрат всех четных чисел в диапазоне
{x**2 for x in range(10) if x%2==0}
> {0, 4, 16, 36, 64}

10. Fizz Buzz

Это тест, в котором нам нужно написать программу, что печатает числа от 1 до 100. Но для чисел, кратных трем, выведет «Fizz» вместо числа, а для кратных пяти выведет «Buzz». (если кратно и трем, и пяти, то выводится, соответственно, FizzBuzz).

Похоже, нам нужно использовать циклы и несколько операторов if-else. Если вы попытаетесь сделать это на любом другом языке, то вам, возможно, придется написать до 10 строк кода. Но используя python, мы сможем реализовать FizzBuzz всего одной строкой кода.

['FizzBuzz' if i%3==0 and i%5==0 else 'Fizz' if i%3==0 else 'Buzz' if i%5==0 else i  for i in range(1,20)]

В приведенном выше коде мы используем понимание списка для запуска цикла от 1 до 20, а затем на каждой итерации цикла мы проверяем, делится ли число на 3 или 5. Если да, то мы заменяем число на Fizz или Buzz соответственно (при выполнении обоих условий заменим число на FizzBuzz).

11. Палиндром

Палиндром — это число или строка, которые в обратном виде выглядят одинаково.

text = 'level'
ispalindrome = text == text[::-1]
ispalindrome
> True

12. Целые числа, разделенные пробелами, в списке

lis = list(map(int, input().split()))
print(lis)
> 1 2 3 4 5 6 7 8
[1, 2, 3, 4, 5, 6, 7, 8]

13. Лямбда-функция

Лямбда-функция — это небольшая анонимная функция.

Лямбда-функция может принимать любое количество аргументов, но может иметь только одно __выражение.

sqr = lambda x: x * x  ##Функция, возвращающая квадрат любого числа
sqr(10)
> 100

14. Проверить наличие числа в списке

num = 5
if num in [1,2,3,4,5]:
     print('present')
> present

15. Вывод паттернов

Паттерны — это то, что меня всегда увлекало. В python мы можем рисовать удивительные паттерны, используя всего одну строку кода.

n = 5
print('n'.join('?' * i for i in range(1, n + 1)))
>
?
??
???
????
?????

16. Нахождение факториала

Факториал — это произведение целого числа и всех целых чисел в порядке перед ним.

import math
n = 6
math.factorial(n)
> 720

17. Ряд Фибоначчи

Ряд Фибоначчи — это серия чисел, в которой каждое число (число Фибоначчи) является суммой двух предыдущих чисел. Простейший ряд Фибоначчи: 1, 1, 2, 3, 5, 8, 13 и т.д. Мы можем использовать создание списка и цикл for для создания ряда Фибоначчи в необходимом нам диапазоне.

fibo = [0,1]
[fibo.append(fibo[-2]+fibo[-1]) for i in range(5)]
fibo
> [0, 1, 1, 2, 3, 5, 8]

18. Простое число

Простое число — это число, которое делится только само на себя и 1. например: 2,3,5,7 и т. Д. Чтобы сгенерировать простые числа в диапазоне, мы можем использовать функцию списка с фильтром и лямбда для генерации простых чисел.

list(filter(lambda x:all(x % y != 0 for y in range(2, x)), range(2, 13)))
> [2, 3, 5, 7, 11]

19. Нахождение максимального числа

findmax = lambda x,y: x if x > y else y 
findmax(5,14)
> 14
или 
max(5,14)

В приведенном выше коде с использованием лямбда-функции мы проверяем условие сравнения и в соответствии с ним возвращаем максимальное число.

20. Линейная алгебра

Иногда нам нужно увеличить числа в списке в 2 или 5 раз. Код ниже покажет, как это сделать.

def scale(lst, x): return [i*x for i in lst] 
scale([2,3,4], 2) ## вызов функции
> [4,6,8]

21. Транспонировать матрицу

Если вам нужно преобразовать все строки в столбцы и наоборот, в python вы можете транспонировать матрицу всего в одну строку кода, используя функцию zip.

a=[[1,2,3],
   [4,5,6],
   [7,8,9]] 
transpose = [list(i) for i in zip(*a)] 
transpose
> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

22. Подсчет нахождений паттерна

Это важный и рабочий метод, когда нам нужно знать количество повторений паттерна в тексте. В python есть библиотека re, которая сделает эту работу за нас.

import re; len(re.findall('python','python is a programming language. python is python.'))
> 3

23. Замена текста другим текстом

"python is a programming language. python is python".replace("python",'Java')
> Java is a programming language. Java is Java

24. Симуляция подбрасывания монеты

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

import random; random.choice(['Head',"Tail"])
> Head

25. Генерация групп

groups = [(a, b) for a in ['a', 'b'] for b in [1, 2, 3]] 
groups
> [('a', 1), ('a', 2), ('a', 3), ('b', 1), ('b', 2), ('b', 3)]

Я поделился всеми полезными и важными однострочниками, которые я знаю. Если вы знаете какие-то ещё, поделитесь в комментариях.

Понравилась статья? Поделить с друзьями:
  • Как написать простой калькулятор на пайтон
  • Как написать простой калькулятор на python
  • Как написать простой калькулятор на java
  • Как написать простой антивирус
  • Как написать простой http сервер