Join us

PYTHON FUNDAMENTAL FOR BEGINNER

1_-XjypWyDoz_SDEjgvsrXMg.png

A little history about the Python Programming language

A little history about the Python Programming language

Python is a multipurpose and dynamic interpretive programming language, python language is much easier to understand even for a beginner, and unlike other programming languages

With code that is simple and easy to implement, a programmer can prioritize the development of the application that is made, instead of being busy looking for syntax errors.

                print("Learn python")
            

Only by you writing the code as above, you can print what you want inside the ( ) with quotes “ “, without having to use a semicolon at the end

How to install python

Before you use python, you must install the latest version of python at this time, How to install python is very easy, follow the guide below. Below is a guide on how to install python on Linux, Windows, and Mac OS platforms.

LINUX

  1. Open a browser, visit http://www.python.org/downloads/source/
  2. Download the latest version of Python as a zip file for Unix/Linux
  3. Extract the zip file you just downloaded
  4. Edit the Modules/Setup file if you want to customize Python
  5. Run ./configure script
  6. make
  7. make install
    This step will install Python in the standard location /usr/local/bin and the libraries in /usr/local/lib/pythonXX where XX is the latest version of Python you are using.

                For some distros (distribution stores) from the Linux operating system Python is already installed in it. So you don't need to install it again.
            

WINDOWS

  1. Open a browser, visit http://www.python.org/downloads/windows/
  2. OR, click the direct link https://www.python.org/downloads/release/python-3105/
  3. Open (click 2x) the python installer file that you just downloaded
  4. Follow the installation steps to completion

Mac OS

  1. Open a browser, visit http://www.python.org/download/mac/
  2. Download the latest version of Python for Macintosh
  3. Open the file you just downloaded
  4. Follow the installation steps to completion

Running Python

LINUX

  1. Open Terminal CTRL + ALT + T
  2. Type python then you will enter into the Python shell.
  3. Write your Python script, for example, print(“Welcome to Python”). if you press the ENTER key, the Python script will be executed.
  4. To exit Python shell-type exit()

OR

  1. Use a text editor, for example, gedit.
  2. Create a new file, and type your python script, for example, print(“Welcome to Python”).
  3. Save As with .py extension (example: print.py).
  4. Run the file using Terminal.
  5. Open a terminal CTRL+ALT+T.
  6. Go to the directory where your Python files are stored (example: cd /Users/admin/Desktop/).
  7. Run the Python script using python followed by the file name (example: python print.py).
  8. Your Python script will be executed/run.

WINDOWS

Using shell

  1. Open IDLE (python shell on windows), you can look for it in the START button.
  2. Write your Python script, for example, 10 * 4 = 40. if you press the ENTER key, the Python script will be executed.

To exit Python shell-type exit()

To exit Python shell-type exit()

Mac OS

  1. Open a terminal.
  2. Type python then you will enter into the Python shell.
  3. Write your Python script, for example, print(“Welcome to Python”). if you press the ENTER key, the Python script will be executed.
  4. To exit Python shell-type exit()

OR

  1. Use a text editor.
  2. Create a new file, and type your python script, for example, print(“Welcome to Python”).
  3. Save As with .py extension (example: print.py),
  4. Run the file using Terminal.
  5. Open terminal CTRL+ALT+T
  6. Go to the directory where your Python files are stored (example: cd /Users/admin/Desktop/).
  7. Run the Python script using python followed by the file name (example: python print.py).
  8. Your Python script will be executed/run.

Type Data Python

A data type is a medium or memory on a computer that is used to store information.

Python itself has a data type that is quite unique when we compare it with other programming languages.

Here are the data types of the Python programming language:

To try various data types, please try the Python script below.

                #boolean datatype
print(True)

#String datatype
print("Let's learn Python")
print('Learn Python Very Easy')

#Integer data type
print(20)

#float datatype
print(3.14)

#Hexadecimal data type
print(9a)

#Complex data types
print(5h)

#List datatype
print([1,2,3,4,5])
print(["one", "two", "three"])

#tuple datatype
print((1,2,3,4,5))
print(("one", "two", "three"))

#Dictionary data types
print({"name":"Budi", 'age':20})
#Dictionary data type is entered into the biodata variable
biodata = {"name":"Andi", 'age':21} #biography variable initialization process
print(biodata) #printing the biodata variable containing the Dictionary data type
print(type(biodata)) # function to check the type of data type. will show <class 'dict'> which means dict is a data type dictionary
            

Variable Python

Variables are memory locations reserved for storing values.
Variables store data that is carried out during program execution, which later the contents of these variables can be changed by certain operations on programs that use variables

Variables are dynamic, meaning that Python variables do not need to be declared a specific data type and Python variables can be changed when the program is run.

Writing rules :

  1. The first character must be a letter or underscore ( _ )
  2. Subsequent characters can be letters, underscores ( _ ), or numbers
  3. Characters in variable names are case-sensitive. This means that lowercase and uppercase letters are distinguished. For example, the variables first name and first name are different variables.

to create a variable in python, the method is very easy, just write any free variable, then fill it with any value by adding equals ( = ), before the value

Below is an example of using variables :

                #process of entering data into variables
name = "John Doe"
#process print variable
print(name)

#values ​​and data types in variables can be changed
age = 20 #initial value
print(age) #print age value
type(age) #check age data type
age = "twenty one" #value after change
print(age) #print age value
type(age) #check age data type

firstname = "Budi"
lastname = "Susanto"
name = firstname + " " + lastname
age = 22
hobby = "Swimming"
print("Biodata\n", name, "\n", age, "\n", hobby)

#examples of other variables
thisvariable = "Hello"
this_also_variable = "Hi"
_inivariablealso = "Hi"
inivariable222 = "Bye"

length = 10
width = 5
area = length * width
print(area)
            

Python Operators

Operators are constructs that can manipulate the value of an operand.

For example operation 3 * 2 = 6. Here 3 and 2 are operands and * is the operator.

Python programming language supports a variety of operators, including:

below is an example of arithmetic operators:

                #ARITHMATIC OPERATOR

#summing
print(13 + 2)
apple = 7
orange = 9
fruit = apple + orange #
print(fruit)

#Subtraction
debt = 10000
pay = 5000
remainingDebt = debt - pay
print("Your outstanding balance is ", remainingDebt)

#Multiplication
length = 15
width = 8
area = length * width
print(area)

#Distribution
cake = 16
child = 4
cakePerChild = cake / child
print("Each child will get as much cake as ", cakePerChild)

#Remaining Divide / Modulus
number1 = 14
number2 = 5
result = number1 % number2
print("The remainder of the number ", number1, " and ", number2, " is ", result)

#Rank
number3 = 8
number4 = 2
resultPower = number3 **number4
print(result to power)

#Round Division
print(10//3)
#10 divided by 3 is 3.3333. Because it is rounded it will produce a value of 3
            

comparison operator is used to compare a value :

Assignment Operator is used to assign and modify the value to a variable.

Python Conditions

IF Conditions

If conditions are used to determine the actions and conditions to be taken

there are several statements including if, else and elif The if the condition is used to execute code if the condition evaluates to true True
If the condition evaluates to False, the if statement/condition will not be executed.

Below is an example of using IF :

                #The if condition is a condition that will be executed by the program if it is true or TRUE

value = 9

# if the condition is true / TRUE then the program will execute the command below
if(value > 7):
    print("Nine is greater than seven") # Condition True, Executed

# if the condition is false / FALSE then the program will not execute the command below
if(value > 10):
    print("Nine is greater than ten") # False condition, then not executed
            

IF ELSE Conditions

Is used to determine what action to take/execute if the conditions do not match.

The IF ELSE condition is a condition where if the statement is true True then the code in the if will be executed, but if it is False then the code in the else will be executed.

Below is an example of IF ELSE:

                #The if else condition is if the condition evaluates to TRUE then the if code will be executed, but if it is FALSE then the else code will be executed

value = 3
# If the if statement is TRUE then the if will be executed, but if FALSE the else will be executed.
if(value > 7):
    print("Congratulations you passed")
else:
    print("Sorry you didn't pass")
            

ELIF Conditions

With elif we can create program code that will select several possibilities that can occur. Almost the same as the “else” condition, the difference is that the “elif” condition can be many, not just one.

Below is an example of ELIF :

                #Examples of using the elif condition

today = "Sunday"

if(today == "Monday"):
    print("I'm going to college")
elif(today== "Tuesday"):
    print("I'm going to college")
elif(today == "Wednesday"):
    print("I'm going to college")
elif(today == "Thursday"):
    print("I'm going to college")
elif(today== "Friday"):
    print("I'm going to college")
elif(today== "Saturday"):
    print("I'm going to college")
elif(today == "Sunday"):
    print("I'm going on vacation")
            

Python Loops

A loop is a program code instruction that is executed repeatedly. Its function is to command the computer to do something repeatedly with a certain amount as long as a predetermined condition is still met.

The loop has three parts :

  1. While loop
  2. For loop
  3. Nested loop

While loop

A while loop is a statement that is executed many times as long as the condition evaluates to True.

Below is an example of using a While Loop :

                #Examples of using While Loop
#Note: Scoping in Python can use tabs instead of brackets

count = 0
while (count < 9):
    print("The count is: ", count)
    count = count + 1

print("Goodbye!")
            

For Loop

Python’s for loop has the ability to iterate over items of any order, such as a list or a string.

Below for an example For Loop :

                #A simple for loop example
number = [1,2,3,4,5]
for x in number:
    print(x)

#Example of repetition for
fruit = ["pineapple", "apple", "orange"]
for food in fruit:
    print("I like to eat", food)
            

Nested Loop

A nested loop is a programming term that means to make loops within loops.

Below Is an example of the nested loop:

                #Examples of using Nested Loop
#Note: Using modulo in conditionals assumes values ​​other than zero as True(true) and zero as False(false)

i = 2
while(i < 100):
    j = 2
    while(j <= (i/j)):
        if not(i%j): break
        j = j + 1
    if (j > i/j) : print(i, " is prime")
    i = i + 1

print("Goodbye!")
            

Python List

In the Python programming language, the most basic data structure is a sequence of lists. Each successive element will be assigned a position number or index. The first index in the list is zero, the second index is one, and so on.

Make a python list

The list is the most versatile data type available in Python, which can be written as a comma-separated list of values ​​(items) between square brackets. The important thing about lists is that the items in a list cannot be of the same type.

Below is an example of a list :

                list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]
            

Access values in the python list

To use it, use square brackets to slice along with the index, to get the values ​​available in the index

Below is an example :

                #How to access values ​​in Python lists

list1 = ['physics', 'chemistry', 1993, 2017]
list2 = [1, 2, 3, 4, 5, 6, 7 ]

print("list1[0]: ", list1[0])
print("list2[1:5]: ", list2[1:5])
            

list1[0]: fisika list2[1:5]: [2, 3, 4, 5]

Delete values in the python list

To delete a value in a python list, you can use one of the del statements if you know exactly which element you are removing.

Below is an example :

                #An example of how to delete a value in a python list

list = ['physics', 'chemistry', 1993, 2017]

print(list)
del list[2]
print("After deleting the value at index 2 : ", list)
            

Python List Methods and Functions

Python includes the following methods and functions:

Python Tuples

Tuples are sequences, like lists. The main difference between tuples and lists is that tuples are immutable, unlike Python’s Lists. Tuples use brackets, while Python lists use square brackets.

Creating tuples is as easy as entering comma-separated values. Optionally, you can enter these comma-separated values ​​between the brackets as well. As an example :

                #A simple example of creating tuples in the python programming language

tup1 = ('physics', 'chemistry', 1993, 2017)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"
            

Empty tuples are written as two empty parentheses, for example, tup_1 = (); To write a tuple containing a single value, you must enter a comma, even if there is only one value, for example, tup_1 = (10,) Like String indexes, the index of tuples starts at 0, and they can be sliced, concatenated, and so on.

Access Values ​​In Python Tuples

To access values ​​in tuples, use square brackets to slice along with the index or index to get the values ​​available at that index. As an example:

                #How to access tuple values

tup1 = ('physics', 'chemistry', 1993, 2017)
tup2 = (1, 2, 3, 4, 5, 6, 7 )

print("tup1[0]: ", tup1[0])
print("tup2[1:5]: ", tup2[1:5])
            

After you execute the code above, the result will be like this:

                tup1[0]: albert tup2[1:5]: (2, 3, 4, 5)
            

Basic Operations on Python Tuples

Tuples respond to the + and * operators in the same way as Strings; They mean concatenation and looping here also applies

, except the result is a new tuple, not a string.

The following example :

Built-in Functions in Python Tuples

Python includes the following built-in functions :

Python Dictionary

Dictionary is a data type in python that serves to store a collection of data/values ​​with a “key-value” approach, each key is separated from its value by a colon (:)

The dictionary value can be of any type, but the key must be an immutable data type such as a string, number, or tuple.

Access values in the python dictionary

To access a Dictionary element, you can use the familiar square brackets along with the key to getting the value. Here is a simple example:

                #Example of how to make a Dictionary in Python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print("dict['Name']: ", dict['Name'])
print("dict['Age']: ", dict['Age'])
            

Update Values ​​In Python Dictionary

You can update the Dictionary by adding new entries or key-value pairs, modifying existing entries, or deleting existing entries as shown in the simple example given below.

                #Update the python dictionary

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # Change existing entries
dict['School'] = "DPS School" # Adding a new entry

print("dict['Age']: ", dict['Age'])
print("dict['School']: ", dict['School'])
            

Remove Python Dictionary Element

You can delete individual Dictionary elements or delete the entire contents of the Dictionary. You can also delete the entire Dictionary in one operation.

To explicitly delete the entire Dictionary, just use the del statement. Here is a simple example:

                #Example of how to delete in Python Dictionary

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}

del dict['Name'] # delete entry with key 'Name'
dict.clear() # delete all entries in dict
del dict # delete existing dictionary

print("dict['Age']: ", dict['Age'])
print("dict['School']: ", dict['School'])
            

Method Build-in in Python Dictionary

Python includes the following built-in methods:

Python Function

Functions are organized and reusable blocks of code that are used to perform an action. Functions provide better modularity for your application and a high level of code usage.

Defining Python Functions
You can define functions to provide the required functionality. Here are simple rules for defining functions in Python.

  1. The function block starts with the keyword def followed by the function name and parentheses (()).
    2. Each input parameter or argument must be placed inside these brackets. You can also specify parameters inside these brackets.
    3. The first statement of a function can be either an optional statement — a function documentation string or a docstring.
    4. The code block in each function starts with a colon (:) and is indented.
    5. Restatement [expression] exits a function, optionally passing the expression back to the caller. A return statement without arguments is the same as a return of None.

Function example :

                #example simple for loop
number = [1,2,3,4,5]
for x in number:
    print(x)

#exampel for loop
fruits = ["mango", "aple", "orange"]
for food in fruits:
    print ("i like food", food)
            

Only registered users can post comments. Please, login or signup.

Start blogging about your favorite technologies, reach more readers and earn rewards!

Join other developers and claim your FAUN account now!

User Popularity
9

Influence

803

Total Hits

1

Posts