# Learn how to program in Python with Examples

Contents

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

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

1 2 3 4 5 6 7 8 9 | #! / usr / bin / python3 sum = 0 for i in range (1, 1001): sum = sum + i print ('The sum is', sum) |

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.

1 2 3 4 5 6 7 8 9 | #! / usr / bin / python3 factorial = 1 for i in range (1, 41): factorial = factorial * i print ('The factorial of', i, 'is', factorial) |

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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | The factorial of 2 is 2 The factorial of 3 is 6 The factorial of 4 is 24 The factorial of 5 is 120 The factorial of 6 is 720 ... The factorial of 38 is 523022617466601111760007224100074291200000000 The factorial of 39 is 20397882081197443358640281739902897356800000000 The factorial of 40 is 815915283247897734345611269596115894272000000000 |

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:

1 2 3 4 5 6 7 8 9 10 11 12 13 | The factorial of 1 is 1.0 The factorial of 2 is 2.0 The factorial of 3 is 6.0 ... The factorial of 38 is 5.23022617466601 e +44 The factorial of 39 is 2.0397882081197442 e +46 The factorial of 40 is 8.159152832478977 e +47 |

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #! / usr / bin / python3 # Definition of the factorial function def factorial (n): if n <0: raise ValueError ('The function expects a positive number!') if not isinstance (n, int): raise ValueError ('The function expects an integer !!') if n == 0: return 1 else: result = 1 for i in range (2, n + 1): result * = i return result # Try the function test = 22 print ('The factorial of', test, 'is', factorial (test)) |

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:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | #! / usr / bin / python3 # Definition of a recursive factorial function def factorial (n): if n <0: raise ValueError ('Please enter a positive number!') if not isinstance (n, int): raise ValueError ('Please enter an integer!') if n == 0: return 1 else: return n * factorial (n -1) # Try the function test = 6 print ('The factorial of', test, 'is', faculty (test)) |

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

1 2 3 4 5 6 7 8 9 10 11 12 13 | #! / usr / bin / python3 tst = 'Did Tim never wear such light-colored trousers with a belt?' tmp = [characters. lower () for characters in tst if characters. isalpha ()] if tmp == tmp [:: -1]: print (tst, 'is a palindrome.') else: print (tst, 'is not a palindrome.') |