Skip to content

luizfernandopavanello/30-days-of-Python

Repository files navigation

🐍 30 Days Of Python

# Day Topics
01 Introduction
02 Variables, Built-in Functions
03 Operators
04 Strings
05 Lists
06 Tuples
07 Sets
08 Dictionaries
09 Conditionals
10 Loops
11 Functions
12 Modules
13 List Comprehension
14 Higher Order Functions
15 Python Type Errors
16 Python Date time
17 Exception Handling
18 Regular Expressions
19 File Handling
20 Python Package Manager
21 Classes and Objects
22 Web Scraping
23 Virtual Environment
24 Statistics
25 Pandas
26 Python web
27 Python with MongoDB
28 API
29 Building API
30 Conclusions

🐍🇺🇦🐍 HAPPY CODING 🐍🇺🇦🐍

30 Days Of Python: Day 1 - Introduction

Twitter Follow

Author: Fernando Vicentin Pavanello
First Edition: March, 2022

30 Days of Python

Welcome

Congratulations for deciding to participate in a 30 days of Python programming challenge . In this challenge you will learn everything you need to be a python programmer and the whole concept of programming.

Introduction

Python is a widely-used high-level programming language with dynamic semantics, used for general-purpose programming. It is an open source, interpreted, objected-oriented programming language. Python was created by a Dutch programmer born in 1956 in Haarlem, the Netherlands, Guido van Rossum. The name of Python programming language was derived from a British sketch comedy series, Month Python's Flying Circus.
The first version was released on February 20, 1991. The speed with which Python has spread around the world is a result of the continuous work of thousands (very often anonymous) programmers, testers, users (many of them aren't IT specialists) and enthusiasts, but it must be said that the very first idea (the seed from which Python sprouted) came to one head - Guido's.

This challenge is designed for beginners and professionals who want to learn python programming language. It may take 30 to 100 days to complete the challenge, people who actively participate on the telegram group have a high probability of completing the challenge.

Why should I learn Python?

It is a programming language which is very close to human language and because of that it is easy to learn and use.

It is omnipresent, people use numerous Python-powered devices on a daily basis, whether they realize it or not. There have been millions (well, actually billions) of lines of code written in Python, which means almost unlimited opportunities for code reuse and learning from well-crafted examples. What's more, there is a large and very active Python community, always happy to help.

There are also a couple of factors that make Python great for learning:

  • It is easy to learn - the time needed to learn Python is shorter than for many other languages; this means that it's possible to start the actual programming faster;
  • it's easy to teach - the teaching workload is smaller than that needed by other languages; this means that the teacher can put more emphasis on general (language-independent) programming techniques, not wasting energy on exotic tricks, strange exceptions and incomprehensible rules;
  • It is easy to use for writing new software - it's often possible to write code faster when using Python;
  • it's easy to understand - it's also often easier to understand someone else's code faster if it is written in Python;
  • It is easy to obtain, install and deploy - Python is free, open and multiplatform; not all languages can boast that.

Of course, Python has its drawbacks, too:

  • it's not a speed demon - Python does not deliver exceptional performance;
  • in some cases it may be resistant to some simpler testing techniques - this may mean that debugging Python's code can be more difficult than with other languages; fortunately, making mistakes is always harder in Python.

If you're not familiar with any other languages, Python is great to begin with, because it will give you a solid foundation and allow you to learn other programming languages (e.g., C++, Java, or C) much easier and much faster. Learning Python is fun and trendy!

I hope this is enough to convince you to start learning Python. Python is eating the world and you are killing it before it eats you.

What is Python actually used for?

Do you remember Battlefield 2, Battlefield 2142 and Battlefield Heroes - strategy and first person shooter games from EA DICE? All the games use Python for logic and server controls. Python is frequently used for creating open-source, free games, e.g., OpenRTS, PySol, Metin 2, or Frets On Fire - famous Guitar Hero-like games written in pygame.

And what about the major websites and services? Dropbox? UBER? Spotify? Pintrest? BuzzFeed? Yes. They were all written, to a greater or lesser extent, in Python. Other examples?

  • Internet Applications (BitTorrent, Jogger Publishing Assistant, TheCircle, TwistedMatrix)
  • 3D CAD/CAM (FreeCAD, Fandango, Blender, Vintech RCAM)
  • Enterprise Applications (Odoo, Tryton, Picalo, LinOTP 2, RESTx)
  • Image Applications (Gnofract 4D, Gogh, imgSeek, MayaVi, VPython)
  • Mobile Applications (Aarlogic C05/3, AppBackup, Pyroute)
  • Office Applications (calibre, faces, Notalon, pyspread)
  • Personal Information Managers (BitPim, Narval, Prioritise, Task Coach, WikidPad) [Source: https://wiki.python.org/moin/PythonProjects]

Generally, Python is a great choice for:

  • Web and Internet development (e.g., Django and Pyramid frameworks, Flask and Bottle micro-frameworks)
  • Scientific and numeric computing (e.g., SciPy - a collection of packages for the purposes of mathematics, science, and engineering; Ipython - an interactive shell that features editing and recording of work sessions)
  • Education (it's a brilliant language for teaching programming! And that's why we're offering this course to you!)
  • Desktop GUIs (e.g., wxWidgets, Kivy, Qt)
  • Software Development (build control, management, and testing - Scons, Buildbot, Apache Gump, Roundup, Trac)
  • Business applications (ERP and e-commerce systems - Odoo, Tryton) [Source: https://www.python.org/about/apps]

And many, many other projects and development tools.

Do I need any additional equipment for the course?

The course can be accessed online through any Internet browser, on computers with Linux, Windows, or Mac OS.

For the best learning experience, we recommend having the Python 3 standard installation on your computer. A copy of Python 3 can be downloaded from https://www.python.org/downloads. The installation contains a software application called IDLE (Integrated Development and Learning Environment), which will enable you to execute simple Python commands and see the effects of executing your programs.

Linux users most probably have Python already installed, as Python's infrastructure is intensively used by many Linux OS components.

Introduction to Python and computer programming

How does a computer program work?

Let's start the absolute basics... A makes a computer usable. Without a program, a computer, even the most powerful one, is nothing more than just an object. Similarly, without a player, a piano is nothing than a wooden box. Computers are able to perform very complex tasks, but this ability is not innate. A computer's nature is quite different, it can execute simple operations. For example, a computer cannot understand the value of a complicated mathematical function by itself, although this isn't beyond the realms of possibility in the near future. Contemporary computers can only evaluate the results of very fundamentals operations, like adding or dividing, but they can do it very fast, and can repeat these actions virtually any number of times. Imagine that you want to know the average speed you're reached during a long journey. You know the distance, you know the time, you need the speed. Naturally, the computer will be able to compute this, but the computer is not aware of such things as distance, speed, or time. Therefore, it is necessary to instruct the computer to:

  • accept a number representing the distance;
  • accept a number representing the travel time;
  • divide the former value by the latter and store the result in the memory;
  • display the result (representing the average speed) in a readable format.

These four simple actions form a program. Of course, these examples are not formalized, and they are very far from what the computer can understand, but they are good enough to be translated into a language the computer can accept.

Language is the keyword.

Natural languages vs. programming languages

A language is a means (and a tool) for expressing and recording thoughts. there are many languages all around us. Some of them require neither speaking nor writing, such as body language; it's possible to express yor deepest feelings very precisely without saying a word. Another language you use each day is your mother tongue, which you use to manifest your will and to ponder reality. Computers have their own language too, called machine language, which is very rudimentary. A computer, even the most technically sophisticated, is devoid of even a trace of intelligence. You could say it is like a well-trained dog - it responds only to a predetermined set of known commands. The commands it recognizes are very simple. We can imagine that the computer responds to orders like "take that number, divide by another and save the result". A complete set of known commands is called an 'Instruction List', sometimes abbreviated to 'IL'. Different types of computers may vary depending on the size of their ILs, and the instructions could be completely different in different models. No computer is currently capable of creating a new language. However, that may change soon. Just as people use a number of very different languages, machines have many different languages too. The difference, though, is that human languages developed naturally. moreover, they are still evolving, and new words are created every day as old words disappear. These languages are called 'natural languages'.

→ Note: Machine languages are develop by humans.

What makes a language?

We can say that each language (machine or natural, it doesn't matter) consists fo the following elements:

  • an alphabet: a set of symbols used to build words of a certain language (e.g. the Latin alphabet for English, the Cyrillic alphabet for Russian, Kanji for Japanese, and so on.);
  • a lexis: (aka dictionary) a set of words the language offers its users (e.g., the word "computer" comes from the English language dictionary, while "cmoptrue" doesn't; the word "chat" is present both in english and French dictionaries, but their meanings are different);
  • a syntax: a set of rules (formal or informal, written or felt intuitively) used to determine if a certain string of words forms a valid sentence (e.g., 'I am a python' is a syntactically correct phrase, while 'I a python am' doesn't);
  • semantics: a set of rules determining if a certain phrase makes sense (e.g, "I ate a doughnut" makes sense, but "A doughnut ate me" doesn't)

The IL is, in fact, the alphabet of a machine language. This is the simplest and most primary set of symbols we can use to give commands. It's the computer's mother tongue. Unfortunately, this tongue is a far cry from human mother tongue. We all (both computers and humans) need something else, a common language for computers and humans, or a bridge between the two different worlds. We need a language in which humans can write their programs and a language that computers may use to execute the programs, one that is far more complex than machine language and yet far simpler than natural language. Such languages are often called high-level programming language. They are at least somewhat similar to natural ones in that they use symbols, words and conventions readable to humans. These languages enable humans to express commands to computers that are much more complex than those offered by ILs. A program written in a high-level programming language is called a source code (in contrast to the machine code executed by computers). Similarly, the file containing the source code is called the source file.

Compilation vs. interpretation

Computer programming is the act of composing the selected programming language's elements in the order that will cause the desired effect. The effect could be different in every specific case - it's up to the programmer's imagination, knowledge and experience. Of course, such a composition has to be correct in many senses:

  • alphabetically: a program needs to be written in a recognizable script, such as Roman, Cyrillic, etc;
  • lexically: each programming language has it dictionary and you need to master it; thankfully, it's much simpler and smaller than the dictionary of any natural language;
  • syntactically: each language has its rules and they must be obeyed;
  • semantically: the program has to make sense.

Unfortunately, a programmer can also make mistakes with each of the above four senses. Each of then can cause the program to become completely useless.

Let's assume that you've successfully written a program. How do we persuade the computer to execute it? You have to render your program into machine language. Luckily, the translation can be done by a computer itself, making the whole process fast and efficient. There are two different ways of transforming a program from a high-level programming language into machine language:

  • COMPILATION: the source program is translated once (however, this act must be repeated each time you modify the source code) by getting a file (e.g., an .exe file if the code is intended to be run under MS Windows) containing the machine code: now you can distribute the file worldwide; the program that performs this translation is called a compiler os translator;
  • INTERPRETATION: you (or any user of the code) can translate the source program each time it has to be run; the program performing this kind of transformation is called an interpreter, as it interprets the code every time it is intended to be executed; it also means that you cannot just distribute the source code as-is, because the end-user also needs the interpreter to execute it.

Due to some very fundamental reasons, a particular high-level programming language is designed to fall into one of these two categories. There are very few languages that can be both compiled and interpreted. Usually, a programming language is projected with this factor in its constructors'minds - will it be compiled or interpreted?

What does the interpreter actually do?

Let's assume once more that you have written a program. Now, it exists as a computer file: a computer program is actually a piece of text, so the source code is usually placed in text files.

→ Note: it has to be pure text, without any decorations like different fonts, color, embedded images or other media. Now you have to invoke the interpreter and let it read your source file.

The interpreter reads the source code in a way that is common in Western culture: from top to bottom and from left to right. These are some exceptions. First of all, the interpreter checks if all subsequent lines are correct (using the four aspects covered earlier). If the compiler finds an error, it finishes its work immediately. The only result in this case is an error message. The interpreter will inform you where the error is located and what caused it. However, these messages may be misleading, as the interpreter isn't able to follow your exact intentions, and may detect errors at some distance from their real causes. For example, if you try to use an entity of an unknown name, it will cause an error, but the error will be discovered in the place where it tries to use the entity, not where the new entity's name was introduced. If the line looks good, the interpreter tries to execute it (note: each line is usually executed separately, so the trio "read-check-execute" can repeated many times - more times than the actual number of lines in the source file, as some parts of the code may be executed more than once). It is also possible that a significant part of the code may be executed successfully before the interpreter finds an error. This is normal behavior in this execution model. You may ask now: which is better? The "compiling" model or the "interpreting" model? There is no obvious answer. If there had been, one of these models would have ceased to exist a long time ago. Both of them have their advantages and their disadvantages.

Compilation vs. interpretation - advantages and disadvantages

  • ADVANTAGES:

    • COMPILATION:

      • the execution of the translates code is usually faster;
      • only the user has to have the compiler - the end-user may use the code without it;
      • the translated code is stored using machine language - as it is very hard to understand it, your own inventions and programming tricks are likely to remain your secret.
    • INTERPRETATION:

      • you can run the code as soon as you complete it - there are no additional phases of translation;
      • the code is stored using programming language, not the machine one - this means that it can be run on computers using different machine language; you don't compile your code separately for each different architecture.
  • DISADVANTAGES:

    • COMPILATION:

      • the compilation itself may be a very time-consuming process - you may not be able to run your code immediately after any amendment;
      • you have to have as many compilers as hardware platforms you want your code to be run on.
    • INTERPRETATION:

      • don't expect that interpretation will ramp your code to high speed - your code will share the computer's power with the interpreter, so it can't be really fast;
      • both you and the end user have to have the interpreter to run your code.

→ What does this all mean for you?

  • Python is an interpreted language. This means that is inherits all the described advantages and disadvantages. Of course, it adds some of its unique features to both sets;
  • If you want to program in python, you'll need the Python interpreter. You won't be able to run your code without it. Fortunately, Python is free. This is one of its most important advantages.

Due to historical reasons, languages designed to be utilized in the interpretation manner are often called scripting languages, while the source programs encoded using them are called scripts.

A hobby programming project

The circumstances in which Python was created are a bit puzzling. According to Guido van Rossum:

"In December 1989, I was looking for a "hobby" programming project that would keep me occupied during the week around Christmas. My office (...) would be closed, but I had a home computer, and not much else on my hands. I decided to write an interpreter for the new scripting language I had been thinking about lately: a descendant of ABC that would appeal to Unix/C hackers. I chose Python as a working title for the project, being in a slightly irreverent mood (and a big fan of Monty Python's Flying Circus). -- Guido van Rossum"

Python goals

In 1999, Guido van Rossum, defined his goals for Python:

  • an easy and intuitive language just as powerful as those of the major competitors;
  • open source, so anyone can contribute to its development:
  • code that is as understandable as plain English;
  • suitable for everyday tasks, allowing for short development times.

About 20 years later, it is clear that all these intentions have been fulfilled. Some sources say that Python is the most popular programming language in the world, while others claim it's the second or the third.

Python isn't a young language anymore. It is mature and trustworthy. It's not a one-hit wonder. It's a bright star in the programming firmament, and time spent learning Python is a very good investment.

Python rivals?

Python has two direct competitors, with comparable properties and predispositions. These are:

  • Perl - a scripting language originally authored by Larry Wall;
  • Ruby - a scripting language originally authored by Yukihiro Matsumoto.

The former is more traditional, more conservative than Python, and resembles some of the good old languages derived from the classic C programming language.

In contrast, the latter is more innovative and more full of fresh ideas than Python. Python itself lies somewhere between these two creations.

The Internet is full of forums with infinite discussions on the superiority of one of these three over the others, should you wish to learn more about each of them.

Where can we see Python in action?

We see it every day and almost everywhere. It's used extensively to implement complex Internet services like search engines, cloud storage and tools, social media and so on. Whenever you use any of these services, you are actually very close to Python, although you wouldn't know it.

Many developing tools are implemented in Python. More and more everyday use applications are being written in Python. Lots of scientists have abandoned expensive proprietary tools and switched to Python. Lots of IT project testers have started using Python to carry out repeatable test procedures. The list is long.

Why not Python?

Despite Python's growing popularity, there are still some niches where Python is absent, or is rarely seen:

  • low-level programming (sometimes called "close to metal" programming): if you want to implement an extremely effective driver or graphical engine, you wouldn't use Python;
  • applications for mobile devices: although this territory is still waiting to be conquered by Python, it will most likely happen someday.

Basic Python

Hello, World!

It's time to start writing some real, working Python code. It'll be very simple for the time being.

Python Sintax

A Python script can be written in Python interactive shell or in the code editor. A Python file has an extension ".py".

Python Indentation

An indentation is a white space in a text. Indentation in many languages is used to increase code readability, however Python uses indentation to create block of codes. In other programming languages curly brackets are used to create blocks of codes instead od indentation. One of the common bugs when writing python code is wrong indentation.

Comments

Comments are very important to make the code more readable and to leave remarks in our code. Python does not run comment parts of our code.Any text starting with hash(#) in Python is a comment.

Example: Single Line Comment

    # This is the first comment
    # This is the second comment
    # Python is eating the world

Example: Multiple Comment

Triple quote can be used for multiple comment if it is not assigned to a variable

"""This is multiline comment
multiline comment takes multiple lines.
python is eating the world
"""

Data types

In Python there are several types of data types. Let get started with the most commom ones. Different data types will be covered in detail in other sections. For the time being, let just go through the different data types and get familiar with them.

Number

  • Integer: Integer(negative, zero and positive) numbers Example: ... -3, -2, -1, 0, 1, 2, 3 ...
  • Float: Decimal numbers Example: -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5
  • Complex: Example 1 + j, 2 + 4j

String

A collection of one or more characters under a single or double quote. If a string is more than one sentence then we use a triple quote.

Example:

'Case'
'Chiba City'
"Python"
"I love teaching"
'I hope you are enjoying the first day of 30DaysOfPython Challenge'

Booleans

A boolean data type is either a True or False value. T and F should be always uppercase.

Example:

    True  #  Is the light on? If it is on, then the value is True
    False # Is the light on? If it is off, then the value is False

List

Python list is an ordered collection which allows to store different data type items, using []. A list is similar to an array.

Example:

[0, 1, 2, 3, 4, 5]  # all are the same data types - a list of numbers
['Banana', 'Orange', 'Mango', 'Avocado'] # all the same data types - a list of strings (fruits)
['Finland','Estonia', 'Sweden','Norway'] # all the same data types - a list of strings (countries)
['Banana', 10, False, 9.81] # different data types in the list - string, integer, boolean and float

Dictionary

A Python dictionary object is an unordered collection of data in a key value pair format, using {}.

Example:

{
'first_name':'Case',
'last_name':'Sprawl',
'country':'Chiba City', 
'age':99, 
'is_married':False,
'skills':['Python', 'Linux', 'ETH']
}

Tuple

A tuple is an ordered collection of different data types like list, but tuples cannot be modified once they are created. They are immutable.

Example:

('Case', 'Sprawl', 'Gibson', 'William', 'Molly') # Names
('Earth', 'Jupiter', 'Neptune', 'Mars', 'Venus', 'Saturn', 'Uranus', 'Mercury') # planets

Set

A set is a collection of data types similar to list and tuple. Unlike them, a set is not an ordered collection of items. Like in Mathematics, set in Python stores only unique items.

Example:

{2, 4, 3, 5}
{3.14, 9.81, 2.7} # order is not important in set

Checking Data types

To check the data type of certain data/variable we use the type function.

Python File

First open your project folder, inside this folder, create a file called "helloworld.py". To see our results, we should use a built in function print(). The print() built-in function takes one or more arguments as follows print('argument1', 'argument2', 'argument3'). See the examples below.

Example:

The file name is helloworld.py

# Day 1 - 30DaysOfPython Challenge

print(2 + 3)             # addition(+)
print(3 - 1)             # subtraction(-)
print(2 * 3)             # multiplication(*)
print(3 / 2)             # division(/)
print(3 ** 2)            # exponential(**)
print(3 % 2)             # modulus(%)
print(3 // 2)            # Floor division operator(//)

# Checking data types
print(type(10))          # Int
print(type(3.14))        # Float
print(type(1 + 3j))      # Complex number
print(type('Case'))  # String
print(type([1, 2, 3]))   # List
print(type({'name':'Case'})) # Dictionary
print(type({9.8, 3.14, 2.7}))    # Set
print(type((9.8, 3.14, 2.7)))    # Tuple

Day 2 >>

About

30 days of Python programming challenge is a step-by-step guide to learn the Python programming language in 30 days.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages