www.xbdev.net
xbdev - software development
Thursday April 17, 2025
Home | Contact | Support | Python Language... Power of the Snake .. ..
     
 

Python Language...

Power of the Snake .. ..

 


Python > Python Primer (Tutorial)


The following gives you a quick overview of steps we'll use to get you from 'what is python' to 'I love the smell of python in the morning'. Kick of with the basics of variables and logics through to loops and hacky fun things.

• 1. What is Python? (why python, environment, file extension, how it works, ...)
• 2. The 'language' - layout, formatting, comments, print statement, command prompt, ...
• 3. Functions and conditional logic
• 4. Loops and recursion
• 5. Libraries (imports)
• 6. Data, array, dictionaries, external files, ..
• 7. Hacky fun things you can do with Python
• 8. Serious projects for the serious developer

So don't worry, you'll be writing viruses and scrapping web pages in no time - you'll be surprised at just how easy and powerful python is.


python programming- I will juice you up
The Cable Guy (2002). Don't worry, I'll help you get juiced up with python in no time at all!




- I'll juice you up.
- Call it one guy doing another guy a solid.
- That is so nice.
- Well, you're a nice guy. Many customers treat me like snot.
- You'd be surprised how many customers treat me like snot. Like I'm a goddamn plumber or something.
- You're a Python programmer


1. What is Python? (why python, environment, file extension, how it works, ...)


Why Python?

Python is a powerful programming language that uses 'indentation' for conditional statments and functions. It's also an 'interpreted' language (processes the raw python files in real-time - does not need compiling).

Key points
• Open source (and free)
• Easy to learn and very powerful
• Lots of tutorials and resources
• Highly supported in many areas, such as machine learning and AI
• Easy to find a fix online (stackoverflow)

What is the Python File Type? What Editor?

Start with the files, a python file has the extension '.py', and is just a text file. So you can open it in any text editor, like notepad, notepad++, visual studio, vim, ...

Microsoft Word does not work with text files - it works with 'word' files with the extension '.doc' or '.docx' - so it's not a very good choice for editing your python file.

Key Points
Python file extension '.py'
Python files are 'text files'

How Python Works


You open your text editor, create a new text file called 'test.py', type a few lines of python code and save your file. Then you can run it using the command prompt:

G:>python test.py


Example: test.py
print(' hello (wonderful) python' )

'print(..)' is a built in function which sends debug information to the output

Run Simple Python in Browser

A cool thing as well, for learning, is you can actually run python 3.0 in a web browser! Here is a library for running python using html script blocks.

Details are available here [LINK]

Python version

There are different versions of python - however, the two main flavours are version 2 and version 3. Version 3 introduces lots of changes, such as, strict unicode (support all languages like Chinese), also there was new libraries introduces (not all libraries will work with all versions of python)

You can find out which version of python you're using either at the command prompt or in code directly
Command prompt, type python --version and press enter
python --version


Or in code
import sys
print(sys.version)


print with or without parthentesis?
Earlier versions of python, 2.7 you could us print without paranthesis (e.g., print 'test'). Version 3.0+ of python required parenthesis for functions, including the print - otherwise you'll get an error.
print "test"    # Won't work with python 3+
print( "test" # Will work on both python 2 and 3



python logo
Python logo and homepage 'https://www.python.org/'



Python is free and runs on all platforms - you can download it and install it easily from the python homepage:
python.org



2. The 'language' - layout, formatting, comments, print statement, command prompt, ...


Naming Convention

Essentially, you call functions which perform operations, such as 'print' function for outputing information to the console window. You can also 'store' data in variables using 'identifiers'. You have to be careful your identifiers aren't reserved words (e.g., you don't want to call your variable 'print')

# 'hash' symbol is used for comments (this line won't be run)
myname 'Bob'
myage 23
print( mynamemyage )


Comments

Anything after a 'hash' symbol (#) won't be executed - used to add comments

Strings

There are 4 main ways of creating strings, using set of single or double quotes ('/") or a triple set of single or double quotes, for example:

stringA 'This is a cat'
stringB "This is a cat"
stringC '''This is a cat'''
stringD """This is a cat"""


Triple starting and ending quotes are great when you want to do blocks of text - you don't need to worry about escaping single quotes or double quotes.

Formatting Strings

Strings are very important - especially in python - the language itself is made up of strings - and you can have python generate python - but you need to know how to process, convert, concatenate, manipulate strings in all sorts of ways

'str.format()' Function

Python loves strings - it's a great language for reading, processing and manipulating text data.

You might need to 'insert' data (like numbers) into string with formatting:

txt "For only {price:.2f} dollars!"
print(txt.format(price 39))

txtX "My name is {fname}, I'm {age}".format(fname "John"age 36)


Convert numbers or non string values to strings using 'str' function:

'Hello, Number ' str(5)


'f' Strings

'f' strings let you insert values into the string directly without having to append them on the end.

print(f"Hello, {repr('Monty')} Python!")

bb 22
val 
f"Hello number: {bb}"
print( val )


Add some control, such as decimal places:

f'{expression!conversion:format_spec}'

let a f'{price:.2f}'
print( # '0.20'


'%' Syntax Strings

'%' is the original syntax for formatting strings in Python.

print('Here is you %s milkshake. Enjoy!' order)


Type of Data

There are different data types, strings, numbers, objects, and you need some way of checking what the type is - especially if something goes wrong, or you're reading data from external files. The solution is the 'type' function.

'a value'
22.2
6

print( type(a) )
print( 
type(b) )
print( 
type(c) )


Querky String Operations

Few interesting things you can do with python strings - that you can't do in other languages - such as 'multiplying' a string by a number.

"cat" 10


What do this do? If you multiply a string by a number, it 'repeats' the string, so what you end up with is '10' concatenated versions of the word 'cat'.

catcatcatcatcatcatcatcatcatcat


Blocks and Indentation (Tabs and Spaces)

Other languages like C++ and JavaScript use curley brackets to 'group' blocks of code that represent functions or conditional blocks. Python uses indentation, so 4 spaces or a single tab means you're stepping into a block.

2
if ( == ):
    print( 
'a is equal to 2' )
else
    print( 
'the value a is not 2' )



You'll use this all the time - anytime you want to check something - you can print it out to the console.

print('a')
print(
'this is a test');
1
2
3
print( 'values:'xyz)


Command Prompt (Running code in command prompt)

Great for testing little snippets or performing calculations. Open up a command prompt, type 'python', and the python interpreter is running. You'll see the symbols '>>' which indicates that python is running and waiting for you to type commands.

A simple test, is to type something like '2 * 10'. If python is running, it should perform the calculation and output the result on the following line (20).


python snakes programming
Run and test small lines of python without even opening or creating a python file - run it directly in the command prompt.




3. Functions and conditional logic


Function syntax ('def')

You define a function using the keyword 'def' followed by the function name and parathesis. You call the function using the function name.

# Define the function called myfunc
def myfunc():
    print(
'cats like milk')
    
# Call the function
myfunc()


You can redefine the function just by defining the function with the same name (won't give any error)

def hello():
    print(
'abc 1')
    
def hello():
    print(
'abc 2')
    
def hello():
    print(
'abc 3');
    
# Call function 'hello' - print 'abc 3'
hello()



Conditional logic (if statements, else, elif, switch, case, ...)


if ( True ):
    print(
'true')
else:
    print(
'false')



if ( False ):
    print(
'one')
elif False ):
    print(
'two')
elif False ):
    print(
'three')
elif True ):
    print(
'four')
else:
    print(
'size')



While the official documentation are happy not to provide switch, you can do a workaround using dictionaries.
def zero():
    print(
"You typed zero.")

def sqr():
    print(
"n is a perfect square")

def even():
    print(
"n is an even number")

def prime():
    print(
"n is a prime number")

# map the inputs to the function blocks
options = {zero,
           
sqr,
           
sqr,
           
sqr,
           
even,
           
prime,
           
prime,
           
prime,
}

# Call the option '4' - prints: n is a perfect square
options[4]()


Python 3.10, they introduced the pattern matching technique which could also be used in place of the switch/case.
status 400
match status:
    case 
400:
        print(
"Bad request")
    case 
404:
        print(
"Not found")
    case 
418:
        print(=
"I'm a teapot")

    
# If an exact match is not confirmed, this last case will be used if provided
    
case _:
        print(
"Something's wrong with the internet")


The version number matters - 'match' won't work if you're not using one of the very latest version of Python (3.10+). Be aware, lots of people are still using older versions of python like 2.7 - so it's something to be aware of if you're dependent on very specific python version.


4. Loops and recursion



For loop

for i in range(0,10):
    print(
'hello'i)


While loop

0
while ( ):
    
i++
    print( 
)


Do While

Python does not have built-in functionality to explicitly create a do while loop like other languages. But it is possible to emulate a do while loop in python by restructing your code so it executes first before the while is called.


Recursion (Eating Own Tail)

def callme):
    if ( 
10 ):
        return;
    print( 
)
    
callme)
    
callme)



5. Libraries (Imports and External Libraries)


Python on its own is great - but what makes it a real gem is the huge number of external libraries that you can use - everything from robotic control to games and animation.

Importing library

import frog
frog.update()


Installing libraries

Easiest way to install an external library is with the 'pip' command at the command prompt.
G>pip frog



6. Data, array, dictionaries, external files, ..


Data is very important to python - as you'll be working with data all the time!

List

= [] # create an empty list

a.push# add some data to the array
a.push)
a.push'dd' # mix data types in the array

print( # print the array

print( a.length # print the size of the array


Dictionaries

= {}            # create an empty dicionary
g['cat'] = 2      # add item to the dictionary
g['dog'] = 'happy' 
g['mouse'] = 22

print( g['dog'] ) # retrive the item with the index 'dog'


Files


Read in a simple text file and print out the contents.
open("example.txt"'r')
text f.read()
f.close()
0
print( text )


Create a text file and write it out.
open('out.txt''wt')
f.write('hello file')
f.close()
0






7. Hacky fun things you can do with Python


Python generating python, generating more python and more,

It's like a dirty dream.... or a virus... imagine it, python generating python, which can generate different python and execute itself and do all sorts of crazy thing!

A simple Python script that generates another Python script and then runs it:
def generate_script(filename):
    
# Content of the generated script
    
script_content '''
def main():
    print("Hello from the generated script!")

if __name__ == "__main__":
    main()
'''

    
# Write the content to the specified filename
    
with open(filename'w') as file:
        
file.write(script_content)

def run_generated_script(filename):
    
# Import the generated script as a module
    
import importlib.util
    spec 
importlib.util.spec_from_file_location("generated_script"filename)
    
generated_script importlib.util.module_from_spec(spec)
    
spec.loader.exec_module(generated_script)

    
# Call the main function of the generated script
    
generated_script.main()

def main():
    
# Generate the script file
    
generated_script_filename "generated_script.py"
    
generate_script(generated_script_filename)

    
# Run the generated script
    
print("Running the generated script...")
    
run_generated_script(generated_script_filename)

if 
__name__ == "__main__":
    
main()


When you run this script, it will generate another Python script named `generated_script.py`, which contains a simple `main()` function that prints "Hello from the generated script!". Then, it imports and runs the generated script. You can modify the `script_content` variable inside the `generate_script()` function to generate any Python code you want.


Remember to have proper permissions to write files in the directory where you run the script.

Web scraping

A simple Python example using the `requests` and `BeautifulSoup` libraries to scrape a web page.

First, you'll need to install these libraries, if you haven't got them installed.
pip install requests
pip install beautifulsoup4


A simple script to scrape a webpage. In this example, you'll scrape the titles of articles from a hypothetical news website:
import requests
from bs4 import BeautifulSoup

def scrape_website(url):
    
# Send a GET request to the URL
    
response requests.get(url)

    
# Check if the request was successful
    
if response.status_code == 200:
        
# Parse the HTML content of the page
        
soup BeautifulSoup(response.text'html.parser')

        
# Find all the article titles (you'll need to inspect the HTML of the page to find the appropriate tags)
        
article_titles soup.find_all('h2'class_='article-title')  # Adjust the tag and class according to the website's structure

        # Print the titles of the articles
        
for title in article_titles:
            print(
title.text)
    else:
        print(
"Failed to retrieve page.")

# URL of the website you want to scrape
url 'https://example.com/news'

# Call the function with the URL
scrape_website(url)


Replace `'https://example.com/news'` with the actual URL of the website you want to scrape. Also, make sure to adjust the `find_all` function parameters according to the structure of the HTML on the website you're scraping. You may need to inspect the HTML of the page to find the appropriate tags and classes for the content you're interested in.


8. Serious projects for the serious developer


If you into the hardcore serious path to mastering python for some hardcore projects, then python has your back!

Some cook projects that python is ideally for:
• Robot that learns to walk by itself (Deep-Q Learning, Reinforcement Learning)
• Scrape twitter data and learn what the users are tweeting about without going on twitter (Scrapy, TweePy, Machine Learning)
• Home automation system (Arduino, Python3)
• Self Driving Cars (Deep-Q Learning, PyTorch)
• Personal AI Assistant (NLP, Deep Learning)
• Compilers (Yes you can build your own languages and compilers)
• Games with GUI tools (PyQt etc.)
• Task Automation (Data analysis, Data Science)
• Drone projects with Raspberry Pi and Arduino (TensorFlow)
• Blockchain projects
• Microcontroller projects








 
Advert (Support Website)

 
 Visitor:
Copyright (c) 2002-2025 xbdev.net - All rights reserved.
Designated articles, tutorials and software are the property of their respective owners.