Lesson 1 - Fundamental of Programming in Python
Lesson 1 - Fundamental of Programming in Python
Python was designed for readability and has some similarities to the English language with
influence from mathematics.
Python 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.
Indentation
Indentation refers to the spaces at the beginning of a code line. Where in other programming
languages the indentation in code is for readability only, the indentation in Python is very important. Python
uses indentation to indicate a block of code.
Python will give you a syntax error if you skip the indentation:
The number of spaces is up to you as a programmer, the most common use is four, but it has to be at least
one.
You must use the same number of spaces in the same block of code, otherwise Python will give you an
error:
Comments
Python has commenting capability for the purpose of in-code documentation. Comments can be
used to explain Python code. Comments can be used to make the code more readable. Comments can be
used to prevent execution when testing code. A comment does not have to be text that explains the code, it
can also be used to prevent Python from executing code. Comments start with a #, and Python will render
the rest of the line as a comment, and Python will ignore them:
Comments can be placed at the end of a line, and Python will ignore the rest of the line:
Python does not really have a syntax for multi-line comments. To add a multiline comment, you
could insert a # for each line:
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:
Variable
One of the most powerful features of a programming language is the ability to manipulate
variables. A variable is a name that refers to a value. The variables hold values (data).
Example:
When you’re using variables in Python, you need to adhere to a few rules and guidelines. Breaking
some of these rules will cause errors; other guidelines just help you write code that’s easier to read and
understand. Be sure to keep the following variable rules in mind:
Variable names can contain only letters, numbers, and underscores. They can start with a letter or
an underscore, but not with a number. For instance, you can call a variable message_1 but not
1_message.
Spaces are not allowed in variable names, but underscores can be used to separate words in
variable names. For example, greeting_message works, but greeting message will cause errors.
Avoid using Python keywords and function names as variable names; that is, do not use words that
Python has reserved for a particular programmatic purpose, such as the word print. (You will learn
“Python Keywords and Built-in Functions” on other lessons.)
Variable names should be short but descriptive. For example, name is better than n, student_name
is better than s_n, and name_length is better than length_of_persons_name.
Be careful when using the lowercase letter l and the uppercase letter O because they could be
confused with the numbers 1 and 0.
Variables do not need to be declared with any particular type, and can even change type after they have
been set.
Datatypes
Datatype is set of data with predefined values. The Type of data stored in a variable.
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:
Get the Type
You can get the data type of a variable with the type() function.
In Python, the data type is set when you assign a value to a variable: Python will automatically
define what kind of data you store in a variable.
String
Series of characters interpreted as text. String variables can be declared either by using single or
double quotes:
Raw String
To represent special characters such as tabs and newlines, Python uses the backslash (\) to
signify the start of an escape sequence. For example:
However, raw strings treat the backslash (\) as a literal character. For example:
Multiline Strings
Note: You will learn more about strings in string functions lessons.
Integer
If you want to specify the data type, you can use the following constructor functions:
Example:
Converting one data type to another is known as casting. Python is an object-orientated language,
and as such it uses classes to define data types, including its primitive types. Casting in python is therefore
done using constructor functions.
Example: The value of variable a is string and convert it into integer using the int() constructor function.
Operators
Operators are used to perform operations on variables and values. Python divides the operators in the
following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
Arithmetic operators are used with numeric values to perform common mathematical operations:
Python Assignment Operators
Identity operators are used to compare the objects, not if they are equal, but if they are the same
object, with the same memory location:
Expression
An Expression is a sequence or combination of values, variables, operators and function calls that
always produces or returns a result value.
So, the first combination x = 5 is an expression, the second combination y = 3 is an another expression and
at last, z = x + y is also an expression.
Any Instruction that a python interpreter can execute (carry out) is called a Statement. An
Instruction is an order/command given to a computer processor by a computer program to perform some
mathematical or logical manipulations (calculations). Each line or a sentence in any programming language
is called an instruction.
A Statement is the smallest executable unit of code that has an effect, like creating a variable or
displaying a value. Each line of code that we write in any programming language is called a statement.
Because all the lines are executable by the interpreter or the compiler of that programming language.
Identifiers
Variable name is known as identifier. There are few rules that you must follow while naming the
variables in Python. For example, here the variable is of integer type that holds the value 10. The name of
the variable, which is num is called identifier.
Num = 10
Concatenation
String concatenation means add strings together. Use the + character to add a variable to another
variable or a value to another value:
Example:
If you try to combine a string and a number, Python will give you an error:
So, to concatenate a string into a number or integer value, you need to cast it into string using str function:
The placeholders can be identified using named indexes {name}, numbered indexes {0}, or even
empty placeholders {}.
format()
The format() method allows you to format selected parts of a string. Sometimes there are parts of a
text that you do not control, maybe they come from a database, or user input?
Empty placeholders
To control such values, add placeholders (curly brackets {}) in the text, and run the values through
the format() method:
Example:
You can add parameters inside the curly brackets to specify how to convert the value: More
parameters formatting type on https://www.w3schools.com/python/ref_string_format.asp
Example:
For multiple empty placeholders, the first parameter of format() method will be the first value of the
first placeholders. It depends on order of format parameters.
Numbered Index placeholders
You can use index numbers (a number inside the curly brackets {0}) to be sure the values are
placed in the correct placeholders:
Also, if you want to refer to the same value more than once, use the index number:
Named Indexes placeholders
You can also use named indexes by entering a name inside the curly brackets {carname}, but then
you must use names when you pass the parameter values “My name is {name}”.format(name = "Red"):
Example:
String %
Strings in Python have a unique built-in operation that can be accessed with the % operator. This
lets you do simple positional formatting very easily.
You can add numbers in String (%s) placeholders to insert a whitespace before and after of a
string. %10s added spaces before the string value, and -10s added spaces after the string value.
Character (%c)
f-Strings
Also called “formatted string literals,” f-strings are string literals that have an f at the beginning and
curly braces containing expressions (e.g.: variable, function, etc.) that will be replaced with their values.
Examples:
Keywords
Python has a set of keywords that are reserved words that cannot be used as variable names,
function names, or any other identifiers:
Getting User Input
Python allows for user input. That means we can ask the user for input. The method is a bit
different in Python 3.6 than Python 2.7. Python 3.6 uses the input() method. Python 2.7 uses the
raw_input() method.
The following example asks for the username, and when you entered the username, it gets printed
on the screen.
Python 3.6
Note: Python stops executing when it comes to the input() function, and continues when the user has given
some input.