Python – AppDividend https://appdividend.com Latest Code Tutorials Tue, 22 Jan 2019 19:40:32 +0000 en-US hourly 1 https://wordpress.org/?v=5.0.3 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Python – AppDividend https://appdividend.com 32 32 Python Stack Tutorial Example | Data Structures in Python https://appdividend.com/2019/01/22/python-stack-tutorial-example-data-structures-in-python/ https://appdividend.com/2019/01/22/python-stack-tutorial-example-data-structures-in-python/#respond Tue, 22 Jan 2019 19:36:46 +0000 http://localhost/wordpress/?p=3754 Python Stack Tutorial With Example From Scratch

Python Stack Tutorial Example | Data Structures in Python is today’s topic. The Stack is an Abstract Data Type in Python. Stack stores an Item in order in which they were added. Items can add and removed from the top of the stack. The famous principle the Stack is using called the LIFO(Last In, First Out). […]

The post Python Stack Tutorial Example | Data Structures in Python appeared first on AppDividend.

]]>
Python Stack Tutorial With Example From Scratch

Python Stack Tutorial Example | Data Structures in Python is today’s topic. The Stack is an Abstract Data Type in Python. Stack stores an Item in order in which they were added. Items can add and removed from the top of the stack. The famous principle the Stack is using called the LIFO(Last In, First Out).

In Python, we can use the List data type because we can add or remove the item from the list. A list is a built-in datatype we can use to create a Stack.

Python Stack Tutorial Example

Basic Python Stack Operations are following.

  1. Add item to the Stack.
  2. Remove the item from the Stack.
  3. How many items are there in the Stack?

Let’s take the example of Stack.

Create one file called app.py and write the following code.

# app.py

class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

dataStack = Stack()
dataStack.push('krunal')
print(dataStack.items)

In the above code, we have defined one list called items inside the Constructor.

Then, we have created a method called a push. The push method is responsible for adding an item to the Stack.

Next step is that we have created an object from the Stack class and called a push method to an object and pass an item in the parameter.

Now, that item will be added inside the list, and finally, we have printed that list. See the output below.

 

Python Stack Tutorial Example

Now let’s interact with the above code and see the output. Remove the last three lines of the code.

# app.py

class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

Okay, now go to the terminal and type the following command.

python3 -i app.py

 

Stack Data Structures in Python

Python Stack Pop Example

We have seen the Push Example in Stack. Now let’s see the Pop example in Stack.

Pop Example in Stack is same as Python List Pop method. If we do not specify the argument that which item needs to be removed then it will by default remove the last item in the list. Stack pop also works the same way. That is why we need to define a pop method in the Stack class and see the output.

# app.py

class Stack:
    def __init__(self):
        self.items = ['Imhotep', 'Anak Su na moon']

    def push(self, item):
        self.items.append(item)
    
    def pop(self):
        self.items.pop()

In the above example, we have added two items at the time of building an object means in the constructor.

Now, when we call the pop() method on the Stack object, it will remove the last item from the stack which here is Anak Su na moon. So only the Imhotep will be there in the Stack.

Let’s interact with the Python Shell and see the output.

 

Python Stack Pop Example

Check Stack Items Length

We can check the total number of items of Stack or length of the Stack by len() function of Python. Let’s see the output below.

# app.py

class Stack:
    def __init__(self):
        self.items = ['Imhotep', 'Anak Su na moon']

    def push(self, item):
        self.items.append(item)
    
    def pop(self):
        self.items.pop()

    def length(self):
        return len(self.items)

Now, we have defined one function called length. It will return the total number of items inside the Stack.

See the output below.

 

Check Stack Items Length

Finally, Python Stack Tutorial Example | Data Structures in Python is over.

The post Python Stack Tutorial Example | Data Structures in Python appeared first on AppDividend.

]]>
https://appdividend.com/2019/01/22/python-stack-tutorial-example-data-structures-in-python/feed/ 0
Python While Loop Example | Loops in Python Tutorial https://appdividend.com/2019/01/22/python-while-loop-example-loops-in-python-tutorial/ https://appdividend.com/2019/01/22/python-while-loop-example-loops-in-python-tutorial/#respond Tue, 22 Jan 2019 17:07:43 +0000 http://localhost/wordpress/?p=3745 Python While Loop Tutorial With Example

Python While Loop Example | Loops in Python Tutorial is today’s topic. With the use of while loop, we can execute the set of statements as long as the condition is true. A while loop tells a computer to do something as long as the condition is met or holds true. Its construct consists of the […]

The post Python While Loop Example | Loops in Python Tutorial appeared first on AppDividend.

]]>
Python While Loop Tutorial With Example

Python While Loop Example | Loops in Python Tutorial is today’s topic. With the use of while loop, we can execute the set of statements as long as the condition is true. A while loop tells a computer to do something as long as the condition is met or holds true. Its construct consists of the block of code and the condition. The condition is evaluated, and if the condition is true, the code within the block is executed. It repeats until the condition becomes false.

Python While Loop Example

Loops are used in the Python programming to repeat the specific block of code. In this post, you will learn to create the while loop in Python. 

A while loop in Python is used to iterate over the block of code as long as the test condition) is true. See the following syntax of while loop. We generally use a while loop when we don’t know, the number of times to iterate.

The syntax of while Loop in Python

See the following syntax of while loop.

while test_expression:
    { body of while }

In while loop, the test expression is checked first. The body of a loop is entered only if a test_expression evaluates to True.

After one iteration, the test expression is rechecked. This process continues until the text_expression evaluates to False. Remember, we need to change the value somehow otherwise it will go to an infinite loop.

In the Python, a body of a while loop is determined by indentation. Body starts with an indentation, and the first unindented line marks the end. Python interprets any non-zero value to TrueNone and 0 are interpreted as False.

See the following example of while loop in Python.

# app.py

i = 21
while i < 29:
  print(i)
  i += 1

 

Python While Loop Example

In the above program, the test expression will hold as long as our variable i is less than or equal to 29 in our program starting from 21. We need to increase the value of i variable in the body of the loop. It is essential and mostly forgotten. If we failing to do so will result in an infinite loop or never-ending loop. Finally, the result is displayed.

while loop with else

Let’s take an example of while loop with else in Python. 

If you have used Python For Loop then in that we have else block same here as we can have an optional else block with the while loop as well.

The else part is executed if the condition in a while loop evaluates to False.

A while loop can be stopped with the break statement. In such a case, the else part is ignored. Hence, the while loop’s else part runs if no break occurs and the condition is false.

Here is an example.

# app.py

counter = 0

while counter < 3:
    print(counter)
    counter = counter + 1
else:
    print('Executed Else Statement')

In the above code, unless the condition is false, the counter is printed. After the condition is false, the else block is executed. See the output below.

 

while loop with else

The break Statement in Python

With the break statement, we can stop the loop even if the while condition is true.

# app.py

i = 1
while i < 5:
  print(i)
  if i == 3:
    break
  i += 1

See the output below.

 

The break Statement in Python

Finally, Python While Loop Example | Loops in Python Tutorial is over.

The post Python While Loop Example | Loops in Python Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/01/22/python-while-loop-example-loops-in-python-tutorial/feed/ 0
Python With Statement Tutorial Example https://appdividend.com/2019/01/22/python-with-statement-tutorial-example/ https://appdividend.com/2019/01/22/python-with-statement-tutorial-example/#respond Tue, 22 Jan 2019 16:16:27 +0000 http://localhost/wordpress/?p=3738 Python With Tutorial With Example

Python With Statement Tutorial Example is today’s topic. Opening files using the with statement is generally recommended because it ensures that open file descriptors are closed automatically after program execution leaves the context of the with statement. In Python, you need to give access to the file by opening it. You can do it by using an open() […]

The post Python With Statement Tutorial Example appeared first on AppDividend.

]]>
Python With Tutorial With Example

Python With Statement Tutorial Example is today’s topic. Opening files using the with statement is generally recommended because it ensures that open file descriptors are closed automatically after program execution leaves the context of the with statement. In Python, you need to give access to the file by opening it. You can do it by using an open() function. Open returns the file object, which has methods and attributes for getting information about and manipulating the opened file.

Python With Statement Tutorial Example

Let’s see an example of with statement in python.

with open('app.txt', 'w') as f:
    f.write('AppDividend')

In the above code, we have opened up a file in write mode and written that file. With the “with” statement, you get the better syntax and exceptions handling. The “with” statement simplifies exception handling by encapsulating common preparation and cleanup tasks.

Without the with statement

Let’s see an example where we do not use with statement and handling file operations in Python.

# app.py

file = open('app.txt')
data = file.read()
print(data)
file.close()

See the output below.

 

Python With Statement Tutorial Example

Opening a file using with is as simple as: with open(filename) as the file.

Write above code using With Statement

Let’s write the same code, but using with statement and see the output.

# app.py

with open('app.txt') as file:
   data = file.read()
   print(data)

The output is the same, but here we have used the with statement to read the file and printing in the console.

 

Write above code using With Statement

Here notice that we have not used a file.close() function. That function will be automatically called.

Finally, Python With Statement Tutorial Example is over.

The post Python With Statement Tutorial Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/01/22/python-with-statement-tutorial-example/feed/ 0
Python CSV Tutorial | Reading and Writing CSV Files in Python https://appdividend.com/2019/01/22/python-csv-tutorial-reading-and-writing-csv-files-in-python/ https://appdividend.com/2019/01/22/python-csv-tutorial-reading-and-writing-csv-files-in-python/#respond Tue, 22 Jan 2019 10:53:08 +0000 http://localhost/wordpress/?p=3718 Python CSV Read and Write Files Tutorial With Example

Python CSV Tutorial | Reading and Writing CSV Files in Python is today’s topic. Exchanging information through text files is the standard way to share info between programs and one of the most popular formats for transferring data in the CSV format. You don’t need to build your own CSV parser from scratch. There are acceptable standard […]

The post Python CSV Tutorial | Reading and Writing CSV Files in Python appeared first on AppDividend.

]]>
Python CSV Read and Write Files Tutorial With Example

Python CSV Tutorial | Reading and Writing CSV Files in Python is today’s topic. Exchanging information through text files is the standard way to share info between programs and one of the most popular formats for transferring data in the CSV format. You don’t need to build your own CSV parser from scratch. There are acceptable standard libraries you can use.

In this post, you will learn how to read, process, and parse the CSV files using Python. You will see how CSV files work, learn the all-important csv library built into Python.

What is a CSV File?

CSV(Comma Separated Values) files are used to store a large number of variables or data. They are incredibly simplified spreadsheets think Excel, only the content is stored in plaintext. Python CSV module is a built-in function that allows Python to parse these types of files.

The text inside the CSV file is laid out in rows, and each of those has columns, all separated by commas.

Technically in CSV files, the first row is column names in SQL tables, and then the other rows are the data according to the columns.

Every line in a CSV file is a row in the spreadsheet, while the commas are used to define and separate cells.

The structure of the CSV file is following.

column 1 name,column 2 name, column 3 name
first row data 1,first row data 2,first row data 3
second row data 1,second row data 2,second row data 3
third row data 1,third row data 2,third row data 3
fourth row data 1,fourth row data 2,fourth row data 3

Parsing CSV Files With Python’s Built-in CSV Library

Python CSV library provides functionality to read and write to the CSV files. It is specifically designed to work out of the box with Excel-generated CSV files; it is effortless to work with the variety of CSV formats.

The csv library contains the objects and other code to read, write, and process data from and to the CSV files.

Python CSV module includes all the necessary functions built in. They CSV function list is following.

  1. csv.reader()
  2. csv.writer()
  3. csv.register_dialect()
  4. csv.unregister_dialect()
  5. csv.get_dialect()
  6. csv.list_dialects()
  7. csv.field_size_limit

Python CSV Tutorial

Let’s read and write the CSV files using Python CSV module.

Reading CSV Files

If we need to pull the data from the CSV file, you must use the reader function to generate the reader object.

The reader function is formed to take each line of the file and make the list of all columns. Then, you choose the column you want a variable data for.

The CSV file is opened as the text file with Python’s built-in open() function, which returns the file object. This is then passed to the reader, which does the heavy lifting.

The syntax for reading a CSV file in Python is following.

import CSV
With open(‘some.csv’, ‘rb’) as f:
reader = csv.reader(f)
for row in reader:
print row

Let’s see the following example.

Let’s create a CSV file called data.csv and add the following content.

column 1 name,column 2 name, column 3 name
first row data 1,first row data 2,first row data 3
second row data 1,second row data 2,second row data 3
third row data 1,third row data 2,third row data 3
fourth row data 1,fourth row data 2,fourth row data 3

In the same directory, create a file called app.py and add the following code inside that file.

# app.py

import csv

with open('data.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'\t{row[0]} works in the {row[1]} department, and was born in {row[2]}.')
            line_count += 1
    print(f'Processed {line_count} lines.')

Notice the first line of code is used to import the CSV module.

Then we have used the open() function and pass the file which we need to read and then use the csv module’s reader function to create an object and iterate that object to get the row and columns.

Each row returned by the reader is the list of String elements containing the data found by removing the delimiters. 

The first row returned contains the column names, which is handled in a special way.

See the output below.

 

Python CSV Tutorial | Reading and Writing CSV Files in Python

See in the output; we have differentiated the columns names and rows data.

Optional Python CSV reader Parameters

The reader object can handle the different styles of CSV files by specifying additional parameters, some of which are shown below:

  • The delimiter specifies the character used to separate each field. The default is the comma (‘, ‘).
  • The quotechar specifies the unique character used to surround fields that contain the delimiter character. The default is the double quote (‘ ” ‘).
  • The escapechar specifies the character used to escape the delimiter character, in case quotes aren’t used. The default is no escape character.

Writing to CSV Files

You can also write to the CSV file using the writer object and the .write.row() method.

If the writing file has not been created, then it will be automatically created. Let’s see the following example.

# app.py

import csv

with open('student.csv', mode='w') as student_file:
    student_writer = csv.writer(student_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

    student_writer.writerow(['Krunal Lathiya', 'GTU', 'BE'])
    student_writer.writerow(['Ankit Lathiya', 'GTU', 'MCA'])

    print('Writing has been completed')

In the above code, we have not created the student.csv file, still created a writer object and written the two rows.

Run the file and see the output.

 

Writing to CSV Files in Python

You can see the student.csv file inside your project directory.

Krunal Lathiya,GTU,BE
Ankit Lathiya,GTU,MCA

The quotechar is an optional parameter that tells the writer object which characters to use to quote fields when writing the file. 

Whether quoting is used or not, however, is determined by an optional quoting parameter:

  • If quoting is set to the csv.QUOTE_MINIMAL, then .writerow() will quote fields only if they contain a delimiter or a quotechar. This is by default case.
  • If quoting is set to the csv.QUOTE_ALL, then .writerow() will quote all the fields.
  • If quoting is set to the csv.QUOTE_NONNUMERIC, then .writerow() will quote all the fields containing the text data and convert all numeric fields to a float data type.
  • If quoting is set to the csv.QUOTE_NONE, then .writerow() will escape delimiters instead of quoting them. In that case, you also must provide the value for the escapechar optional parameter.

Finally, Python CSV Tutorial | Reading and Writing CSV Files in Python is over.

The post Python CSV Tutorial | Reading and Writing CSV Files in Python appeared first on AppDividend.

]]>
https://appdividend.com/2019/01/22/python-csv-tutorial-reading-and-writing-csv-files-in-python/feed/ 0
Python Super Function Example | Super() Method Tutorial https://appdividend.com/2019/01/22/python-super-function-example-super-method-tutorial/ https://appdividend.com/2019/01/22/python-super-function-example-super-method-tutorial/#respond Tue, 22 Jan 2019 06:52:59 +0000 http://localhost/wordpress/?p=3706 Python Super Function Tutorial With Example

Python Super Function Example | Super() Method Tutorial is today’s topic. The super() builtin returns the proxy object that allows you to refer parent class by ‘super.’ The super function in Python can be used to gain access to inherited methods which is either from a parent or sibling class.  The super() builtin function returns a […]

The post Python Super Function Example | Super() Method Tutorial appeared first on AppDividend.

]]>
Python Super Function Tutorial With Example

Python Super Function Example | Super() Method Tutorial is today’s topic. The super() builtin returns the proxy object that allows you to refer parent class by ‘super.’ The super function in Python can be used to gain access to inherited methods which is either from a parent or sibling class. 

The super() builtin function returns a proxy object, a substitute object a substitute object that can call the method of the base class via delegation. This is called indirection (ability to reference base object with super()). The super function is versatile and can be used in the couple of ways.

Python Super Function Example

If we want to understand the python super function, we need to know about Inheritance in the Python language. In Python Inheritance, the subclasses can inherit from the superclass.

Python super function can refer the superclass implicitly. So, Python super () function makes our task more manageable.

While referring the superclass from the base class, we don’t need to write the name of superclass explicitly. 

In the following sections, we will discuss the python super function.

How to Call Super in Python 3?

We can call using the following syntax. We will take a regular class definition and modify it by adding the super function. The final code with super() keyword looks like below.

class MyParentClass():
    def __init__(self):
        pass

class SubClass(MyParentClass):
    def __init__(self):
        super()

As you can see, this is a setup of single inheritance.

We can see that there’s the base or parent class (also sometimes called the superclass), and derived class or subclass.

But we still need to initialize the parent or base class within the subclass or derived or child. 

We can call the super() function to process easier.  The goal of Super function is to provide a much more abstract and portable solution for initializing classes.

Let’s see the example of the super() function in Python.

# app.py

class Computer():
    def __init__(self, computer, ram, ssd):
        self.computer = computer
        self.ram = ram
        self.ssd = ssd

class Laptop(Computer):
    def __init__(self, computer, ram, ssd, model):
        super().__init__(computer, ram, ssd)
        self.model = model

lenovo = Laptop('lenovo', 2, 512, 'l420')
print('This computer is:', lenovo.computer)
print('This computer has ram of', lenovo.ram)
print('This computer has ssd of', lenovo.ssd)
print('This computer has this model:', lenovo.model)

In the above example, we have defined one base class which is Computer, and one is derived class which is Laptop.

We have defined three properties inside the base class, and the derived class has total four properties. 

Three properties from derived class are derived from the base class, and fourth is that’s own property. In the derived or child class has its model property. Other three are obtained from base class Computer.

So, now if we only create an object of the derived class, we still have all the access of the base class’s property because of super() function.

The output of the above example is the following.

 

Python Super Function Example

Python super() function with multilevel inheritance

As we have stated previously that Python super() function allows us to refer the superclass implicitly.

But in the case of multi-level inheritances which class will it refer? Well, a Python super() will always refer the immediate superclass.

Also, a Python super() function not only can refer the __init()__ function but also can call all other function of the superclass. So, in the following example, we will see that.

See the following example.

# app.py

class A:
    def __init__(self):
        print('Initializing: class A')

    def sub_method(self, b):
        print('Printing from class A:', b)


class B(A):
    def __init__(self):
        print('Initializing: class B')
        super().__init__()

    def sub_method(self, b):
        print('Printing from class B:', b)
        super().sub_method(b + 1)


class C(B):
    def __init__(self):
        print('Initializing: class C')
        super().__init__()

    def sub_method(self, b):
        print('Printing from class C:', b)
        super().sub_method(b + 1)


if __name__ == '__main__':
    c = C()
    c.sub_method(1)

See the output below.

 

Super() Method Tutorial Example

So, from the output we can clearly see that the __init()__ function of class C had been called at first, then class B and after that class A. 

The same thing happened by calling sub_method() function.

If your program contains multi-level inheritance, then this super() function is beneficial for you.

Finally, Python Super Function Example is over.

The post Python Super Function Example | Super() Method Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/01/22/python-super-function-example-super-method-tutorial/feed/ 0
Python Sys.argv Tutorial | Command Line Arguments Example https://appdividend.com/2019/01/22/python-sys-argv-tutorial-command-line-arguments-example/ https://appdividend.com/2019/01/22/python-sys-argv-tutorial-command-line-arguments-example/#respond Tue, 22 Jan 2019 05:34:40 +0000 http://localhost/wordpress/?p=3698 Python Command Line Arguments Tutorial With Example

Python Sys.argv Tutorial | Command Line Arguments Example is today’s topic. In the command line, we can start the program with the additional arguments. These arguments are passed into the program.  The Python sys module provides access to any command-line arguments using the sys.argv method. It serves the two purposes. The sys.argv is the list of all the command-line arguments. len(sys.argv) is the total […]

The post Python Sys.argv Tutorial | Command Line Arguments Example appeared first on AppDividend.

]]>
Python Command Line Arguments Tutorial With Example

Python Sys.argv Tutorial | Command Line Arguments Example is today’s topic. In the command line, we can start the program with the additional arguments. These arguments are passed into the program

The Python sys module provides access to any command-line arguments using the sys.argv method. It serves the two purposes.

  1. The sys.argv is the list of all the command-line arguments.
  2. len(sys.argv) is the total number of length of command-line arguments.

Here sys.argv[0] is the program, i.e. script name. If you are going to work with command line arguments, you probably want to use sys.argv. 

Python Sys.argv Tutorial

Let’s take the example of sys.argv command and see the output of the following program.

# app.py

import sys

print('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))

Now, go to your command line tool and type the following command with the arguments following by space and hit the enter and see the output.

 

Python Sys.argv Tutorial

Now, analyze the output. We have passed the six arguments, and we got six arguments in the Argument List.

As mentioned above, our first argument is always the script name, and it is also being counted in the number of arguments. So even if you do not pass any arguments to your script, the argv variable always contains at least one element, and that is the script name.

The arguments in an argv method are always parsed as the String

So, you need to be careful, if you are expecting your input to be of any other type. 

You may need to cast or convert the elements according to your requirements.

Storing command line arguments

You can store any number of arguments given at the start of the program in the variables. Let’s see the following example.

# app.py

import sys

print('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))

data = sys.argv[2]
print('The argument three is:', data)

Now, run the file in the command line and see the output.

 

Storing command line arguments

Finally, Python Sys.argv Tutorial | Command Line Arguments Example is over.

The post Python Sys.argv Tutorial | Command Line Arguments Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/01/22/python-sys-argv-tutorial-command-line-arguments-example/feed/ 0
Python Input Example | Getting Input From User Tutorial https://appdividend.com/2019/01/21/python-input-example-getting-input-from-user-tutorial/ https://appdividend.com/2019/01/21/python-input-example-getting-input-from-user-tutorial/#respond Mon, 21 Jan 2019 16:28:11 +0000 http://localhost/wordpress/?p=3690 Python Input Tutorial Example

Python Input Example | Getting Input From User Tutorial is today’s topic. The input() method reads a line from input, converts into a string and returns it. The input() function allows user input. If we want to capture the input in the program, we will need a variable. The variable is a container to hold data.  You can take […]

The post Python Input Example | Getting Input From User Tutorial appeared first on AppDividend.

]]>
Python Input Tutorial Example

Python Input Example | Getting Input From User Tutorial is today’s topic. The input() method reads a line from input, converts into a string and returns it. The input() function allows user input. If we want to capture the input in the program, we will need a variable. The variable is a container to hold data. 

You can take an input and assign it to the variable. It is done using the = operator before the input keyword and then putting the variable name before the = operator.

Python Input Example

The syntax for input() method is following.

input(prompt)

The input() method takes a prompt as an optional argument. The prompt String, representing a default message before the input. If EOF is read, it raises an EOFError exception. See the following example.

# app.py

surname = input('What is your surname? ')
print('Your surname is: ',surname)

The output of the method is following.

 

Python Input Example

Example 2:

Let’s see the following example.

# app.py

inputString = input()
print('The inputted string is:', inputString)

See the output below.

 

Getting Input From User Tutorial

The above example is not right in the sense of User Experience. It is often the right idea to tell the user what to input.

We can do this by putting the hint in quotes inside the input parentheses. That hint will come in the next line and will wait for the user to input. 

Then, the user can then type the input, and when you hit the ENTER key, it will capture the input.

Finally, Python Input Example | Getting Input From User Tutorial is over.

The post Python Input Example | Getting Input From User Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/01/21/python-input-example-getting-input-from-user-tutorial/feed/ 0
Python Global Keyword Tutorial With Example https://appdividend.com/2019/01/21/python-global-keyword-tutorial-with-example/ https://appdividend.com/2019/01/21/python-global-keyword-tutorial-with-example/#respond Mon, 21 Jan 2019 12:02:14 +0000 http://localhost/wordpress/?p=3674 Global Keyword in Python Tutorial With Example

Python Global Keyword Tutorial With Example is today’s topic. In this post, you’ll learn about the global keyword, global variable and when to use global keywords in Python. In Python, global keyword allows you to modify the variable outside of the current scope.  Global keyword is used to create the global variable and make changes to a variable in […]

The post Python Global Keyword Tutorial With Example appeared first on AppDividend.

]]>
Global Keyword in Python Tutorial With Example

Python Global Keyword Tutorial With Example is today’s topic. In this post, you’ll learn about the global keyword, global variable and when to use global keywords in Python. In Python, global keyword allows you to modify the variable outside of the current scope. 

Global keyword is used to create the global variable and make changes to a variable in a local context.

Python Global Keyword Tutorial With Example

The basic rules for a global keyword in Python are following.

  1. When we create a variable inside the function, it is local by default.
  2. When we define a variable outside of the function, it’s global by default. You don’t have to use the global keyword.
  3. We use global keyword to read and write a global variable inside the function.
  4. Use of global keyword outside the function does not affect.

Let’s take an example of Global Keyword.

# app.py

def myLocalFunc():
  global site
  site = 'AppDividend'
myLocalFunc()
print(site)

See the output below.

 

Python Global Keyword Tutorial

In the above example, we have defined the Global variable inside the function. Then we have access that variable outside the function.

Due to we have defined the site variable as a Global, we can access that variable outside that function.

Accessing global Variable From Inside a Function

Let’s take an example where we have defined one variable outside the function. Use that variable inside the function and see the output below.

# app.py

site = 'AppDividend'

def myLocalFunc():
    print(site)

myLocalFunc()

The output is following.

 

Python Global Keyword Tutorial With Example

Modifying Global Variable From Inside the Function

In this example, we are defining one variable outside of the function and then change that variable inside the function and see the output of that variable.

# app.py

site = 'AppDividend'

def myLocalFunc():
    site = site + ': A Good Blog'
    print(site)

myLocalFunc()

Now, in the above example, we are trying to modifying that variable which is defined outside the function. Now, that function has no access to the outside variable. We will see an error in the output.

 

Modifying Global Variable From Inside the Function

Changing Global Variable From Inside the Function using Global Keyword

Let’s take an example where we modify the Global variable inside the function using the Global keyword.

# app.py

count = 21

def myLocalFunc():
    global count
    count = count - 2
    print(count)

myLocalFunc()
print(count)

The above program outputs 19 because we are modifying the global variable directly using global keyword.

 

Changing Global Variable From Inside a Function using Global Keyword

Global Variables Across Python Modules

In Python, we create a single module called shared.py to hold the global variables and share information across Python modules within the same program. Let’s take an example.

Now, first in this example, we will need three files.

  1. shared.py
  2. app.py
  3. main.py

Write the following code inside the shared.py file.

# shared.py

count = 21

In this file, we have defined the global variable called count and assign the value 21.

Now, write the following code inside the app.py file.

# app.py

import shared

shared.count = 19

In this file, we have imported the shared file module and modify that variable to 19.

Finally, write the following code inside the main.py file.

# main.py

import shared
import app

print(shared.count)

Run the file by the following command.

python3 main.py

See the output below.

 

Global Variables Across Python Modules

The app.py modifies the global variable, and we have seen in the output.

So, we have seen almost all the use cases of Global keyword in Python.

Finally, Python Global Keyword Tutorial With Example is over.

The post Python Global Keyword Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2019/01/21/python-global-keyword-tutorial-with-example/feed/ 0
Python Slice Example | slice() Method Tutorial https://appdividend.com/2019/01/19/python-slice-example-slice-method-tutorial/ https://appdividend.com/2019/01/19/python-slice-example-slice-method-tutorial/#respond Sat, 19 Jan 2019 21:30:20 +0000 http://localhost/wordpress/?p=3651 Python Slice Example Tutorial From Scratch

Python Slice Example | slice() Method Tutorial is today’s topic. The slice() constructor creates the slice object representing the set of indices specified by range(start, stop, step). The slice object is used to determine how to slice the sequence.  You can specify where to start the slicing, and where to end.  You can also determine the step, […]

The post Python Slice Example | slice() Method Tutorial appeared first on AppDividend.

]]>
Python Slice Example Tutorial From Scratch

Python Slice Example | slice() Method Tutorial is today’s topic. The slice() constructor creates the slice object representing the set of indices specified by range(start, stop, step). The slice object is used to determine how to slice the sequence. 

You can specify where to start the slicing, and where to end.  You can also determine the step, which allows you to, e.g., slice only every other item.

Python Slice Example

The slice object is used to slice the given sequences like string, bytes, tuple, list, range or any object which supports the sequence protocol ( which implements __getitem__() and __len__() method).

The syntax of Python slice() function is following.

slice(stop)
slice(start, stop, step)

The start parameter is optional, and it is the starting integer where the slicing of the object starts.

The stop parameter is required, and it is an integer number specifying at which position to end the slicing.

The step parameter is optional, and it is an integer value which determines the increment between each index for slicing.

Let’s see the example of Python slice() method.

# app.py

A = ('Bad Bunny', 'Louis Fonsi', 'Daddy Yankee', 'Drake')
result = slice(1,3)
print(A[result])

The output of the above program is following.

 

Python Slice Example | slice() Method Tutorial

See in the above example, we have sliced the object from the index 1 to 3, and we get the elements like Louis Fonsi and Daddy Yankee.

Get substring from a given string using slice object

Let’s see the following example of String where we will get a substring from a string.

# app.py

A = 'AppDividend'
result = slice(3)
print(A[result])

Now, see the output below.

 

Get substring from a given string using slice object

Slice String Using Negative Index

In the following example, we will slice a string based on the negative index.

# app.py

A = 'AppDividend'
result = slice(-3, -1)
print(A[result])

In the below example, we have passed the negative index which means that the execution starts from the end and then go forward and return the value. See the output below.

 

Slice String Using Negative Index

Finally, Python Slice Example | slice() Method Tutorial is over.

The post Python Slice Example | slice() Method Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2019/01/19/python-slice-example-slice-method-tutorial/feed/ 0
Python Sets Tutorial With Example | Getting Started With Sets https://appdividend.com/2019/01/19/python-sets-tutorial-with-example-getting-started-with-sets/ https://appdividend.com/2019/01/19/python-sets-tutorial-with-example-getting-started-with-sets/#respond Sat, 19 Jan 2019 19:12:28 +0000 http://localhost/wordpress/?p=3624 Python Sets Example Tutorial From Scratch

Python Sets Tutorial With Example | Getting Started With Sets is today’s topic. In this article, you will learn about Python sets like how they are created, how you can add the items or remove the elements from them, and all operations performed on sets in Python.  The set is an unordered collection of elements or […]

The post Python Sets Tutorial With Example | Getting Started With Sets appeared first on AppDividend.

]]>
Python Sets Example Tutorial From Scratch

Python Sets Tutorial With Example | Getting Started With Sets is today’s topic. In this article, you will learn about Python sets like how they are created, how you can add the items or remove the elements from them, and all operations performed on sets in Python. 

The set is an unordered collection of elements or items. Every element is unique means no duplicates are allowed and must be immutable which means it cannot be changed in future.

However, the set itself is mutable. We can add or remove items from it. 

Sets can be used to perform mathematical set operations like union, intersection, symmetric difference, etc.

Python Sets Tutorial With Example

Let’s take a simple example of Python Sets.

# app.py

setA = {'Samsung', 'Apple', 'Microsoft'}
print(setA)

See the output below.

 

Python Sets Tutorial With Example

How to create a Python Set

The set is formed by placing all the items inside the curly braces {} and the items are separated by comma or by using the built-in function set().

The set can have any number of items, and they may be of different types (integer, float, tuple, string, etc.). But the set cannot have a mutable element, like a list, or dictionary, as its element.

Let’s create a complex datatypes Python Set.

# app.py

setA = {21, 'AppDividend', (21, 22, 19)}
print(setA)

See the output below.

 

Getting Started With Sets

Access Items in Python Sets

You cannot access items in the set by referring to an index since sets are unordered the items has no index. 

But you can loop through the set elements using the for loop, or ask if the specified value is present in a set, by using them in the keyword.

# app.py

setA = {21, 'AppDividend', (21, 22, 19)}

for item in setA:
    print(item)

See the output below.

 

Access Items in Python Sets

Add Items In Python Set

Sets are mutable. But since they are unordered, indexing has no meaning.

If we need to add one item to a set, we can use the add() method. If we wish to add more than one item then to a set using the update() method. See the below example.

# app.py

setA = {21, 'AppDividend', (21, 22, 19)}

setA.add(True)

print(setA)

In the above example, we have added one item which is the type of Boolean.

For adding the multiple items to the set, we can use the update() method.

# app.py

setA = {'Bad Bunny', 'Drake'}

setA.update({'Daddy Yankee', 'Louis Fonsi'})

print(setA)

Now, see the output below.

 

Add Items In Python Set

Get the Length of a Set

We can use the len function to determine the length of the Set.

# app.py

setA = {'Bad Bunny', 'Drake'}

setA.update({'Daddy Yankee', 'Louis Fonsi'})

print(len(setA))

See the output below.

 

Get the Length of a Set

Remove Item From Set

We cannot access or change an item of the set using indexing or slicing. Set does not support it.

We can remove the item from the set by specifying item value.

# app.py

setA = {'Bad Bunny', 'Louis Fonsi', 'Daddy Yankee'}

setA.remove('Louis Fonsi')

print(setA)

So, the output value is the following.

 

Remove Item From Set

If an item to remove does not exist, the remove() method will raise an error.

Python Set Operations

Sets can be used to carry out the mathematical set operations like union, intersection, difference and symmetric difference.

We can do this in both ways which are operators or methods. Let’s see the following example.

Python Set Union Example

See the following example of Union Operation on Set.

# app.py

setA = {'Bad Bunny', 'Louis Fonsi', 'Daddy Yankee'}
setB = {'Justin Bieber', 'Drake'}

setUnion = setA|setB
print(setUnion)

See the below output.

 

Python Set Union Operation

In the above code line 3, we have performed the union operation between setA and setB. The union operation is performed using | operator. Same can be accomplished using the method union().

# app.py

setA = {'Bad Bunny', 'Louis Fonsi', 'Daddy Yankee'}
setB = {'Justin Bieber', 'Drake'}

setUnion = setA.union(setB)
print(setUnion)

It will give us the same output.

Python Set Intersection Example

The intersection of setA and setB is a set of elements that are common in both sets.

An Intersection is performed using operator. Same can be accomplished using the method intersect().

# app.py

setA = {'Bad Bunny', 'Louis Fonsi', 'Daddy Yankee'}
setB = {'Justin Bieber', 'Drake', 'Louis Fonsi'}

setUnion = setA.intersection(setB)
print(setUnion)

In the above example, we are getting the common items from both sets which is Louis Fonsi. See the output below.

 

Python Set Intersection Example

There are still so many functions out there about Python Sets. We will see briefly one by one on this blog.

Finally, Python Sets Tutorial With Example | Getting Started With Sets is over.

The post Python Sets Tutorial With Example | Getting Started With Sets appeared first on AppDividend.

]]>
https://appdividend.com/2019/01/19/python-sets-tutorial-with-example-getting-started-with-sets/feed/ 0