0% found this document useful (0 votes)
56 views20 pages

Lesson 1 - Fundamental of Programming in Python

This document provides an overview of fundamental programming concepts in Python, including syntax, variables, data types, operators, and string formatting. Python syntax uses indentation rather than curly brackets to define scope. Variables can be created without declaring a type and Python will automatically assign data types. Built-in data types include integers, floats, booleans, strings, and lists. Operators allow performing operations on variables and values. Strings support concatenation, formatting, and multiline text through the use of quotes and special characters.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
56 views20 pages

Lesson 1 - Fundamental of Programming in Python

This document provides an overview of fundamental programming concepts in Python, including syntax, variables, data types, operators, and string formatting. Python syntax uses indentation rather than curly brackets to define scope. Variables can be created without declaring a type and Python will automatically assign data types. Built-in data types include integers, floats, booleans, strings, and lists. Operators allow performing operations on variables and values. Strings support concatenation, formatting, and multiline text through the use of quotes and special characters.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 20

Fundamental of Programming in Python

Syntax Review, Comparisons, and Practices

Python Syntax compared to other programming languages

 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:

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:
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).

• Variables are containers for storing data values.

• A variable is created the moment you first assign a value to it.

• Python has no command for declaring a variable.

Example:

Naming and Using Variables

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.

Variable names are case-sensitive.

You can assign a variable as value of another variable

Datatypes

Datatype is set of data with predefined values. The Type of data stored in a variable.

Two types of datatypes:

1. System-defined datatypes (also called primitive datatypes)


2. User-defined datatypes

Built-in 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:
Get the Type

You can get the data type of a variable with the type() function.

Setting the Data Type

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:

'hello' is the same as "hello"

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:

In a regular string, Python counts an escape sequence as a single character:


Meaning, the character after a back slash (\) only display or count. So, when you want to read the
back slash in a string, you need to put backslash two times to read the second backslash (\\).

Using single backslash

Using Double backslash

Using Raw String

However, raw strings treat the backslash (\) as a literal character. For example:
Multiline Strings

You can assign a multiline string to a variable by using three quotes:

Note: You will learn more about strings in string functions lessons.

Integer

When an integer is enclosed by single or double quotation, python read it as string.


Setting the Specific Data Type

If you want to specify the data type, you can use the following constructor functions:

Example:

The b value is a string, and the c is integer, then d is float.


Casting / Type Casting

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

Python Arithmetic Operators

Arithmetic operators are used with numeric values to perform common mathematical operations:
Python Assignment Operators

Assignment operators are used to assign values to variables:

Python Comparison Operators

Comparison operators are used to compare two values:

Python Logical Operators

Logical operators are used to combine conditional statements:


Python Identity 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:

Python Membership Operators

Membership operators are used to test if a sequence is presented in an object:

Python Bitwise Operators

Bitwise operators are used to compare (binary) numbers:

Expression

An Expression is a sequence or combination of values, variables, operators and function calls that
always produces or returns a result value.

In the above example x, y and z are variables, 5 and 3 are values, = and + are operators.

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.

An Expression always evaluates (calculate) to itself.


Statements

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:

You can also concatenate a string into a variable.


For numbers, the + character works as a mathematical operator:

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:

String Formatting / Placeholders

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:

Format the price to be displayed as a number with two decimals:

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.

String (%s) and Float(%f)

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.

You might also like