Python - tutorial - 01/14 - basics

Revision:


Python - introduction

Python is a popular programming language.

It was created by Guido van Rossum, and released in 1991. It is used for web development (server-side), software development, mathematics, and system scripting.

Python can be used on a server to create web applications.

It can be used alongside software to create workflows.
It also can connect to database systems, and can read and modify files.
It can be used to handle big data and perform complex mathematics.
Lastly, it can be used for rapid prototyping, or for production-ready software development.

Python was designed for readability, and has some similarities to the English language with influence from mathematics.

It uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose.

Python install:

To check if you have python installed on a Windows PC, search in the start bar for Python or run the following on the Command Line (cmd.exe): C:\Users\Your Name>python --version

Python quickstart:

Python is an interpreted programming language, this means that as a developer you write Python (.py) files in a text editor and then put those files into the python interpreter to be executed.
The way to run a python file is like this on the command line:C:\Users\Your Name>python helloworld.py, where "helloworld.py" is the name of your python file.

The Python command line:

To test a short amount of code in python sometimes it is quickest/easiest not to write the code in a file. This is made possible because Python can be run as a command line itself: i.e. type something on the Windows, Mac or Linux command line:C:\Users\Your Name>python. Or, if the "python" command did not work, you can try "py":C:\Users\Your Name>py. From there you can write any python.
Whenever you are done in the python command line, you can simply type exit to quit the python command line interface.


Python - syntax

Execute Python syntax:

Python syntax can be executed by writing directly in the command line, or by creating a python file on the server, using the .py file extension, and running it in the command line.

Python indentation:

indentation refers to the spaces at the beginning of a code line.
The indentation in Python is very important, as Python uses indentation to indicate a block of code.

Python will give you an error if you skip the indentation. The number of spaces is up to the programmer, but it has to be at least one. You have to use the same number of spaces in the same block of code, otherwise Python will give you an error.

Python variables:

in Python, variables are created when you assign a value to it.

Example 1: variables in Python

        x = 5
        y = "Hello, World!"
        
        print(x)
        print(y)
    

!!: Python has no command for declaring a variable.

Comments:

Python has commenting capability for the purpose of in-code documentation. Comments start with a #, and Python will render the rest of the line as a comment

Example 2: comments in Python:

        #This is a comment.
        print("Hello, World!")
        

Comments can be used to explain Python code, to make the code more readable, or to prevent execution when testing code.

Comments can be placed at the end of a line, and Python will ignore the rest of the line.

Example 3: comments at the end of the line

        print("Hello, World!") #This is a comment.
    

A comment can be text that explains the code; it can also be used to prevent Python from executing code:

Example 4: prevent code execution

        #print("Hello, World!")
        print("Cheers, Mate!")
    

Multi line comments:

Python does not really have a syntax for multi line comments. To add a multiline comment you could insert a # for each line.

Example 5: multiline comment

        #This is a comment
        #written in
        #more than just one line
        print("Hello, World!")
    

Or, you can use a multiline string. Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string (triple quotes) in your code, and place your comment inside it. As long as the string is not assigned to a variable, Python will read the code, but then ignore it, and you have made a multiline comment.

Example 6: multiline comment

        """
        This is a comment
        written in
        more than just one line
        """
        print("Hello, World!")
    


Python - variables

Variables are containers for storing data value.

Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.

Example 7: creating variables

        x = 5
        y = "John"
        print(x)
        print(y)
    

Variables do not need to be declared with any particular type, and can even change type after they have been set.

Example 8: changing type of variable

        x = 4       # x is of type int
        x = "Sally" # x is now of type str
        print(x)
    

String variables can be declared either by using single or double quotes.

Variable names are case-sensitive.

Casting: the data type of a variable can be specified with casting.

Example 9: Casting

        x = str(3)    # x will be '3'
        y = int(3)    # y will be 3
        z = float(3)  # z will be 3.0
    

Get the data type of a variable with the type() function.

Example 10: type() function

        x = 5
        y = "John"
        print(type(x)) # class 'int'
        print(type(y)) # class 'str'
    

Variable names can be short (like x and y) or more descriptive(age, carname, total_volume).

Following rules apply for Python variables:

a/ a variable name must start with a letter or the underscore character,
b/ a variable name cannot start with a number,
c/ a variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ),
d/ variable names are case-sensitive (age, Age and AGE are three different variables)

Example 11:legal variable names

        myvar = "John"
        my_var = "John"
        _my_var = "John"
        myVar = "John"
        MYVAR = "John"
        myvar2 = "John"
    

Example 12: illegal variable names

        2myvar = "John"
        my-var = "John"
        my var = "John"
    

Multi words variable names:

Variable names with more than one word can be difficult to read. There are several techniques you can use to make them more readable:

Camel case: each word, except the first, starts with a capital letter:

Example 13: myVariableName = "John"

Pascal case: each word starts with a capital letter:

Example 14: MyVariableName = "John"

Snake case: each word is separated by an underscore character:

Example 15: my_variable_name = "John"

Assign multiple values

many values to multiple variables: Python allows you to assign values to multiple variables in one line.

Example 16: multiple variables in one line

        x, y, z = "Orange", "Banana", "Cherry"
        print(x)  # Orange
        print(y)  # Banana
        print(z)  # Cherry
    

one value to multiple variables: you can assign the same value to multiple variables in one line.

Example 17: one value to multiple variables

        x = y = z = "Orange"
        print(x)  # Orange
        print(y)  # Orange
        print(z)  # Orange
    

unpack a collection: if you have a collection of values in a list, tuple, etc., Python allows you to extract the values into variables. This is called unpacking.

Example 18: unpack a list

        fruits = ["apple", "banana", "cherry"]
        x, y, z = fruits
        print(x)  # apple
        print(y)  # banana
        print(z)  # cherry
    

Output variables: the Python "print" statement is often used to output variables.

To combine both text and a variable, Python uses the "+" character.

Example 19: print and "+"

        x = "awesome"
        print("Python is " + x)  # Python is awesome
    

The "+" character can also be used to add a variable to another variable.

Example 20: "+" and variables

        x = "Python is "
        y = "awesome"
        z =  x + y
        print(z) # Python is awesome        
    

For numbers, the "+" character works as a mathematical operator.

Example 21:

        x = 5
        y = 10
        print(x + y)  # 15
    

If you try to combine a string and a number, Python will give you an error.

Example 22: number + string

        x = 5
        y = "John"
        print(x + y)  #TypeError: unsupported operand type(s) for +: 
          'int' and 'str'
    

Global variables

Global variables: variables that are created outside of a function are known as global variables. Global variables can be used by everyone, both inside of functions and outside.

Example 22: create a variable outside of a function, and use it inside the function

        x = "awesome"
        def myfunc():
          print("Python is " + x)  # Python is awesome
        myfunc() 
    

A variable created inside a function will be local and can only be used inside the function.
A global variable with the same name will remain as it was, global and with the original value.

Example 23: create a variable inside a function, with the same name as the global variable

        x = "awesome"
        def myfunc():
          x = "fantastic"
          print("Python is " + x) # Python is fantastic
        myfunc() 
        print("Python is " + x)  # Python is awesome
    

The global keyword: to create a global variable inside a function, the global keyword can be used.

Example 24: if you use the "global" keyword, the variable belongs to the global scope:

        def myfunc():
            global x
            x = "fantastic"
        myfunc()
        print("Python is " + x)  # Python is fantastic