Что делают на python примеры
Перейти к содержимому

Что делают на python примеры

  • автор:

60 Python Projects with Source Code

60 Python Projects with Source code solved and explained for free

Aman Kharwal

Coders Camp

Python has been in the top 10 popular programming languages for a long time, as the community of Python programmers has grown a lot due to its easy syntax and library support. In this article, I will introduce you to 60 amazing Python projects with source code solved and explained for free.

Python Projects with Source Code

Python Projects For Beginners:

If you’re a newbie to Python where you’ve just learned lists, tuples, dictionaries, and some basic Python modules like the random module, here are some Python projects with source code for beginners for you:

Advance Python Projects:

If you have learned the fundamental Python libraries and some of the external libraries, you should now know how to install external libraries and work with them. So if you are at that level now, you can work on all the advanced Python projects with source code mentioned below:

So these were some very useful Python projects with source code for both a beginner and someone in advance level of Python. I hope you liked this article on Python Projects with source code solved and explained. Feel free to ask your valuable questions in the comments section below.

22 полезных примера кода на Python

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

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

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

Этот пример возвращает в строке найденные гласные "a e i o u" . Это может оказаться полезным при поиске или обнаружении гласных.

2. Первая буква в верхнем регистре

Этот пример используется для превращения каждой первой буквы символов строки в прописную букву. Он работает со строкой из одного или нескольких символов и будет полезен при анализе текста или записи данных в файл и т.п.

3. Печать строки N раз

Этот пример может печатать любую строку n раз без использования циклов Python.

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

Этот пример выполняет слияние двух словарей в один.

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

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

6. Обмен значений между переменными

Это быстрый способ обменять местами две переменные без использования третьей.

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

Это самый быстрый способ проверки наличия повторяющихся значений в списке.

8. Фильтрация значений False

Этот пример используется для устранения всех ложных значений из списка, например false, 0, None, " " .

9. Размер в байтах

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

10. Занятая память

Пример позволяет получить объём памяти, используемой любой переменной в Python.

11. Анаграммы

Этот код полезен для проверки того, является ли строка анаграммой. Анаграмма — это слово, полученное перестановкой букв другого слова.

12. Сортировка списка

Этот пример сортирует список. Сортировка — это часто используемая задача, которую можно реализовать множеством строк кода с циклом, но можно ускорить свою работу при помощи встроенного метода сортировки.

13. Сортировка словаря

14. Получение последнего элемента списка

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

Этот код преобразует разделённый запятыми список в единую строку. Его удобно использовать, когда нужно объединить весь список со строкой.

16. Проверка палиндромов

Этот пример показывает, как быстро проверить наличие палиндромов.

17. Перемешивание списка

18. Преобразование строки в нижний и верхний регистры

19. Форматирование строки

Этот код позволяет форматировать строку. Под форматированием в Python подразумевается присоединение к строке данных из переменных.

20. Поиск подстроки

Этот пример будет полезен для поиска подстроки в строке. Я реализую его двумя способами, позволяющими не писать много кода.

21. Печать в одной строке

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

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

Этот пример покажет, как разбить список на фрагменты и разделить его на меньшие части.

На правах рекламы

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

93+ Python Programming Examples

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:

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:

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:

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.

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:

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.

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:

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.

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.

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

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.

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.

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:

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.

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.

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:

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.

18. Delete an Element from a Python Dictionary

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

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.

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

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:

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

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:

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

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:

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

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.

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:

25. Calculate Simple Interest in Python

Simple Interest is calculated using the following formula:

SI = (P × R × T) / 100

  • 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:

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:

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:

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:

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:

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.

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.

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.

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.

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:

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:

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:

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:

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:

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:

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.

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:

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:

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.

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.

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:

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.

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:

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:

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:

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:

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:

Here is how the algorithm looks in code:

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:

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.

  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:

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.

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:

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:

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

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:

58. Parse the File Name from the Path

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

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.

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.

61. Check the File Size in Python

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

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:

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.

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:

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]:

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:

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”:

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:

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:

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:

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:

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:

72. Get Current Time in Python

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

  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:

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:

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:

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:

76. Generate a Textual Representation of an Object

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

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.

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:

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

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:

79. Capitalize a String

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

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:

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:

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.

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.

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:

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:

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:

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:

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.

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:

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:

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:

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:

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.

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

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:

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 of how to calculate the volume of a cube:

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 the code:

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.

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 the code:

99. Clone a Python List Independently

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

3. An Informal Introduction to Python¶

In the following examples, input and output are distinguished by the presence or absence of prompts ( >>> and … ): to repeat the example, you must type everything after the prompt, when the prompt appears; lines that do not begin with a prompt are output from the interpreter. Note that a secondary prompt on a line by itself in an example means you must type a blank line; this is used to end a multi-line command.

You can toggle the display of prompts and output by clicking on >>> in the upper-right corner of an example box. If you hide the prompts and output for an example, then you can easily copy and paste the input lines into your interpreter.

Many of the examples in this manual, even those entered at the interactive prompt, include comments. Comments in Python start with the hash character, # , and extend to the end of the physical line. A comment may appear at the start of a line or following whitespace or code, but not within a string literal. A hash character within a string literal is just a hash character. Since comments are to clarify code and are not interpreted by Python, they may be omitted when typing in examples.

3.1. Using Python as a Calculator¶

Let’s try some simple Python commands. Start the interpreter and wait for the primary prompt, >>> . (It shouldn’t take long.)

3.1.1. Numbers¶

The interpreter acts as a simple calculator: you can type an expression at it and it will write the value. Expression syntax is straightforward: the operators + , — , * and / work just like in most other languages (for example, Pascal or C); parentheses ( () ) can be used for grouping. For example:

The integer numbers (e.g. 2 , 4 , 20 ) have type int , the ones with a fractional part (e.g. 5.0 , 1.6 ) have type float . We will see more about numeric types later in the tutorial.

Division ( / ) always returns a float. To do floor division and get an integer result you can use the // operator; to calculate the remainder you can use % :

With Python, it is possible to use the ** operator to calculate powers 1:

The equal sign ( = ) is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:

If a variable is not “defined” (assigned a value), trying to use it will give you an error:

There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:

In interactive mode, the last printed expression is assigned to the variable _ . This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:

This variable should be treated as read-only by the user. Don’t explicitly assign a value to it — you would create an independent local variable with the same name masking the built-in variable with its magic behavior.

In addition to int and float , Python supports other types of numbers, such as Decimal and Fraction . Python also has built-in support for complex numbers , and uses the j or J suffix to indicate the imaginary part (e.g. 3+5j ).

3.1.2. Strings¶

Besides numbers, Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes ( ‘. ‘ ) or double quotes ( ". " ) with the same result 2. \ can be used to escape quotes:

In the interactive interpreter, the output string is enclosed in quotes and special characters are escaped with backslashes. While this might sometimes look different from the input (the enclosing quotes could change), the two strings are equivalent. The string is enclosed in double quotes if the string contains a single quote and no double quotes, otherwise it is enclosed in single quotes. The print() function produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters:

If you don’t want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote:

There is one subtle aspect to raw strings: a raw string may not end in an odd number of \ characters; see the FAQ entry for more information and workarounds.

String literals can span multiple lines. One way is using triple-quotes: """. """ or »’. »’ . End of lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of the line. The following example:

produces the following output (note that the initial newline is not included):

Strings can be concatenated (glued together) with the + operator, and repeated with * :

Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated.

This feature is particularly useful when you want to break long strings:

This only works with two literals though, not with variables or expressions:

If you want to concatenate variables or a variable and a literal, use + :

Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one:

Indices may also be negative numbers, to start counting from the right:

Note that since -0 is the same as 0, negative indices start from -1.

In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain substring:

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

Note how the start is always included, and the end always excluded. This makes sure that s[:i] + s[i:] is always equal to s :

One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:

The first row of numbers gives the position of the indices 0…6 in the string; the second row gives the corresponding negative indices. The slice from i to j consists of all characters between the edges labeled i and j, respectively.

For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. For example, the length of word[1:3] is 2.

Attempting to use an index that is too large will result in an error:

However, out of range slice indexes are handled gracefully when used for slicing:

Python strings cannot be changed — they are immutable . Therefore, assigning to an indexed position in the string results in an error:

If you need a different string, you should create a new one:

The built-in function len() returns the length of a string:

Strings are examples of sequence types, and support the common operations supported by such types.

Strings support a large number of methods for basic transformations and searching.

String literals that have embedded expressions.

Information about string formatting with str.format() .

The old formatting operations invoked when strings are the left operand of the % operator are described in more detail here.

3.1.3. Lists¶

Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type.

Like strings (and all other built-in sequence types), lists can be indexed and sliced:

All slice operations return a new list containing the requested elements. This means that the following slice returns a shallow copy of the list:

Lists also support operations like concatenation:

Unlike strings, which are immutable , lists are a mutable type, i.e. it is possible to change their content:

You can also add new items at the end of the list, by using the append() method (we will see more about methods later):

Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:

The built-in function len() also applies to lists:

It is possible to nest lists (create lists containing other lists), for example:

3.2. First Steps Towards Programming¶

Of course, we can use Python for more complicated tasks than adding two and two together. For instance, we can write an initial sub-sequence of the Fibonacci series as follows:

This example introduces several new features.

The first line contains a multiple assignment: the variables a and b simultaneously get the new values 0 and 1. On the last line this is used again, demonstrating that the expressions on the right-hand side are all evaluated first before any of the assignments take place. The right-hand side expressions are evaluated from the left to the right.

The while loop executes as long as the condition (here: a < 10 ) remains true. In Python, like in C, any non-zero integer value is true; zero is false. The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false. The test used in the example is a simple comparison. The standard comparison operators are written the same as in C: < (less than), > (greater than), == (equal to), <= (less than or equal to), >= (greater than or equal to) and != (not equal to).

The body of the loop is indented: indentation is Python’s way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. In practice you will prepare more complicated input for Python with a text editor; all decent text editors have an auto-indent facility. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (since the parser cannot guess when you have typed the last line). Note that each line within a basic block must be indented by the same amount.

The print() function writes the value of the argument(s) it is given. It differs from just writing the expression you want to write (as we did earlier in the calculator examples) in the way it handles multiple arguments, floating point quantities, and strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely, like this:

The keyword argument end can be used to avoid the newline after the output, or end the output with a different string:

Since ** has higher precedence than — , -3**2 will be interpreted as -(3**2) and thus result in -9 . To avoid this and get 9 , you can use (-3)**2 .

Unlike other languages, special characters such as \n have the same meaning with both single ( ‘. ‘ ) and double ( ". " ) quotes. The only difference between the two is that within single quotes you don’t need to escape " (but you have to escape \’ ) and vice versa.

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

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