Introduction

What is Python?

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,
  • system scripting.

Why Python?

  • Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
  • Python has a simple syntax similar to the English language.
  • Python has syntax that allows developers to write programs with fewer lines than some other programming languages.
  • Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.
  • Python can be treated in a procedural way, an object-oriented way or a functional way.

Good to know

  • The most recent major version of Python is Python 3, which we shall be using in this tutorial. However, Python 2, although not being updated with anything other than security updates, is still quite popular.
  • In this tutorial Python will be written in a text editor. It is possible to write Python in an Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which are particularly useful when managing larger collections of Python files.

Why Python?

  • Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
  • Python has a simple syntax similar to the English language.
  • Python has syntax that allows developers to write programs with fewer lines than some other programming languages.
  • Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.
  • Python can be treated in a procedural way, an object-oriented way or a functional way.
Syntax

Python was originally developed as a teaching language, but its ease of use and clean syntax have led it to be embraced by beginners and experts alike. The cleanliness of Python's syntax has led some to call it "executable pseudocode", and indeed my own experience has been that it is often much easier to read and understand a Python script than to read a similar script written in, say, C. Here we'll begin to discuss the main features of Python's syntax. Syntax refers to the structure of the language (i.e., what constitutes a correctly-formed program). For the time being, we'll not focus on the semantics – the meaning of the words and symbols within the syntax – but will return to this at a later point.

Comment

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

Creating a Comment

Single Line Comments : they start with # example #This is a comment print("Hello, World!") while

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: Or, not quite as intended, 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: """ This is a comment written in more than just one line """ print("Hello, World!")

Hello world
In this program, we have used the built-in print() function to print the string Hello, world! on our screen. By the way, a string is a sequence of characters. In Python, strings are enclosed inside single quotes, double quotes, or triple quotes. # This program prints Hello, world! print('Hello, world!')
Variables
Variables are containers for storing data values.

Creating Variables

Python has no command for declaring a variable.A variable is created the moment you first assign a value to it. Variables do not need to be declared with any particular type, and can even change type after they have been set.

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

Casting

If you want to specify the data type of a variable, this can be done with casting.

Example
x = str(3) # x will be '3' y = int(3) # y will be 3 z = float(3) # z will be 3.0
variables Names
You can name a variable in various ways:
Variable Names
  • A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables:
  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive (age, Age and AGE are three different variables)
Example
Legal variable names: myvar = "John" my_var = "John" _my_var = "John" myVar = "John" MYVAR = "John" myvar2 = "John" Illegal variable names: 2myvar = "John" my-var = "John" my var = "John"
Global variables

Variables that are created outside of a function (as in all of the examples above) are known as global variables.Global variables can be used by everyone, both inside of functions and outside. If you create a variable with the same name inside a function, this variable will be local, and can only be used inside the function. The global variable with the same name will remain as it was, global and with the original value.

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

A constant is a type of variable whose value cannot be changed. It is helpful to think of constants as containers that hold information which cannot be changed later. You can think of constants as a bag to store some books which cannot be replaced once placed inside the bag. In Python, constants are usually declared and assigned in a module. Here, the module is a new file containing variables, functions, etc which is imported to the main file. Inside the module, constants are written in all capital letters and underscores separating the words.

PI = 3.14; g = 9.8; import constant print(constant.PI) print(constant.g)

In the above program, we create a constant.py module file. Then, we assign the constant value to PI and g. After that, we create a main.py file and import the constant module. Finally, we print the constant value.

Data types

In programming, data type is an important concept.Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:

  • Numeric Types: int, float, complex
  • Sequence Types: list, tuple, range
  • Mapping Type: dict
  • Set Types: set, frozenset
  • Boolean Type: bool
  • Binary Types: bytes, bytearray, memoryview/p>
if...else statement

Python supports the usual logical conditions from mathematics:

These conditions can be used in several ways, most commonly in "if statements" and loops. An "if statement" is written by using the if keyword, "eles if statement" is written by using the elif keyword and the "else statement" by using else keyword a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b")

while statement

What is while loop in Python?

The while loop in Python is used to iterate over a block of code as long as the test expression (condition) is true.We generally use this loop when we don't know the number of times to iterate beforehand. i = 1 while i < 6: print(i) i += 1 In the while loop, test expression is checked first. The body of the loop is entered only if the test_expression evaluates to True. After one iteration, the test expression is checked again. This process continues until the test_expression evaluates to False. In Python, the body of the while loop is determined through indentation. The body starts with indentation and the first unindented line marks the end. Python interprets any non-zero value as True. None and 0 are interpreted as False.

Function

In Python, a function is a group of related statements that performs a specific task. Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and manageable. Furthermore, it avoids repetition and makes the code reusable.

Syntax of Function

def function_name(parameters): """docstring""" statement(s) Above shown is a function definition that consists of the following components.
  • Keyword def that marks the start of the function header.
  • A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python.
  • Parameters (arguments) through which we pass values to a function. They are optional.
  • A colon (:) to mark the end of the function header.
  • Optional documentation string (docstring) to describe what the function does.
  • One or more valid python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces).
  • An optional return statement to return a value from the function.
def greet(name): """ This function greets to the person passed in as a parameter """ print("Hello, " + name + ". Good morning!") greet('Paul')
Reference