JustToThePoint English Website Version
JustToThePoint en español
JustToThePoint in Thai

Learn to program in Python

Introduction

Python is a simple, easy-to-understand, and minimalistic language. It is one of the easiest programming languages to learn because it has a clean and readable syntax that makes it easy for beginners to read and use. Besides, Python is free and open-source.

Python is an interpreted high-level general-purpose programming. It is used for web development, AI, machine learning, operating systems, mobile application development, and video games.

First steps

In case you do not want to (or cannot) install Python on your computer, you can execute Python programs using online tools, such as Python.org, replit (Python online editor), and Pythontutor.

Learn Python

Learn Python

Otherwise, open the terminal in your operating system and then open the Python prompt by typing python:

user@pc:~$ python
Python 3.9.5 (default, May 11 2021, 08:20:37) 
[GCC 10.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello World")
Hello World
>>> 3*5 # You can use Python as a powerful calculator. The operators +, -, * and / work just like in most other languages.
15
>>> 5**2 # 5 squared
25 # 5^2=25
>>> s = 'supercalifragilisticexpialidocious'
>>> len(s) # The built-in function len() returns the length of a string.
34
>>> import this! # Python has a really good sense of humour
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
>>> quit() # Use quit() or Ctrl-D (i.e. EOF) to exit

A first glimpse into the Python’s magic

>>> print("Hello World")
Hello World # print() displays messages and values onto the screen
>>> type("Hello World")
<class 'str'> # type() returns the value of the object, e.g., strings such as "Hello World" and "Goodbye" belong to the type str.
# Observe that this is just a comment

Python is the batteries-included language. Pint is a Python package to define, operate, and manipulate physical quantities. It allows arithmetic operations between them and conversions from and to different units.

>>> celsius = float(input("Enter temperature (in celsius): "))
Enter temperature (in celsius): 23
>>> fahrenheit = (celsius * 9/5) + 32
>>> print('%.2fºC  = %.2fºF' %(celsius, fahrenheit))
23.00ºC  = 73.40ºF
import random
DICE = {
    1: ("+--------+",
        "│        │",
        "│   O    │",
        "│        │",
        "+--------+",
    ),
    2: ("+---------+",
        "│  O      │",
        "│         │",
        "│      O  │",
        "+---------+",
    ),
    3: ("+---------+",
        "│ O       │",
        "│   O     │",
        "│     O   │",
        "+---------+",
    ),
    4: ("+---------+",
        "│  O   O  │",
        "│         │",
        "│  O   O  │",
        "+---------+",
    ),
    5: ("+---------+",
        "│  O   O  │",
        "│    O    │",
        "│  O   O  │",
        "+---------+",
    ),
    6: ("+---------+",
        "│  O   O  │",
        "│  O   O  │",
        "│  O   O  │",
        "+---------+",
    ),
}
min_value = 1
max_value = 6
dice_value = random.randint(min_value, max_value) # The randint() method returns a random integer value between min_value and max_value
print("The dice's value is: " + str(dice_value)) # str() constructs a string from our random integer "dice_value"
print("\n".join(DICE[dice_value]))
# The join() methods takes all items in an iterable (e.g. our dice's face, DICE[dice_value]) and joins them into one string with the \n separator.

The dice's value is: 2
+---------+
│  O      │
│         │
│      O  │
+---------+
>>> import math
>>> eval("math.pi * pow(7, 2)") 
# eval evaluates an expression. It calculates the area of a circle with a radius of 7 = Pi * r2
153.93804002589985
>>> eval("4/3 * math.pi * math.pow(7, 3)")
# It calculates the volume of a sphere with a radius of 7 = 4/3 * Pi * r3
1436.7550402417319
>>> from sympy import divisors # We need to import the SymPy library
>>> print(divisors(24)) # Return all divisors of n: [1, 2, 3, 4, 6, 8, 12, 24]
>>> user_input = input("Enter a phrase: ") # We need a sentence or phrase from the user. We will use Python's input() method for this task.
Enter a phrase: Keep smiling, because life is a beautiful thing and there is so much to smile about
>>> from nltk.corpus import stopwords
>>> from nltk.tokenize import word_tokenize
>>> nltk.download('stopwords')
# A stop word is a commonly used word, such as "a", "an", or "the" that does not contribute meaning to the phrase. It is typically ignored in a query because it gives no information and makes no contribution to the query.
>>> user_input_tokens = word_tokenize(user_input) # This a function that splits a given sentence into words using the NLTK library

Next, we need to separate each word and store it individually in a list, we also want to get rid or ignore words like ‘of’ from the user input. We can achieve these two goals by typing something like user_input_tokens = (user_input.replace(‘of’, ‘’)).split()

However, we can use Python’s NLTK library. It provides easy-to-use interfaces to over 50 corpora and lexical resources such as WordNet, along with a suite of text processing libraries for classification, tokenization, stemming, tagging, parsing, etc.

NLTK is an amazing library to get started with natural language. Read our article to write a python program to find the definition, synonyms, antonyms, and examples of a given word.

>>> print(user_input)
Keep smiling, because life is a beautiful thing and there is so much to smile about
>>> print(user_input_tokens)
['Keep', 'smiling', ',', 'because', 'life', 'is', 'a', 'beautiful', 'thing', 'and', 'there', 'is', 'so', 'much', 'to', 'smile', 'about']
user_input_without_sw = [word for word in user_input_tokens if not word in stopwords.words()]
# We iterate through all the words in the "user_input_tokens" list, check if the word is in the stop words collection, and if it is not there, then we will append or add it to the "user_input_without_sw" list.
>>> print(user_input_without_sw)
['Keep', 'smiling', ',', 'life', 'beautiful', 'smile']

We need to use the NLTK downloader to obtain some resources: import nltk, nltk.download(‘punkt’), and nltk.download(‘stopwords’).

>>> word = ""
>>> acronym = ""
>>> for word in user_input_without_sw: # Let's create a for loop which will iterate through our words list
...     if len(word)>1: # Let's get rid of all punctuation characters 
...             acronym = acronym + word[0].upper() # We are slicing off the first letter of every word, capitalizing it, and adding it to our acronym variable.
>>> print(f'The acronym of {user_input} is: {acronym}')
The acronym of Keep smiling, because life is a beautiful thing and there is so much to smile about is: KSLBS
>>> from pygorithm.sorting import bubble_sort 

Pygorithm is a fun way to learn algorithms on the go! We are going to import the bubble_sort algorithm (from pygorithm.sorting import bubble_sort). There are other sorting methods available, such as quick_sort, merge_sort, bubble_sort, etc.

>>> print(bubble_sort.get_code()) # It prints the code for the bubble sort algorithm.
def sort(_list):
    """
    Bubble Sorting algorithm

    :param _list: list of values to sort
    :return: sorted values
    """
    for i in range(len(_list)):
        for j in range(len(_list) - 1, i, -1):
            if _list[j] < _list[j - 1]:
                _list[j], _list[j - 1] = _list[j - 1], _list[j]
    return _list

>>> print(bubble_sort.time_complexities())
# bubble_sort.time_complexities() returns time complexities, i.e., Best Case, Average Case, and Worst Case.
Best Case: O(n), Average Case: O(n ^ 2), Worst Case: O(n ^ 2). 

For Improved Bubble Sort:
Best Case: O(n); Average Case: O(n * (n - 1) / 4); Worst Case: O(n ^ 2)
>>> myList = [3, 2, 1, 7, 8, 4, 5, 6, 9, 12, 22]
>>> print(bubble_sort.sort(myList)) # Let's sort the list.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 12, 22]
import random
import passwordmeter

It uses passwordmeter, a configurable, extensible password strength measuring library.

uppercase_letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lowercase_letters = uppercase_letters.lower()
digits = "0123456789"
symbols = "()[]{},;:.-_/\\?+*# "

Functions are reusable, self-contained pieces of code that can be called using a function’s name. They are the fundamental building block of any application in Python. They are key to writing clean modular code.

def secure_password():
    """ It generates a secure password with uppercase and lowercase letters, symbols, and numbers."""
	password = []
	for i in range(2):
		password.append(random.choice(uppercase_letters)) 
                # random.choice returns a random element of the specified sequence (uppercase letters), and we append it to our password, a list of characters.
		password.append(random.choice(lowercase_letters))
		password.append(random.choice(digits))
		password.append(random.choice(symbols))
		password.append(random.choice(uppercase_letters))
		password.append(random.choice(lowercase_letters))
	
	random.shuffle(password) # The shuffle() method takes a sequence, like a list, and reorganize, randomize, or shuffle the items of the list
	return "".join(password)
        # The join() methods takes all items in an iterable (e.g. our list "password") and joins them into one string

# It checks the security of our password.
def check_password(myPassword):
    strength, improvements = passwordmeter.test(myPassword) 
    # The main function provided by the passwordmeter package is the Meter.test() method. It returns a tuple of (float, dict).  
    print("It strength is: " + str(strength)) # The float is the strength of the password in the range 0 to 1, where 0 is extremely weak and 1 is extremely strong. 
    print("Its length is: " + str(len(myPassword)))
    print(improvements) # The second parameter is a dictionary of ways the password could be improved.

if __name__ == '__main__':
	myNewPassword = secure_password()
	print(myNewPassword)
	check_password(myNewPassword)

5N?Ge[jV6gJe
It strength is: 0.9404185412641389
Its length is: 12
{'phrase': 'Passphrases (e.g. an obfuscated sentence) are better than passwords'}
Bitcoin donation

JustToThePoint Copyright © 2011 - 2022 Anawim. ALL RIGHTS RESERVED. Bilingual e-books, articles, and videos to help your child and your entire family succeed, develop a healthy lifestyle, and have a lot of fun.

This website uses cookies to improve your navigation experience.
By continuing, you are consenting to our use of cookies, in accordance with our Cookies Policy and Website Terms and Conditions of use.