DEV Community

loading...

Python Basics, Python 101

Qu35t
・9 min read

image

Python is an interpreted high-level general-purpose programming language created by Guido van Rossum in the late 1980s and published to the general public in 1991.

Its syntax and semantics, which emphasize code simplicity and readability, set it apart from other programming languages. This is achievable thanks to its well-defined English keywords and low punctuation reliance. For example, unlike c and c++, python employs white space indentation instead of curly brackets to delimit code blocks, and semicolons aren't necessary for statement termination.
Python is kept simple in general, and you may find it easier to go through the lines and see what you're doing. Python programs are stored in files with the .py extension, which can be run from the command line by typing python file_name.py.

Python's desirable features include:

Python is really interactive. This makes it easier to test a program's functionality. This can be accomplished by modularization, which involves taking tiny chunks of code and evaluating them to see if they work. It can also be combined with IDLE, a development environment.

Python has numerous libraries. This broadens a programmer's horizons by allowing him or her to work with other programming tools needed in many industries such as web development, data science, machine learning, and so on, to enable various features such as connecting to web servers.

Python is platform independent. Python programs can be run on Unix, Linux, Windows, and Mac OS X systems. Python is a flexible programming language. It's simple to expand into other modules, such as C or C++, and construct snippets to do a variety of tasks.

Python is open Source. Download, use, modify, and redistribute the product are all free. It's available under an open source license, so anyone can use it.

Debugging is simple. Because data types are dynamically typed, errors can be spotted fast. When you mix types that don't match, an exception will be raised for you to see. If necessary, you can organize the codes into packages and modules.

Object oriented programming. Objects aid in the decomposition of complex real-world problems into a form that can be coded and solved to achieve solutions.

Python's applications are numerous.
These are a few examples of applications:
• Web Development
• Artificial Intelligence
• Data Science
• Machine Learning
• Automation
• Internet of Thing
• Scientific and Numeric Applications
• Wrangling, Exploration, and Visualization of Data
• Game Development
• Desktop Applications

Python Installation

Install the most recent Python version for your operating system Here

Install Text Editor:

A code editor is a tool that is used to write and edit code. They are usually lightweight and can be great for learning especially for a beginner.

1.) Visual Studio Code

Visual Studio Code (VS Code) is a free and open-source IDE created by Microsoft that can be used for Python development.Download VScode

2.) Sublime Text

Sublime Text is a popular code editor that supports many languages including Python.Sublime

3.) Atom

Atom is a highly customizable open-source code editor developed by Github that can be used for Python development.Atom

4.) Thonny

Thonny is a simple UI Python dedicated IDE that comes with Python 3 built-in. Once you install it, you can start writing Python code.Thonny

5.) Pycharm

PyCharm is a Jetbrain-powered IDE for professional developers.Pycharm

Hello world

The first example of any programming language is usually "Hello world."
Start IDLE and open a new window (select New Window from the File Menu), create a new file and save it as hello.py in your desired program folders, and then input the following code.

print(Hello World)
Enter fullscreen mode Exit fullscreen mode
Executing the Python program.

To run the hello.py file we produced earlier, use the Command Prompt on Windows or the Terminal on Mac or Linux. Then navigate to the location where our file is stored.
Then, to run the hello.py file, type the following command:

python3 hello.py
Enter fullscreen mode Exit fullscreen mode

If everything is in order, the program should run without issues and display the following message on the screen.

Hello World
Enter fullscreen mode Exit fullscreen mode

Creating Comments in Python

A comment is text in a program's code, script, or another file that the user is not supposed to read. When looking at the source code, though, it can be seen.
Comments make code more understandable by explaining what's going on and by preventing pieces of a program from running.

The # character is used to create a single-line comment.

A multi-line comment is one that spans multiple lines and is typed in triple quotes.

#single line comment
’’’
Multi-line comment
using docstring
’’’
Enter fullscreen mode Exit fullscreen mode

Variables

Variables are identified memory locations where data is kept for programs to refer to and manipulate. Variables, to put it simply, are data storage containers.

When assigning values to variables, the equal sign (=) is used.
The name of the variable is the operand to the left of the = operator, and the value stored in the variable is the operand to the right of the = operator.

fav_activity =  swimming
print(fav_activity)
Enter fullscreen mode Exit fullscreen mode

Variables do not require declaration. Python is a dynamically typed language since their data types are deduced from their assignment statement. This means that throughout the code, different data types might be given to the same variable.

Data Types

Python contains a number of standard data types that describe the operations that may be performed on them as well as the storage technique for each of them.
The most common data types-

1. Numbers

Number data types are the ones that will store the numeric values and are classified as:
-Complex (such as complex numbers)
-Float (floating point real values
-Long (long integers that can also be shown as hexadecimal and octal.)
-Int (signed integers)
It also involves numbers and simple mathematics in Python.

Arithmetic
print(46 + 2)  # 48 (addition)
print(10 - 9)  # 1 (subtraction)
print(3 * 3)  # 9 (multiplication)
print(84 / 2)  # 42.0 (division)
print(2 ** 8)  # 256 (exponent)
print(11 % 2)  # 1 (remainder of the division)
print(11 // 2)  # 5 (floor division)
Enter fullscreen mode Exit fullscreen mode

The math module in Python contains well-known arithmetic functions such as sin, cos, tan, exp, log, log10, factorial, sqrt, floor, and ceil.

2. Strings

In Python, strings are a data type for dealing with text. They're a collection of characters encased in quotation marks.
Using the numerous string methods provided, you may conduct a variety of actions on strings.
Creating a string - A string is created by enclosing text in quotes. You can use either single quotes,', or double quotes, ". A triple-quote can be used for multi-line strings.

language = python
multi_lin = ’’’come one
came all
’’’
greetings = hello
Enter fullscreen mode Exit fullscreen mode
3. Lists

Lists are one of the most versatile data types that you can work on in Python. It contains different items enclosed within square brackets and separated out with commas. In Python, a list is referred to as an array in other programming languages.
Lists are mutable and can contain elements of different data types and even other lists.

# can store any data type
multiple_types = [True, 3.7, "Python"]

# access and modify
favourite_foods = ["pasta", "pizza", "french fries"]
print(favourite_foods[1]) # pizza
favourite_foods[0] = "rösti"
print(favourite_foods[0]) # rösti

# subsets
print(favourite_foods[1:3]) # ['pizza', 'french fries']
print(favourite_foods[2:]) # ['french fries']
print(favourite_foods[0:2]) # ['rösti', 'pizza']

# append
favourite_foods.append("paella")

# insert at index
favourite_foods.insert(1, "soup")

# remove
favourite_foods.remove("soup")

# get length
print(len(favourite_foods)) # 4

# get subset (the original list is not modified)
print(favourite_foods[1:3]) # ['pizza', 'french fries']

# lists inside lists
favourite_drinks = ["water", "wine", "juice"]
favourites = [favourite_foods, favourite_drinks]
print(favourites[1][2]) # juice
Enter fullscreen mode Exit fullscreen mode
4. Tuples

Immutable lists contained in parenthesis are referred to as tuples.

#tuples

new_tuple = ("a", "b", "c", "d")
print(len(new_tuple)) # 4
print(new_tuple[1]) # b
print(new_tuple[1:4]) # ('b', 'c', 'd')
Enter fullscreen mode Exit fullscreen mode

To convert an object into a tuple, use tuple() constructor.

t1 = tuple([12,25,93])
t2 = tuple('abcde')

Enter fullscreen mode Exit fullscreen mode

To write a tuple with one element include a comma(,) after the element.


t1 = (5,)
Enter fullscreen mode Exit fullscreen mode

Tuples are immutable, which means they can't be changed. However, portions/slices of existing tuples can be combined to form a new tuple.

5. Dictionary

Dictionaries are key-value pairs and are surrounded by {}, and are similar to objects in JavaScript.
Creating dictionaries - To declare a dictionary we enclose it in curly braces, {}. Each entry consists of a pair separated
by a colon. The first part of the pair is called the key and can be of any data type and the second is the value. The key acts like an index.


language_creators = {
  "Python" : "Guido van Rossum",
  "C" : "Dennis Ritchie",
  "Java" : "James Gosling",
  "Go": "Robert Griesemer",
  "Perl" : "Larry Wall"
}

# access, modify, delete
print(language_creators["Python"]) # Guido van Rossum
language_creators["Go"] = ["Robert Griesemer", "Rob Pike", "Ken Thompson"]
print(language_creators["Go"]) # ['Robert Griesemer', 'Rob Pike', 'Ken Thompson']
print(len(language_creators)) # 5
del language_creators["Perl"]
print(len(language_creators)) # 4

# print keys and values
print(language_creators.keys())
print(language_creators.values())
Enter fullscreen mode Exit fullscreen mode
6. Boolean
# booleans

a = True
b = False
if a is True and b is False:
  print("YUP!")
Enter fullscreen mode Exit fullscreen mode
Comparison, Logical, and Conditional Operators.

Comparison: ==, !=, <, >, <=, >=
Logical: and, or, not
Conditionals: if, else, elif

# logical operators:

laundry_day = "Monday"
today = "Tuesday"
on_vacation = False
if today is laundry_day and today is not "Sunday" and on_vacation is False:
  print("It's laundry day!")
else:
  print("The laundry can wait!")


# comparison operators:
age = 21
if age >= 21:
  print("You can drive a trailer")
elif age >= 16:
  print("You can drive a car")
else:
  print("You can ride a bike") 
Enter fullscreen mode Exit fullscreen mode

Loops

for loops

# foor loop
for x in range(0, 3):
  print(x)

# loop through list
for x in ["Python", "Go", "Java"]:
  print(x)

# loop through dictionary
language_creators = {
  "Python" : "Guido van Rossum",
  "C" : "Dennis Ritchie",
  "Java" : "James Gosling",
}
for key, value in language_creators.items():
  print("Language: {}; Creator: {}".format(key, value))
Enter fullscreen mode Exit fullscreen mode
while loops
# while loop

level = 0
while(level < 30):
  level += 1
  print(level)
Enter fullscreen mode Exit fullscreen mode

Functions

Functions are defined using the def keyword.

# functions
def allowed_to_drive(age):
  if age >= 21:
    return True
  else:
    return False

print(allowed_to_drive(42)) # True
print(allowed_to_drive(12)) # False
Enter fullscreen mode Exit fullscreen mode

Argument default values can also be specified.

def is_laundry_day(today, laundry_day = "Monday", on_vacation = False):
  if today is laundry_day and today is not "Sunday" and on_vacation is False:
    return True
  else:
    return False

print(is_laundry_day("Tuesday")) # False
print(is_laundry_day("Tuesday", "Tuesday")) # True
print(is_laundry_day("Friday", "Friday", True)) # False
Enter fullscreen mode Exit fullscreen mode

Classes

Classes are groups of variables and the functions that interact with them.
The class keyword in Python is used to define classes. They are comparable to classes in other languages such as Java and C#, although there are several variations, such as the use of self instead of this to refer to the class's resultant object. In addition, instead of the more common class name, the constructor method is called init. Every time a class variable is referenced, self must be the first parameter in the argument list of each function, including the constructor.

Method overloading is not possible in Python, however it can be achieved to some extent by providing default values for arguments (shown in the Functions section).


# classes

class Email:
  # __ means private
  __read = False

  def __init__(self, subject, body):
    self.subject = subject
    self.body = body

  def mark_as_read(self):
    self.__read = True

  def is_read(self):
    return self.__read

  def is_spam(self):
    return "you won 1 million" in self.subject

e = Email("Check this out", "There are a bunch of free online course here: https://course.online")
print(e.is_spam()) # False
print(e.mark_as_read())
print(e.is_read()) # True
Enter fullscreen mode Exit fullscreen mode

Python also allows classes to inherit methods and variables from other classes or multiple classes (multiple inheritance).


# inheritance

class EmailWithAttachment(Email):
  def __init__(self, subject, body, attachment):
    super(EmailWithAttachment, self).__init__(subject, body)
    self.__attachment = attachment

  def get_attachment_size(self):
    return len(self.__attachment)

email_with_attachment = EmailWithAttachment("you won 1 million dollars", "open attachment to win", "one million.pdf")
print(email_with_attachment.is_spam()) # True
print(email_with_attachment.get_attachment_size()) # 15
Enter fullscreen mode Exit fullscreen mode

File I/O

Python file handling operations also known as File I/O deal with two types of files. They are:

  1. Text files
  2. Binary files

Despite the fact that the two file formats appear to be identical on the surface, they encode data differently.

A text file is structured as a sequence of lines. And, each line of the text file consists of a sequence of characters. Termination of each line in a text file is denoted with the end of line (EOL). There are a few special characters that are used as EOL, but comma {,} and newlines are the most common ones.

Image files such as .jpg, .png, .gif, etc., and documents such as .doc, .xls, .pdf, etc., all of them constitute binary files.

Different file handling methods include:
1.Opening a File
2.Writing into a File
3.Reading from a File
4.Closing a File

# write
todos_file = open("todos.txt", "wb")
todos_file.write(bytes("buy a new domain name\n", "UTF-8"))
todos_file.write(bytes("work on the side project\n", "UTF-8"))
todos_file.write(bytes("learn a new programming language\n", "UTF-8"))
todos_file.close()

# read
todos_file = open("todos.txt", "r+")
todos_file_contents = todos_file.read()
print(todos_file_contents)
Enter fullscreen mode Exit fullscreen mode

Discussion (0)