Learn how to program in Python with Examples

(Last Updated On: April 2, 2021)

Learn to program in Python:

Learn to Program in Python- This section is intended to help you with three specific programming tasks help to get on the road to success as quickly as possible. The examples have nothing to do with the Raspberry Pi and can be implemented immediately without any tinkering. They only serve to help you with simple tasks to become independent to lead programming. So, the basic purpose of this article is to help you understand how to program in Python.

Amazon Purchase Links:

Top Gaming Computers

Best Laptops

Best Graphic Cards

Portable Hard Drives

Best Keyboards

Best High Quality PC Mic

Computer Accessories

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

Example 1: calculate the sum of the numbers from 1 to 1000

Do you know how much 1 + 2 + 3 +. . . + 999 + 1000 is? No? There’s a great math Formula with which you can quickly calculate this sum – but we want to program, right? To calculate the total, we need two things from a programming point of view: one Variable in which we store the sum and a loop from 1 to 1000 in which we add each of these numbers to the sum variable. The required Python code

looks like:

Briefly, there are three pitfalls or in simple words three problems:

  • You have to initialize the variable sum with 0. If you have the line sum = 0 omit, Python cannot do sum = sum + i. It’s a little misleading. The error message is name ‘sum’ not defined. What is actually meant is that the content of sum is read out before the variable with a start value was occupied.
  • range (1, 1000) might be more obvious, but it is wrong. With range the first parameter the start value (inclusive), the second the end value (exclusive!).So that the loop runs from 1 to 1000, the end value must be 1001!
  • Note the syntax rules for loops: After for you must have a colon and all commands executed by the loop multiple times must be indented. This does not apply to the print statement the result should only be displayed once after the end of the loop. If you also indent print, all 1000 intermediate results are displayed.


Example 2:  Calculate the factorials of 1! Up to 40!

In mathematics, the factorial function of an integer is n as the product of all numbers defined from 1 to n. The factorial of 6 results from 1 * 2 * 3 * 4 * 5 * 6. Python has no predefined function for calculating the factorial. Especially does the notation i known from mathematics work! Not. You need to so take the calculation into your own hands.

The simplest solution looks very similar to the previous sum example: A variable – we will simply call it a factorial  here – becomes its turn in a loop after multiplied by the numbers from 1 to 40. This time every intermediate result issued, d. that is, the print statement is in the loop (i.e., indented), not outside.

The result is remarkable. Apparently, Python calculates arbitrarily precisely:



In fact, this only applies to whole numbers. If the range of numbers is 32 or 64-bit integers is exceeded, Python automatically changes to a number representation with any number of digits. Calculations performed with it are but then much slower. If you look in the second Line use the initialization factorial  = 1.0, then use Python for all Calculations floating point numbers. Their accuracy is limited to 16 digits. The result looks like this:

Should you need the factorial function more often in your program (that is unlikely, but let’s assume it for didactic reasons), then it would be useful to wrap the code in a function. Do you have an idea, how could you proceed? The function should of course be as good as possible against operating errors, thus protected against the transfer of impermissible parameters. In solution variant 1, the code looks very similar to the example above, that is, the calculation is done in a loop. First are three special cases checked: An error is triggered for negative or non-integer numbers, and for parameter 0, according to the mathematical definition for the factorial function the result 1 is returned. Otherwise, the factorial  is calculated in a loop.


If you search for Python factorial on the internet, you will get a lot more recursive Encounter possible solutions. That has to do with the fact that the factorial function well suited to demonstrate the principle of recursion. Speak of recursion man, when a function calls itself. The following lines show how the factorial can be calculated recursively:

At first glance you can see that the code has become a little shorter. Instead of calculating the factorial in a loop, the statement return n applies * factorial (n-1) itself back to the factorial function – but this time with the parameter n-1. When you go to faculty (40), it comes behind the scenes to 39 other calls, i.e. factorial (39), factorial (38) etc. Please note that the recursive approach here involves less typing, but also with a poorer performance. Recursive algorithms can often be used formulate compact and elegant, but they do not always represent the best resp. fastest solution to a problem!


Example 3: Palindrome test Program in Python

A palindrome is a word or phrase that reads the same thing backwards and forwards results. Spaces and punctuation are not taken into account. So are Otto or did Tim never wear such light-colored trousers with a belt? both palindromes.

The goal of our mini-program is now to determine for a string whether it is or not it is a palindrome. The solution to this problem is downright astonishing: When assigning tmp, the so-called List Comprehension is used: for characters in tst forms a Loop across all signs. if characters.isalpha () causes the loop to only contain letters processed and skips the remaining characters. From the test string it becomes the following list:

[‘t’, ‘r’, ‘u’, ‘g’, ‘t’, ‘i’, ‘m’, ‘e’, ​​’i’, ‘n’, ‘e’,

‘s’, ‘o’, ‘h’, ‘e’, ​​’l’, ‘l’, ‘e’, ​​’h’, ‘o’, ‘s’, ‘e’,

‘n’, ‘i’, ‘e’, ​​’m’, ‘i’, ‘t’, ‘g’, ‘u’, ‘r’, ‘t’]

Now all that remains to be tested is whether these letters are in reverse order result in the same. To do this, the order is reversed with tmp [:: – 1].

 

Recommended For You

About the Author: Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply