Writing a Script in Python
So far, we have covered the main programming structures used in Python. We will now put that together in a script which can be run on demand.
Using Spyder which is part of the Anaconda suite
Spyder is an application where you can edit and run your Python scripts. As part of Anaconda, there are a large number of scientific packages which come pre-installed, to make it easier for scientists getting started in programming.
- Open Anaconda Navigator and launch Spyder.
We will run through a brief overview of the panels:
- Left panel: Editor
- this is a special type of editor which understands python
- as you type, possible options may appear to assist you
- key words are highlighted to help readability and understanding
- Top Right panel: Help
- Variable explorer: as a program runs, variables are loaded here with their values
- File explorer: list of files in the current working directory
- Help: documentation and tutorials
- Bottom Right panel: Console
- Python console: standard python command-line (like typing python in a terminal window)
- IPython console: interactive python (like Jupyter cells)
Organizing your code to run as a script
In Spyder, a new file is created when you first open the application. This is called temp.py.
- Create a new project under Projects -> New Project in your required directory
- Save the temp file to hello.py
- Type the following (the HelloWorld mantra):
- Click on the green arrow in the top toolbar. A popup window may appear which allows you to change a few things. Accept the defaults and click OK
- Have a look in the IPython console window and you should see the output similar to:
Methods
Recall that it is useful to group code into methods so replace the code with:
- Run again as before and the same output will appear in the console window.
- As we have run the output in the IPython console window and we have defined a method called hello() , what will happen if we just type hello() in the console?
Libraries
We will now use a library as we did in previous lessons. Take note of the order.
- The import statement goes at the top
- The methods should come next but should be before the instructions (main body)
- The instructions for running the methods go at the end
try this example:
After running this script, you can type help(math) in the IPython console — just as we did in Jupyter but it has to be loaded with import math first
External
Before we move on, there is an extra line recommended when running the script from outside this environment:
Insert this line above hello() then indent the following code:
This allows us to run from a terminal window: python hello.py
Flexible code — running with arguments
So how would we make this script more dynamic?
We will change the hello() method to take a variable name .
After running the script, in the IPython console, type hello(«Napoleon») or any other name
Challenge
Change the call function to loop over a few names (your first spamming script!).
External Arguments
But these are still variables defined in the script, how do we pass variables in from the command line? There is a library called sys which allows your script to read from the system in which it is running. Variables passed in are called arguments and are strings which are stored in a list called sys.argv
In a new script called sysargs.py, type:
Only one argument is present and that is the name of the program which is running — this will always be the case. We will now include two extra arguments so add some extra lines to the code:
- In Spyder, we can add the extra arguments by:
- Run -> Configure
- Check Command line options then enter “hello world” in the text field
- Click on OK
Challenge
Return to your hello.py script and allow the name to be entered as an argument
WARNING!! Allowing information to be passed into your script this way can be DANGEROUS. The argv array should never be read directly without checking the validity of the contents first.
Разработка надёжных Python-скриптов
Python — это язык программирования, который отлично подходит для разработки самостоятельных скриптов. Для того чтобы добиться с помощью подобного скрипта желаемого результата, нужно написать несколько десятков или сотен строк кода. А после того, как дело сделано, можно просто забыть о написанном коде и перейти к решению следующей задачи.
Если, скажем, через полгода после того, как был написан некий «одноразовый» скрипт, кто-то спросит его автора о том, почему этот скрипт даёт сбои, об этом может не знать и автор скрипта. Происходит подобное из-за того, что к такому скрипту не была написана документация, из-за использования параметров, жёстко заданных в коде, из-за того, что скрипт ничего не логирует в ходе работы, и из-за отсутствия тестов, которые позволили бы быстро понять причину проблемы.
При этом надо отметить, что превратить скрипт, написанный на скорую руку, в нечто гораздо более качественное, не так уж и сложно. А именно, такой скрипт довольно легко превратить в надёжный и понятный код, которым удобно пользоваться, в код, который просто поддерживать как его автору, так и другим программистам.
Автор материала, перевод которого мы сегодня публикуем, собирается продемонстрировать подобное «превращение» на примере классической задачи «Fizz Buzz Test». Эта задача заключается в том, чтобы вывести список чисел от 1 до 100, заменив некоторые из них особыми строками. Так, если число кратно 3 — вместо него нужно вывести строку Fizz , если число кратно 5 — строку Buzz , а если соблюдаются оба этих условия — FizzBuzz .
Исходный код
Вот исходный код Python-скрипта, который позволяет решить задачу:
Поговорим о том, как его улучшить.
Документация
Я считаю, что полезно писать документацию до написания кода. Это упрощает работу и помогает не затягивать создание документации до бесконечности. Документацию к скрипту можно поместить в его верхнюю часть. Например, она может выглядеть так:
В первой строке даётся краткое описание цели скрипта. В оставшихся абзацах содержатся дополнительные сведения о том, что именно делает скрипт.
Аргументы командной строки
Следующей задачей по улучшению скрипта станет замена значений, жёстко заданных в коде, на документированные значения, передаваемые скрипту через аргументы командной строки. Реализовать это можно с использованием модуля argparse. В нашем примере мы предлагаем пользователю указать диапазон чисел и указать значения для «fizz» и «buzz», используемые при проверке чисел из указанного диапазона.
Эти изменения приносят скрипту огромную пользу. А именно, параметры теперь надлежащим образом документированы, выяснить их предназначение можно с помощью флага —help . Более того, по соответствующей команде выводится и документация, которую мы написали в предыдущем разделе:
Модуль argparse — это весьма мощный инструмент. Если вы с ним не знакомы — вам полезно будет просмотреть документацию по нему. Мне, в частности, нравятся его возможности по определению подкоманд и групп аргументов.
Логирование
Если оснастить скрипт возможностями по выводу некоей информации в ходе его выполнения — это окажется приятным дополнением к его функционалу. Для этой цели хорошо подходит модуль logging. Для начала опишем объект, реализующий логирование:
Затем сделаем так, чтобы подробностью сведений, выводимых при логировании, можно было бы управлять. Так, команда logger.debug() должна выводить что-то только в том случае, если скрипт запускают с ключом —debug . Если же скрипт запускают с ключом —silent — скрипт не должен выводить ничего кроме сообщений об исключениях. Для реализации этих возможностей добавим в parse_args() следующий код:
Добавим в код проекта следующую функцию для настройки логирования:
Основной код скрипта при этом изменится так:
Если скрипт планируется запускать без прямого участия пользователя, например, с помощью crontab , можно сделать так, чтобы его вывод поступал бы в syslog :
В нашем небольшом скрипте неоправданно большим кажется подобный объём кода, нужный только для того, чтобы воспользоваться командой logger.debug() . Но в реальных скриптах этот код уже таким не покажется и на первый план выйдет польза от него, заключающаяся в том, что с его помощью пользователи смогут узнавать о ходе решения задачи.
Тесты
Модульные тесты — это полезнейшее средство для проверки того, ведёт ли себя приложения так, как нужно. В скриптах модульные тесты используют нечасто, но их включение в скрипты значительно улучшает надёжность кода. Преобразуем код, находящийся внутри цикла, в функцию, и опишем несколько интерактивных примеров её использования в её документации:
Проверить правильность работы функции можно с помощью pytest :
Для того чтобы всё это заработало, нужно, чтобы после имени скрипта шло бы расширение .py . Мне не нравится добавлять расширения к именам скриптов: язык — это лишь техническая деталь, которую не нужно демонстрировать пользователю. Однако возникает такое ощущение, что оснащение имени скрипта расширением — это самый простой способ позволить системам для запуска тестов, вроде pytest , находить тесты, включённые в код.
В случае возникновения ошибки pytest выведет сообщение, указывающее на расположение соответствующего кода и на суть проблемы:
Модульные тесты можно писать и в виде обычного кода. Представим, что нам нужно протестировать следующую функцию:
В конце скрипта добавим следующие модульные тесты, использующие возможности pytest по использованию параметризованных тестовых функций:
Обратите внимание на то, что, так как код скрипта завершается вызовом sys.exit() , при его обычном вызове тесты выполняться не будут. Благодаря этому pytest для запуска скрипта не нужен.
Тестовая функция будет вызвана по одному разу для каждой группы параметров. Сущность args используется в качестве входных данных для функции parse_args() . Благодаря этому механизму мы получаем то, что нужно передать функции main() . Сущность expected сравнивается с тем, что выдаёт main() . Вот что сообщит нам pytest в том случае, если всё работает так, как ожидается:
Если произойдёт ошибка — pytest даст полезные сведения о том, что случилось:
В эти выходные данные включён и вывод команды logger.debug() . Это — ещё одна веская причина для использования в скриптах механизмов логирования. Если вы хотите узнать подробности о замечательных возможностях pytest — взгляните на этот материал.
Итоги
Сделать Python-скрипты надёжнее можно, выполнив следующие четыре шага:
- Оснастить скрипт документацией, размещаемой в верхней части файла.
- Использовать модуль argparse для документирования параметров, с которыми можно вызывать скрипт.
- Использовать модуль logging для вывода сведений о процессе работы скрипта.
- Написать модульные тесты.
Вокруг этого материала развернулись интересные обсуждения — найти их можно здесь и здесь. Аудитория, как кажется, хорошо восприняла рекомендации по документации и по аргументам командной строки, а вот то, что касается логирования и тестов, показалось некоторым читателям «пальбой из пушки по воробьям». Вот материал, который был написан в ответ на данную статью.
Уважаемые читатели! Планируете ли вы применять рекомендации по написанию Python-скриптов, данные в этой публикации?
Cкрипты — Python: Настройка окружения
В интерпретируемых языках от написания кода до запуска — всего один шаг. Ничего не нужно компилировать в машинный код.
Всю работу делает интерпретатор, которому достаточно подать на вход скрипт — программу на интерпретируемом языке. Внутри этой программы записаны простые последовательности команд, которые компьютеру нужно выполнить.
Если на каком-то языке удобно писать скрипты, его называют «скриптовым языком» или «языком для написания сценариев».
Скрипты на Python
Python отлично подходит на роль скриптового языка. Последовательность команд в простых сценариях не нужно никак оформлять и запускать скрипты максимально просто. Мы просто пишем команды одну за другой в файл:
Затем мы просто вызываем интерпретатор с полученным файлом на входе:
У Python много полезных модулей и функций, входящих в поставку. Поэтому его часто используют для автоматизации различных задач, которые не хочется выполнять вручную при работе на компьютере. К тому же написание скриптов — отличная отправная точка для тех, кто только начинает знакомиться с программированием.
Скрипты и shebang
В Linux, macOS, BSD и других unix-подобных операционных системах командные оболочки умеют запускать скрипты на любых языках, в том числе и на Python. При этом скрипты сообщают оболочке, какой интерпретатор нужно вызывать для выполнения сценария.
Интерпретатор указывается специальной строкой в самой первой строчке файла скрипта, которая называется shebang. Это название произошло от первых двух символов такой строчки: # называется sharp, а ! — bang.
Типичный shebang выглядит так:
После символов #! идет путь до интерпретатора. При запуске скрипта с shebang командная оболочка читает первую строку и пробует запустить указанный интерпретатор. Если скрипту с указанным shebang дать права на исполнение, то интерпретатор в командной строке можно не указывать:
Shebang и разные версии Python
В целом shebang — штука довольно простая, когда интерпретатор в системе ровно один. Но мы с вами знаем, что версий Python в системе может быть установлено несколько. Более того, в виртуальном окружении путь к интерпретатору будет отличаться от /usr/bin и будет разным в разных окружениях.
Как сделать так, чтобы скрипт запускался всегда с нужной версией Python? Нужно всего лишь не указывать путь до команды python напрямую, а использовать программу env .
Эта программа умеет находить и запускать программы с учетом переменных окружения. При активации виртуального окружения модифицируется переменная $PATH , поэтому env будет запускать именно ту версию интерпретатора, которая нам нужна. Нужная версия просто найдется раньше, потому что путь до исполняемых файлов окружения добавляется в начало $PATH .
А теперь рассмотрим правильный способ указывать shebang в проектах на python:
Открыть доступ
Курсы программирования для новичков и опытных разработчиков. Начните обучение бесплатно
30 python scripts examples
You can write and execute a simple python script from the terminal without creating any python file. If the script is large, then it requires writing and saves the script in any python file by using any editor. You can use any text editor or any code editor like sublime, Visual Studio Code, or any IDE software developed for python only like PyCharm or Spyder to write the script. The extension of the python file is .py. The python version 3.8 and the spyder3 IDE of python are used in this article to write the python script. You have to install spyder IDE in your system to use it.
If you want to execute any script from the terminal, then run the ‘python’ or ‘python3’ command to open python in interaction mode. The following python script will print the text “Hello World” as output.
Now, save the script in a file named c1.py. You have to run the following command from the terminal to execute c1.py.If you want to run the file from spyder3 IDE, then you have to click on the run button
of the editor. The following output will show in the editor after executing the code.Joining two strings:
There are many ways to join string values in python. The most simple way to combine two string values in python is to use the ‘+’ operator. Create any python with the following script to know the way to join two strings. Here, two string values are assigned in two variables, and another variable is used to store the joined values that are printed later.
c2.py
The following output will appear after running the script from the editor. Here, two words, “Linux” and “Hint” are joined, and “LinuxHint” is printed as output.
If you want to know more about the other joining option in python, then you can check the tutorial, Python String Concatenation.
Format floating point in the string:
Floating point number is required in programming for generating fractional numbers, and sometimes it requires formatting the floating-point number for programming purposes. There are many ways to exist in python to format the floating-point number. String formatting and string interpolation are used in the following script to format a floating-point number. format() method with format width is used in string formatting, and ‘%” symbol with the format with width is used in string interpolation. According to the formatting width, 5 digits are set before the decimal point, and 2 digits are set after the decimal point.
c3.py
# Use of String Formatting
float1 = 563.78453
print ( "<:5.2f>" . format ( float1 ) )# Use of String Interpolation
float2 = 563.78453
print ( "%5.2f" % float2 )The following output will appear after running the script from the editor.
If you want to know more about string formatting in python, then you can check the tutorial, Python String Formatting.
Raise a number to a power:
Many ways exist in python to calculate the x n in Python. In the following script, three ways are shown to calculate the xn in Python. Double ‘*’ operator, pow() method, and math.pow() method are used for calculating the xn. The values of x and n are initialized with numeric values. Double ‘*’ and pow() methods are used for calculating the power of integer values. math.pow() can calculate the power of fractional numbers; also, that is shown in the last part of the script.
c4.py
import math
# Assign values to x and n
x = 4
n = 3# Method 1
power = x ** n
print ( "%d to the power %d is %d" % ( x , n , power ) )# Method 2
power = pow ( x , n )
print ( "%d to the power %d is %d" % ( x , n , power ) )# Method 3
power = math . pow ( 2 , 6.5 )
print ( "%d to the power %d is %5.2f" % ( x , n , power ) )The following output will appear after running the script. The first two outputs show the result of 4 3, and the third output shows the result of 2 6.5 .
Working with Boolean types:
The different uses of Boolean types are shown in the following script. The first output will print the value of val1 that contains the Boolean value, true. All positive are negative numbers return true as Boolean value and only zero returns false as a Boolean value. So, the second and third outputs will print true for positive and negative numbers. The fourth output will print false for 0, and the fifth output will print false because the comparison operator returns false.
c5.py
# Boolean value
val1 = True
print ( val1 )# Number to Boolean
number = 10
print ( bool ( number ) )number = — 5
print ( bool ( number ) )number = 0
print ( bool ( number ) )# Boolean from comparison operator
val1 = 6
val2 = 3
print ( val1 < val2 )The following output will appear after running the script.
Use of If else statement:
The following script shows the use of a conditional statement in python. The declaration of the if-else statement in python is a little bit different than other languages. No curly brackets are required to define the if-else block in python like other languages, but the indentation block must be used properly other the script will show an error. Here, a very simple if-else statement is used in the script that will check the value of the number variable is more than or equal to 70or not. A colon(:) is used after the ‘if’ and ‘else’ block to define the starting of the block.
c6.py
# Assign a numeric value
number = 70# Check the is more than 70 or not
if ( number >= 70 ) :
print ( "You have passed" )
else :
print ( "You have not passed" )The following output will appear after running the script.
Use of AND and OR operators:
The following script shows the uses of AND and OR operators in the conditional statement. AND operator returns true when the two conditions return true, and OR operator returns true when any condition of two conditions returns true. Two floating-point numbers will be taken as MCQ and theory marks. Both AND and OR operators are used in the ‘if’ statement. According to the condition, if the MCQ marks are more than equal to 40 and theory marks is more than or equal to 30 then the ‘if’ statement will return true or if the total of MCQ and theory is more than or equal to 70 then the ‘if’ statement will also return true.
c7.py
# Take MCQ marks
mcq_marks = float ( input ( "Enter the MCQ marks: " ) )
# Take theory marks
theory_marks = float ( input ( "Enter the Theory marks: " ) )# Check the passing condition using AND and OR operator
if ( mcq_marks >= 40 and theory_marks >= 30 ) or ( mcq_marks + theory_marks ) >= 70 :
print ( " \n You have passed" )
else :
print ( " \n You have failed" )According to the following output, if statement returns false for the input values 30 and 35, and returns true for the input values 40 and 45.
switch case statement:
Python does not support a switch-case statement like other standard programming languages, but this type of statement can be implemented in python by using a custom function. employee_details() function is created in the following script to work like the switch-case statement. The function contains one parameter and a dictionary named switcher. The value of the function parameter is checked with each index of the dictionary. If any match found, then the corresponding value of the index will be returned from the function; otherwise, the second parameter value of the switcher.get() method will be returned.
c8.py
# Switcher for implementing switch case options
def employee_details ( ID ) :
switcher = {
"1004" : "Employee Name: MD. Mehrab" ,
"1009" : "Employee Name: Mita Rahman" ,
"1010" : "Employee Name: Sakib Al Hasan" ,
}
»’The first argument will be returned if the match found and
nothing will be returned if no match found»’
return switcher. get ( ID , "nothing" )# Take the employee ID
ID = input ( "Enter the employee ID: " )
# Print the output
print ( employee_details ( ID ) )According to the following output, the script is executed two times, and two employee names are printed based on the ID values.
Use of while Loop:
The use of a while loop in python is shown in the following example. The colon(:) is used to define the starting block of the loop, and all statements of the loop must be defined using proper indentation; otherwise, indentation error will appear. In the following script, the counter value is initialized to 1 that is used in the loop. The loop will iterate 5 times and print the values of the counter in each iteration. The counter value is incremented by 1 in each iteration to reach the termination condition of the loop.
c9.py
The following output will appear after running the script.
Use of for Loop:
for loop is used for many purposes in python. The starting block of this loop is required to define by a colon(:), and the statements are defined by using proper indentation. In the following script, a list of weekday names is defined, and a for loop is used to iterate and print each item of the list. Here, len() method is used to count the total items of the list and define the limit of the range() function.
c10.py
The following output will appear after running the script.
Run one Python script from another:
Sometimes it is required to use the script of a python file from another python file. It can be done easily, like importing any module by using the import keyword. Here, vacations.py file contains two variables initialized by string values. This file is imported in c11.py file with the alias name ‘v’. A list of month names is defined here. The flag variable is used here to print the value of vacation1 variable for one time for the months ‘June’ and ‘July’. The value of the vacation2 variable will print for the month ‘December’. The other nine-month names will be printed when the else part of the if-elseif-else statement will be executed.
vacations.py
c11.py
# Import another python script
import vacations as v# Initialize the month list
months = [ "January" , "February" , "March" , "April" , "May" , "June" ,
"July" , "August" , "September" , "October" , "November" , "December" ]
# Initial flag variable to print summer vacation one time
flag = 0# Iterate the list using for loop
for month in months:
if month == "June" or month == "July" :
if flag == 0 :
print ( "Now" , v. vacation1 )
flag = 1
elif month == "December" :
print ( "Now" , v. vacation2 )
else :
print ( "The current month is" , month )The following output will appear after running the script.
Use of command-line argument:
The following script shows the use of command-line arguments in python. Many modules exist in python to parse the command-line arguments ‘sys’ module is imported here to parse the command-line arguments. len() method is used to count the total arguments, including the script file name. Next, the argument values will be printed.
c12.py
# Import sys module
import sys# Total number of arguments
print ( ‘Total arguments:’ , len ( sys . argv ) )print ( "Argument values are:" )
# Iterate command-line arguments using for loop
for i in sys . argv :
print ( i )If the script is executed without any command-line arguments, then the following output will appear that is showing the script filename.
The command-line argument values can be set in spyder editor by opening the Run configuration per file dialog box by clicking on the Run menu. Set the values with space by clicking the Command line options of General settings part of the dialog box.
If the script is executed after setting the values shown above, then the following output will appear.
The command-line argument values can be passed in the python script easily from the terminal. The following output will appear if the script is executed from the terminal.
If you want to know more about command-line arguments in python, then you can check the tutorial, How to parse arguments on command-line in Python.Use of regex:
Regular expression or regex is used in python to match or search and replace any particular portion of a string based on the particular pattern. ‘re’ module is used in python to use a regular expression. The following script shows the use of regex in python. The pattern used in the script will match those string where the first character of the string is a capital letter. A string value will be taken and match the pattern using match() method. If the method returns true, then a success message will print otherwise an instructional message will print.
c13.py
# Import re module
import re# Take any string data
string = input ( "Enter a string value: " )
# Define the searching pattern
pattern = ‘^[A-Z]’# match the pattern with input value
found = re . match ( pattern , string )# Print message based on the return value
if found:
print ( "The input value is started with the capital letter" )
else :
print ( "You have to type string start with the capital letter" )The script is executed two times in the following output. match() function returns false for the first execution and returns true for the second execution.
Use of getpass:
getpass is a useful module of python that is used to take password input from the user. The following script shows the use of the getpass module. getpass() method is used here to take the input as password and ‘if’ statement is used here to compare the input value with the defined password. “you are authenticated” message will print if the password matches otherwise it will print “You are not authenticated” message.
c14.py
# import getpass module
import getpass# Take password from the user
passwd = getpass . getpass ( ‘Password:’ )# Check the password
if passwd == "fahmida" :
print ( "You are authenticated" )
else :
print ( "You are not authenticated" )If the script runs from the spyder editor, then the input value will be shown because the editor console doesn’t support password mode. So, the following output shows the input password in the following output.
If the script executes from the terminal, then input value will not be shown like other Linux password. The script is executed two times from the terminal with an invalid and valid password that is shown in the following output.
Use of date format:
The date value can be formatted in python in various ways. The following script uses the datetime module to set the current and the custom date value. today() method is used here to read the current system date and time. Next, the formatted value of the date is printed by using different property names of the date object. How a custom date value can be assigned and printed is shown in the next part of the script.
c15.py
from datetime import date
# Read the current date
current_date = date. today ( )# Print the formatted date
print ( "Today is :%d-%d-%d" %
( current_date. day , current_date. month , current_date. year ) )# Set the custom date
custom_date = date ( 2020 , 12 , 16 )
print ( "The date is:" , custom_date )The following output will appear after executing the script.
Add and remove the item from a list:
list object is used in python for solving various types of problems. Python has many built-in functions to work with the list object. How a new item can be inserted and removed from a list is shown in the following example. A list of four items is declared in the script. Insert() method is used to insert a new item in the second position of the list. remove() method is used to search and remove the particular item from the list. The list is printed after the insertion and deletion.
c16.py
# Insert an item in the 2nd position
fruits. insert ( 1 , "Grape" )# Displaying list after inserting
print ( "The fruit list after insert:" )
print ( fruits )# Remove an item
fruits. remove ( "Guava" )# Print the list after delete
print ( "The fruit list after delete:" )
print ( fruits )The following output will appear after executing the script.
If you want to know more details about the insertion and deletion of the python script, then you can check the tutorial, “How to add and remove items from a list in Python”.List comprehension:
List comprehension is used in python to create a new list based on any string or tuple or another list. The same task can be done using for loop and lambda function. The following script shows two different uses of list comprehension. A string value is converted into a list of characters using list comprehension. Next, a tuple is converted into a list in the same way.
c17.py
# Create a list of characters using list comprehension
char_list = [ char for char in "linuxhint" ]
print ( char_list )# Define a tuple of websites
websites = ( "google.com" , "yahoo.com" , "ask.com" , "bing.com" )# Create a list from tuple using list comprehension
site_list = [ site for site in websites ]
print ( site_list )Slice data:
slice() method is used in python to cut the particular portion of a string. This method has three parameters. These parameters are start, stop, and step. The stop is the mandatory parameter, and the other two parameters are optional. The following script shows the uses of the slice() method with one, two, and three parameters. When one parameter is used in the slice() method, then it will use the mandatory parameter, stop. When the two parameters are used in the slice() method, then start and stop parameters are used. When all three parameters are used, then start, stop, and step parameters are used.
c18.py
# Assign string value
text = "Learn Python Programming"# Slice using one parameter
sliceObj = slice ( 5 )
print ( text [ sliceObj ] )# Slice using two parameter
sliceObj = slice ( 6 , 12 )
print ( text [ sliceObj ] )# Slice using three parameter
sliceObj = slice ( 6 , 25 , 5 )
print ( text [ sliceObj ] )The following output will appear after running the script. In the first slice() method, 5 is used as the argument value. It sliced the five characters of text variables that are printed as output. In the second slice() method, 6 and 12 are used as arguments. The slicing is started from position 6 and stopped after 12 characters. In the third slice() method, 6, 25, and 5 are used as arguments. The slicing is started from position 6, and the slicing stopped after 25 characters by omitting 5 characters in each step.
Add and search data in the dictionary:
dictionary object is used in python to store multiple data like the associative array of other programming languages. The following script shows how a new item can be inserted, and any item can be searched in the dictionary. A dictionary of customer information is declared in the script where the index contains the customer ID, and the value contains the customer name. Next, one new customer information is inserted at the end of the dictionary. A customer ID is taken as input to search in the dictionary. ‘for’ loop and ‘if’ condition is used to iterate the indexes of the dictionary and search the input value in the dictionary.
c19.py
# Define a dictionary
customers = { ‘06753’ : ‘Mehzabin Afroze’ , ‘02457’ : ‘Md. Ali’ ,
‘02834’ : ‘Mosarof Ahmed’ , ‘05623’ : ‘Mila Hasan’ , ‘07895’ : ‘Yaqub Ali’ }# Append a new data
customers [ ‘05634’ ] = ‘Mehboba Ferdous’print ( "The customer names are:" )
# Print the values of the dictionary
for customer in customers:
print ( customers [ customer ] )# Take customer ID as input to search
name = input ( "Enter customer ID:" )# Search the ID in the dictionary
for customer in customers:
if customer == name:
print ( customers [ customer ] )
breakThe following output will appear after executing the script and taking ‘02457’ as ID value.
If you want to know more about the other useful methods of the dictionary, then you can check the tutorial, “10 most useful Python Dictionary Methods”.Add and search data in set:
The following script shows the ways to add and search data in a python set. A set of integer data is declared in the script. add() method is used to insert new data in the set. Next, an integer value will be taken as input to search the value in the set by using for loop and if condition.
c20.py
# Define the number set
numbers = { 23 , 90 , 56 , 78 , 12 , 34 , 67 }# Add a new data
numbers. add ( 50 )
# Print the set values
print ( numbers )message = "Number is not found"
# Take a number value for search
search_number = int ( input ( "Enter a number:" ) )
# Search the number in the set
for val in numbers:
if val == search_number:
message = "Number is found"
breakThe script is executed two times with the integer value 89 and 67. 89 does not exist in the set, and “Number is not found” is printed. 67 exists in the set, and “Number is found” is printed.
If you want to know about the union operation in the set, then you can check the tutorial, “How to use union on python set”.
Count items in the list:
count() method is used in python to count how many times a particular string appears in other string. It can take three arguments. The first argument is mandatory, and it searches the particular string in the whole part of another string. The other two arguments of this method are used to limit the search by defining the searching positions. In the following script, the count() method is used with one argument that will search and count the word ‘Python’ in the string variable.
c21.py
The following output will appear after executing the script.
If you want to know more details about the count() method, then you can check the tutorial, How to use count() method in python.
Define and call a function:
How user-defined function can be declared and called in python is shown in the following script. Here, two functions are declared. addition() function contains two arguments to calculate the sum of two numbers and print the value. area() function contains one argument to calculate the area of a circle and return the result to the caller by using the return statement.
c22.py
# Define addition function
def addition ( number1 , number2 ) :
result = number1 + number2
print ( "Addition result:" , result )# Define area function with return statement
def area ( radius ) :
result = 3.14 * radius * radius
return result# Call addition function
addition ( 400 , 300 )
# Call area function
print ( "Area of the circle is" , area ( 4 ) )The following output will appear after executing the script.
If you want to know details about the return values from a python function, then you can check the tutorial, Return Multiple Values from A Python Function.Use of throw and catch exception:
try and catch block are used to throw and catch the exception. The following script shows the use of a try-catch block in python. In the try block, a number value will be taken as input and checked the number is even or odd. If any non-numeric value is provided as input, then a ValueError will be generated, and an exception will be thrown to the catch block to print the error message.
c23.py
# Try block
try :
# Take a number
number = int ( input ( "Enter a number: " ) )
if number % 2 == 0 :
print ( "Number is even" )
else :
print ( "Number is odd" )# Exception block
except ( ValueError ) :
# Print error message
print ( "Enter a numeric value" )The following output will appear after executing the script.
If you want to know more details about the exception handling in python, then you can check the tutorial, “Exception Handling in Python”.Read and Write File:
The following script shows the way to read from and write into a file in python. The filename is defined in the variable, filename. The file is opened for writing using the open() method at the beginning of the script. Three lines are written in the file using the write() method. Next, the same file is opened for reading using the open() method, and each line of the file is read and printed using for loop.
c24.py
#Assign the filename
filename = "languages.txt"
# Open file for writing
fileHandler = open ( filename , "w" )# Add some text
fileHandler. write ( "Bash \n " )
fileHandler. write ( "Python \n " )
fileHandler. write ( "PHP \n " )# Close the file
fileHandler. close ( )# Open file for reading
fileHandler = open ( filename , "r" )# Read a file line by line
for line in fileHandler:
print ( line )# Close the file
fileHandler. close ( )The following output will appear after executing the script.
If you want to know more details about reading and writing files in python, then you can check the tutorial, How to read and write to files in Python.
List files in a directory:
The content of any directory can be read by using the os module of python. The following script shows how to get the list of a specific directory in python using the os module. listdir() method is used in the script to find out the list of files and folders of a directory. for loop is used to print the directory content.
c25.py
# Import os module to read directory
import os# Set the directory path
path = ‘/home/fahmida/projects/bin’# Read the content of the file
files = os . listdir ( path )# Print the content of the directory
for file in files:
print ( file )The content of the directory will appear after executing the script if the defined path of the directory exists.
Read and write using pickle:
The following script shows the ways to write and read data using the pickle module of python. In the script, an object is declared and initialized with five numeric values. The data of this object is written into a file using the dump() method. Next, the load() method is used to read the data from the same file and store it in an object.
c26.py
# Import pickle module
import pickle# Declare the object to store data
dataObject = [ ]
# Iterate the for loop for 5 times
for num in range ( 10 , 15 ) :
dataObject. append ( num )# Open a file for writing data
file_handler = open ( ‘languages’ , ‘wb’ )# Dump the data of the object into the file
pickle . dump ( dataObject , file_handler )# close the file handler
file_handler. close ( )# Open a file for reading the file
file_handler = open ( ‘languages’ , ‘rb’ )# Load the data from the file after deserialization
dataObject = pickle . load ( file_handler )# Iterate the loop to print the data
for val in dataObject:
print ( ‘The data value : ‘ , val )# close the file handler
file_handler. close ( )The following output will appear after executing the script.
If you want to know more details about reading and writing using pickle, then you can check the tutorial, How to pickle objects in Python.
Define class and method:
The following script shows how a class and method can be declared and accessed in Python. Here, a class is declared with a class variable and a method. Next, an object of the class is declared to access the class variable and class method.
c27.py
# Define the class
class Employee:
name = "Mostak Mahmud"
# Define the methoddef details ( self ) :
print ( "Post: Marketing Officer" )
print ( "Department: Sales" )
print ( "Salary: $1000" )# Create the employee object
emp = Employee ( )# Print the class variable
print ( "Name:" , emp. name )# Call the class method
emp. details ( )The following output will appear after executing the script.
Use of range function:
The following script shows the different uses of range function in python. This function can take three arguments. These are start, stop, and step. The stop argument is mandatory. When one argument is used, then the default value of the start is 0. range() function with one argument, two arguments, and three arguments are used in the three for loops here.
c28.py
# range() with one parameter
for val in range ( 6 ) :
print ( val , end = ‘ ‘ )
print ( ‘ \n ‘ )# range() with two parameter
for val in range ( 5 , 10 ) :
print ( val , end = ‘ ‘ )
print ( ‘ \n ‘ )# range() with three parameter
for val in range ( 0 , 8 , 2 ) :
print ( val , end = ‘ ‘ )
print ( ‘ \n ‘ )The following output will appear after executing the script.
Use of map function:
map() function is used in python to return a list by using any user-defined function and any iterable object. In the following script, cal_power() function is defined to calculate the x n , and the function is used in the first argument of the map() function. A list named numbers is used in the second argument of the map() function. The value of x will be taken from the user, and the map() function will return a list of power values of x, based on the item values of the numbers list.
c29.py
# Define the function to calculate power
def cal_power ( n ) :
return x ** n# Take the value of x
x = int ( input ( "Enter the value of x:" ) )
# Define a tuple of numbers
numbers = [ 2 , 3 , 4 ]# Calculate the x to the power n using map()
result = map ( cal_power , numbers )
print ( list ( result ) )The following output will appear after executing the script.
Use of filter function:
filter() function of python uses a custom function to filter data from an iterable object and create a list with the items for those the function returns true. In the following script, SelectedPerson() function is used in the script to create a list of the filtered data based on the items of selectedList.
c30.py
# Define a list of participant
participant = [ ‘Monalisa’ , ‘Akbar Hossain’ ,
‘Jakir Hasan’ , ‘Zahadur Rahman’ , ‘Zenifer Lopez’ ]# Define the function to filters selected candidates
def SelectedPerson ( participant ) :
selected = [ ‘Akbar Hossain’ , ‘Zillur Rahman’ , ‘Monalisa’ ]
if ( participant in selected ) :
return TrueselectedList = filter ( SelectedPerson , participant )
print ( ‘The selected candidates are:’ )
for candidate in selectedList:
print ( candidate )The following output will appear after executing the script.
Conclusion:
The python programming basics are discussed using 30 different topics in this article. I hope the examples of this article will help the readers to learn python easily from the beginning.
About the author
Fahmida Yesmin
I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.