What is Python

What is Python

Website: https://ks-industries.tech/

INTRODUCTION TO PYTHON

Python is a high-level programming language which was designed by Guido van Rossum and it was released in February 1991. Python has multiple features; it is functionalobject oriented, structuredproceduralreflective, etc. It helps programmers to write logical codes for all types of projects.


It is a dynamically typed language, which means it will execute most usual programming behaviours at runtime that static programming languages execute during compilation. It is also garbage collected. Garbage collection simply means memory management; it reuses the memory that is no longer referenced. It has a comprehensive standard library.

Python can be used for machine learning, web development, AI, etc.

HISTORY OF PYTHON

Guido Van Rossum of the Centrum Wiskunde Informatica (CWI) in the Netherlands invented Python in the 1980s. It was a direct successor of the SETL-inspired ABC programming language. The entire procedure began in December of 1989. Python’s initial version was published in 1991.From then newer versions of the language were kept in motion with better features.

Some of the major releases are

Python 2.0 – launch date: 16.10.2002

Python 3.0 – launch date: 03.12.2008 (major revision)

Python 2.7.13 – launch date: 17.12.2016

Python 3.5.3 – launch date: 17.01.2017

Python 3.6.10- launch date: 18.12.2019

Python 3.8.2- launch date: 29.02.2020

Python 3.9.5- launch date: 03.05.2021

After the major revision in 2008, which was not backward compatible, many of its versions were backported to 2.6x and 2.7x. The 2.7x version was initially supposed to expire in the year 2015 but was continued till 2020 since there were a number of concerns dealing with forwarding porting of large codes. It’s quality in terms of security hasn’t improved. On 12th July 2018, Van Rossum retired from his position as the director of Python. In Jan 2019 a team of 5 core developers was formed, to run the organization.

In 2021 the members are Pablo Galindo Salgado, Thomas Wouters, Brett Cannon, Carol Willing and Barry Warsaw. As of now, only the versions after 3.6x are working. The versions 3.9.2 and 3.8.8 had to be hastened due to the lack of security in the earlier versions.

 


SPECIALITY OF PYTHON

  •  It has simple, less-cluttered syntax, therefore, making it easy to use. Anybody can learn basic python coding within 6-8 weeks
  •    It is free and open-source. It’s easy to find on the website, and anyone can download it and begin coding right away.
  •   It is easily portable, therefore any code can be created on any operating system and will run smoothly on any OS.
  •    It is an interpreted language conceding it to execute the code directly
  •     It is a multi-paradigm language, which means it uses more than one paradigm to make coding smooth.
  •    It is object-oriented. It deals with ‘objects’ that store data in the form of fields and code in the form of procedures.
  • It is a structured programming language. It uses structured flow constructs in the form of selection(if/then/else) and repetition(while/for) to make the quality of data clear.
  •  It is a functional programming language. It applies and composes functions. It develops a set of expressions that adds value to other values.
  •    It is an aspect-oriented programming language, which allows it to increase its modularity. It does this in a way that the code can be run in more than one way without modifying the code itself.
  •    It also includes metaprogramming which means it has the ability to use other programs as its data. It allows you to build a program that can read, transfer, generate or can modify itself while running.
  •  It includes meta objects. It is an object created to deal with a pre-existing object.
  •    Different paradigms are supported by design contract; basically, it should follow specific components which helps in extending the functionality of the code and logic programming; it is written in a logical format with rules.
  •   Dynamic typing: It checks the safety of the programming while running
  • It also uses reference counting, it’s the process of storing a number of references, pointers etc.
  •     It uses garbage collection to exercise its memory effectively.
  •      It contains dynamic name resolution, in simple words, it has resolutions in tokens of program expressions for programming components
  •   The standard library helps in implementing functional tools. Its two modules include – itertools and functools
  •  It is designed to be highly extensible making it last longer. As it leads to extending the use of the program whilst keeping the effort put in the implementation of the extension limited.
  •      It has a graphical user interface (GUI) 
  •    It avoids premature optimization.

USAGE OF PYTHON

  •  WEB DEVELOPMENT- Codes written in Python are readable and one can use English keywords rather than punctuations. This makes maintaining and updating the software effortlessly and timelessly. It also has many web development frameworks; DjangoPyramid and Flask. They have been used to create some well-known sites such as SpotifyReddit and Mozill. It is due to the extensive libraries that make access and management of huge data easy.        
  •     AI AND MACHINE-  Since Python is such a simple, easy to use language it is best used for artificial intelligence and machine learning projects. Thus, it’s also the favourite language among data scientists. A few examples of Python AI projects are- Tensor FlowKerasTheano, etc.
  •     DATA ANALYTICS-Another field that uses Python voluminously is Data analytics. In the times that we live in a lot of data has been created on a daily basis, therefore, developing an even greater need for a program that makes sense out of the data collected so that it can be put to better use. Python is flexible and well-structured makes analysis easy.
  •     DATA VISUALISATION- Data visualisation is the process of developing a graphical representation of data collected. It uses various tools such as charts, graphs, maps, dashboards, etc. As mentioned above, being in a data-driven world makes this process extremely useful. Python containing graphic libraries amongst all of its features helps in the visualisation of data. Plotly is one of the many graphic libraries.
  •     PROGRAMMING APPS- One can program any kind of app using Python. Gaming, Business, Educational, etc, all can be developed in Python
  •     GAME DEVELOPMENT- Python has its uses in the game development industry, despite the fact that it is far from becoming an industry standard. The computer language may be used to create simple games, making it a valuable tool for quickly developing a prototype.
  •     LANGUAGE DEVELOPMENT- Python’s simple and elegant architecture, as well as its syntax, has sparked the development of new programming languages. Python has a syntax that is comparable to those of CobraCoffeeScript, and Go. If you’re new to programming, knowing Python will make it easier for you to expand out into other fields.
  •     FINANCE- Python is becoming more popular in the financial sector, particularly in areas like the quantitative and qualitative analysis. It can be useful for predicting asset price trends and automating operations across many data sources, as well as identifying asset price patterns and forecasts. Python, as previously said, is an excellent tool for working with large data sets, and there are several modules to aid with data compilation and processing. As a result, it’s one of the finance industry’s most popular languages.
  •     SEO- The field of search engine optimization is another surprising Python application on our list (SEO). It’s a field that frequently benefits from automation, which Python makes possible. Python can assist in implementing modifications across several pages or categorising keywords. Natural language processing (NLP) and other emerging technologies are likely to be important to SEO professionals.SEO experts are likely to be interested in natural language processing (NLP) and other new technologies.

SOME PYTHON PROJECTS

1) MADLIPS-

It is a great start for software development as it is basic and has various elements. Mad Libs Generator explains how to modify user-inputted data, with Mad Libs referring to a set of inputs entered by the user. An adjective, a pronoun, or even a verb might be used as the user’s input. The application will run once all of the inputs have been submitted.

loop = 1
while (loop < 10):
    noun = input("Select a noun: ")
    p_noun = input("Select a plural noun: ")
    noun2 = input("Select a noun: ")
    place = input("Give a place: ")
    adjective = input("Select an adjective (Describing word): ")
    noun3 = input("Select a noun: ")
// Displays the story 
    print ("-------------------------")
    print ("Be nice to your",noun,"- footed", p_noun)
    print ("For a duck could be someone's", noun2,",")
    print ("Be loving to your",p_noun,"while",place)
    print ("Where the weather is always",adjective,".")
    print ("You may think that is this the",noun3,",")
    print ("Well it is.")
    print ("-----------------------------")
    loop = loop + 1
// Source code from stackoverflow

COPY

2) NUMBER GUESSING-

The code creates a random number between 1 and 10, or 1 and 100, or any range chosen by the user, and the user must guess the number after the computer gives a clue. When a user’s estimate is incorrect, they are given extra suggestions to help them guess the number, but at the cost of lowering their score.


Any arithmetic hint, such as multiples, divisible, bigger or smaller, or a mix of these, can be used as a clue. The software also requires methods to determine whether or not the user has provided a real number, to evaluate the input number to the actual number, and to calculate the difference between the two values.

import random
attempts_list = []
def show_score():
    if len(attempts_list) <= 0:
        print("No high score presently, go ahead and create one!")
    else:
        print("High score is {} attempts".format(min(attempts_list)))
def start_game():
    random_number = int(random.randint(1, 10))
    print("HELLO! Welcome !")
    player_name = input("ENTER NAME ")
    wanna_play = input("Hi, {}, let’s begin (Enter Yes/No) ".format(player_name))
    // Where the show_score function USED to be
    attempts = 0
    show_score()
    while wanna_play.lower() == "yes":
        try:
            guess = input("Select a number between 1 and 10 ")
            if int(guess) < 1 or int(guess) > 10:
                raise ValueError("Please guess a number within the given range")
            if int(guess) == random_number:
                print("PERFECT! You got it!")
                attempts += 1
                attempts_list.append(attempts)
                print("You took {} attempts".format(attempts))
                play_again = input("Play again (Enter Yes/No) ")
                attempts = 0
                show_score()
                random_number = int(random.randint(1, 10))
                if play_again.lower() == "no":
                    print("Have a nice day”)
                    break
            elif int(guess) > random_number:
                print("It's lower")
                attempts += 1
            elif int(guess) < random_number:
                print("It's higher")
                attempts += 1
        except ValueError as err:
            print(" not a valid value. Try again...")
            print("({})".format(err))
    else:
        print("That's cool, have a good one!")
if __name__ == '__main__':
    start_game()

COPY

3) ROCK, PAPER, SCISSORS-

This program, which is a mini-game, is meant for when you don’t have someone to play with. The programme needs the user to make the initial move. The input, which might be a string or an alphabet, is assessed once the move is validated. The result function determines a winner after analysing the input text, while the scorekeeper function updates the round’s score.


import random
import os
import re
os.system('cls' if os.name=='nt' else 'clear')
while (1 < 2):
    print "\n"
    print "Rock, Paper, Scissors - Shoot!"
    userChoice = raw_input("Choose your weapon [R]ock], [P]aper, or [S]cissors: ")
    if not re.match("[SsRrPp]", userChoice):
        print "Please choose a letter:"
        print "[R]ock, [S]cissors or [P]aper."
        continue
    // Echo the user's choice
    print "You chose: " + userChoice
    choices = ['R', 'P', 'S']
    opponenetChoice = random.choice(choices)
    print "I chose: " + opponenetChoice
    if opponenetChoice == str.upper(userChoice):
        print "Tie! "
    #if opponenetChoice == str("R") and str.upper(userChoice) == "P"
    elif opponenetChoice == 'R' and userChoice.upper() == 'S':      
        print "Scissors beats rock, I win! "
        continue
    elif opponenetChoice == 'S' and userChoice.upper() == 'P':      
        print "Scissors beats paper! I win! "
        continue
    elif opponenetChoice == 'P' and userChoice.upper() == 'R':      
        print "Paper beat rock, I win! "
        continue
    else: 
       print ("You win!" )     

COPY

4) WEBSITE BLOCKER-

We are all aware that while surfing the internet, a slew of undesirable websites shows up to divert our attention. This project comes in handy in such situations since it can be set up to prevent particular websites from loading. People who are easily distracted and go to social networking sites while working on anything serious would benefit from the software.

import time
from datetime import datetime as dt
hosts_path = r"/etc/hosts"   // r is for raw string
hosts_temp = "hosts"
redirect = "127.0.0.1"
web_sites_list = ["www.facebook.com", "facebook.com"]    // users can modify the list of the websites they want to block
while True:
   if dt(dt.now().year, dt.now().month, dt.now().day, 9) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day,22):
       print("Working hours")
       with open(hosts_path, "r+") as file:
           content = file.read()
           for website in web_sites_list:
               if website in content:
                   pass
               else:
                   file.write(redirect+" "+website+"\n")
   else:
       print("Fun time")
       with open(hosts_path, "r+") as file:
           content = file.readlines()
           file.seek(0)
           for line in content:
              
               if not any(website in line for website in web_sites_list):
                   file.write(line)
              
           file.truncate()
time.sleep(5)

COPY

5) ALARM CLOCK-

For an intermediate Python developer, this is an intriguing Command Line Interface (CLI) Python application. Alarm clock features are used by people all around the world, however this project may be tweaked in a new way. Certain YouTube URLs may be uploaded to a text file, and the project is created such that when a user sets an alarm, the code will randomly select a link from the video and begin playing it.


import datetime
import os
import time
import random
import webbrowser
if not os.path.isfile("youtube_alarm_videos.txt"):
    print('Creating "youtube_alarm_videos.txt"...')
    with open("youtube_alarm_videos.txt", "w") as alarm_file:
        alarm_file.write("https://www.youtube.com/watch?v=anM6uIZvx74")
def check_alarm_input(alarm_time):
    """Checks to see if the user has entered in a valid alarm time"""
    if len(alarm_time) == 1: // [Hour] Format
        if alarm_time[0] < 24 and alarm_time[0] >= 0:
            return True
    if len(alarm_time) == 2: // [Hour:Minute] Format
        if alarm_time[0] < 24 and alarm_time[0] >= 0 and \
           alarm_time[1] < 60 and alarm_time[1] >= 0:
            return True
    elif len(alarm_time) == 3: // [Hour:Minute:Second] Format
        if alarm_time[0] < 24 and alarm_time[0] >= 0 and \
           alarm_time[1] < 60 and alarm_time[1] >= 0 and \
           alarm_time[2] < 60 and alarm_time[2] >= 0:
            return True
    return False
print("Set a time for the alarm (Ex. 06:30 or 18:30:00)")
while True:
    alarm_input = input(">> ")
    try:
        alarm_time = [int(n) for n in alarm_input.split(":")]
        if check_alarm_input(alarm_time):
            break
        else:
            raise ValueError
    except ValueError:
        print("ERROR: Enter time in HH:MM or HH:MM:SS format")
seconds_hms = [3600, 60, 1]
alarm_seconds = sum([a*b for a,b in zip(seconds_hms[:len(alarm_time)], alarm_time)])
now = datetime.datetime.now()
current_time_seconds = sum([a*b for a,b in zip(seconds_hms, [now.hour, now.minute, now.second])])
time_diff_seconds = alarm_seconds - current_time_seconds
if time_diff_seconds < 0:
    time_diff_seconds += 86400 
print("Alarm set to go off in %s" % datetime.timedelta(seconds=time_diff_seconds))
// Sleep until the alarm goes off
time.sleep(time_diff_seconds)
print("Wake Up!")
with open("youtube_alarm_videos.txt", "r") as alarm_file:
    videos = alarm_file.readlines()
webbrowser.open(random.choice(videos))


COPY

6) TIC TAC TOE-


A nine-square grid is used in this two-player game. At each opportunity, each player picks their move and marks their square one with O or X. The player who makes all of their marks in a straight line, whether diagonally, horizontally, or vertically, wins. The opposing player’s challenge is to both stop their opponent’s game and build their own chain. This can be built by using the Pygame Python library as it is filled with graphics and sounds.

import random
import sys
board=[i for i in range(0,9)]
player, computer = '',''
moves=((1,7,3,9),(5,),(2,4,6,8))
winners=((0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6))
tab=range(1,10)
def print_board():
    x=1
    for i in board:
        end = ' | '
        if x%3 == 0:
            end = ' \n'
            if i != 1: end+='---------\n';
        char=' '
        if i in ('X','O'): char=i;
        x+=1
        print(char,end=end)
def select_char():
    chars=('X','O')
    if random.randint(0,1) == 0:
        return chars[::-1]
    return chars
def can_move(brd, player, move):
    if move in tab and brd[move-1] == move-1:
        return True
    return False
def can_win(brd, player, move):
    places=[]
    x=0
    for i in brd:
        if i == player: places.append(x);
        x+=1
    win=True
    for tup in winners:
        win=True
        for ix in tup:
            if brd[ix] != player:
                win=False
                break
        if win == True:
            break
    return win
def make_move(brd, player, move, undo=False):
    if can_move(brd, player, move):
        brd[move-1] = player
        win=can_win(brd, player, move)
        if undo:
            brd[move-1] = move-1
        return (True, win)
    return (False, False)
def computer_move():
    move=-1
       for i in range(1,10):
        if make_move(board, computer, i, True)[1]:
            move=i
            break
    if move == -1:
        for i in range(1,10):
            if make_move(board, player, i, True)[1]:
                move=i
                break
    if move == -1:
        // Otherwise, try to take one of desired places.
        for tup in moves:
            for mv in tup:
                if move == -1 and can_move(board, computer, mv):
                    move=mv
                    break
    return make_move(board, computer, move)
def space_exist():
    return board.count('X') + board.count('O') != 9
player, computer = select_char()
print('Player is [%s] and computer is [%s]' % (player, computer))
result='%%% Deuce ! %%%'
while space_exist():
    print_board()
    print('#Make your move ! [1-9] : ', end='')
    move = int(input())
    moved, won = make_move(board, player, move)
    if not moved:
        print(' >> Invalid number ! Try again !')
        continue
    if won:
        result='*** Congratulations ! You won ! ***'
        break
    elif computer_move()[1]:
        result='=== You lose ! =='
        break;
print_board()
print(result)
//Cridets to: https://hackr.io/blog/python-projects


COPY

SOME PYTHON PROJECTS

  • JAVA- It’s an object-oriented language similar to Python that’s used to create large systems with complex business logic. Many products have been built using Java, and Oracle Corporation is presently in charge of all future versions. From basic OOPS ideas to multithreadingstreamslambdasfunctional interfaces, and more, Java has a lot to offer.
  • RUBY- Ruby has been used to create several excellent applications, such as Github and Slideshare. Ruby keeps some things abstract to make developers’ lives easier, whereas Python throws everything at the programmer. Ruby is a cross-platform interpreted language, just like Python. Ruby is a dynamically typed language, which implies that a ruby programme may be changed while it is running
  • PHP-  It is a scripting language. Many small-scale and some large-scale applications are built using this language, which is one of the most versatile of all time. Good PHP-based tools, like WordPress, have emerged in the market, making it simple for individuals to host and maintain their websites, as well as manage content. Although it has a smaller scope and can be used only for web development.
  • C- It is a structured oriented language. It includes functions and operators built-in that can solve almost any complicated problem. is a programming language that combines low-level (assembly) and high-level (object-oriented) programming languages. It may also be used to create applications and interface with low-level system memory and hardware. It may be written on almost any operating system and is compatible with the majority of portable devices.

THE ARTICLE IS WRITTEN BY K.ARYAA AND REVISED BY A.SHARAN



要查看或添加评论,请登录

Sharan A的更多文章

  • What is Arduino

    What is Arduino

    Visit our website for more exciting articles Click here WHAT IS ARDUINO AT A GLIMPSE Arduino is a standardized product…

社区洞察

其他会员也浏览了