Python Basics - Python Syntax: Whitespace and Indentation
Python Basics - Python Syntax: Whitespace and Indentation
At the end of each line, you don’t see any semicolon to terminate the statement. And the code uses indentation to
format the code.
Keywords
Some words have special meanings in Python. They are called keywords.
To find the current keyword list, you use the following code:
String Literals
Python uses single quotes ('), double quotes ("), triple single quotes (''') and triple-double quotes (""") to denote a
string literal.
The string literal need to be surrounded with the same type of quotes. For example, if you use a single quote to start
a string literal, you need to use the same single quote to end it.
Python Variable
What is a variable in Python? In Python, a variable is a label that you can assign a value to it. And a variable is always
associated with a value. To store values, we use variables.
Example:
Creating Variables
The following syntax is an example to define a variable:
= the assignment operator, value could be anything (Number, string, etc) that assign to variable
Python string
A string is a series of characters. In Python, anything inside quotes is a string. And we can use either single or double
quotes.
when a string contains double quotes, we can use the single quotes:
Slicing Strings
Slicing allows you to get a substring from a string.
When want to modify a string, will need to create a new one from the existing string.
Python Numbers
Python supports integers, floats, and complex numbers.
Integers
The integers are numbers such as -1, 0, 1, 2, and 3, .. and they have the type of int.
You can use Math operators like +, -, *, and / to form expressions that include integers.
Exponent
Floats
Any number with a decimal point is a floating-point number. The term float means that the decimal point can appear
at any position in a number. In general, you can use floats like integers.
Python Boolean
Type of data (data type)
To represent true and false, Python provides you with the Boolean data type. The Boolean value has a technical
name as bool. The Boolean data type has two values: True and False.
Note: the Boolean values True and False start with the capital letters (T) and (F).
The following example uses the int() function to convert the input strings to numbers:
These comparison operators compare two values and return a Boolean value, either True or False. We can use
these comparison operators to compare both numbers and strings.
and
or
not
a b a and b
True True True
True False False
False False False
False True False
As you can see from the table, the condition a and b only return True if both conditions evaluate to True.
The or operator
Similar to the and operator, the or operator checks multiple conditions. But it returns True when either or both
individual conditions are True
The following table illustrates the result of the or operator when combining
two conditions
a b a or b
True True True
True False True
False False False
False True True
The or operator returns False only when both conditions are False.
NOT COMPLETED
If statement
The simple Python if statement
we use the if statement to execute a block of code based on a specified condition. The syntax of the if statement
is as follows:
The if statement checks the condition first. If the condition evaluates to True, it executes the statements in the
if-block. Otherwise, it ignores the statements.
Note: the colon (:) that follows the condition is very important. If you forget it, you’ll get a syntax error.
Python if…elif…else
statement
When we want to check multiple conditions and perform an action accordingly.
Note: the else block is optional. If you omit it and no condition is True, the statement does nothing.
In this syntax, the index is called a loop counter. And n is the number of times
that the loop will execute the statement.
The name of the loop counter doesn’t have to be index, you can use
whatever name you want.
The range() is a built-in function in Python. It’s like the print()
function in the sense that it’s always available in the program.
The range(n) generates a sequence of n integers starting at zero. It
increases the value by one until it reaches n.
So the range(n) generates a sequence of numbers: 0,1, 2, …n-1. Note that
it’s always short of the final number (n).
How it works.
First, the sum is initialized to zero.
Second, the sum is added with the number from 1 to 100 in each iteration.
Finally, show the sum to the screen.
Python While
Use the Python while loop statement to execute a code block as long as a condition is True.
Introduction to the Python while statement
Python while statement allows you to execute a code block repeatedly as long as a condition is True.
The condition is an expression that evaluates to a Boolean value, either True or False.
The while statement checks the condition at the beginning of each iteration. It’ll execute the body as long as
the condition is True.
In the body of the loop, you need to do something to stop the loop at some time.
Otherwise, you’ll get an indefinite loop that will run forever until you close the application.
Because the while statement checks the condition at the beginning of each iteration, it’s called a pretest
loop.
If the condition is False from the beginning, the while statement will do nothing.
Flowchart:
How it works:
First, define two variables called max and counter with the initial values of five and zero.
Second, use the while statement with the condition counter < max. It’ll
execute the loop body as long as the value of the counter is less than the
value of max.
Third, show the value of the counter variable and increase it by one in
each iteration. After five iterations, the value of the counter is 5,
which makes the condition counter < max evaluates to False and hence the
loop stops.
2) Using the Python while statement to build a simple command prompt program
The following example uses the while statement to prompt users for input and echo the command that you
entered back. It’ll run as long as you don’t enter the quit command:
Python Functions
What is a function?
A function is a named code block that performs a job or returns a value.
For example, whenever you want to display a value on the screen, you need to call the print () function. Behind
the scene, Python runs the code inside the print () function to display a value on the screen.
In practice, we use functions to divide a large program into smaller and more manageable parts. The functions will
make your program easier to develop, read, test, and maintain. The print () function is one of many built-in
functions in Python. It means that these functions are available everywhere in the program.
1) Function definition
A function definition starts with the def keyword and the name of the function (greet), If the function needs
some information to do its job, you need to specify it inside the parentheses (). The greet function in this example
doesn’t need any information, so its parentheses are empty. The function definition always ends in a colon (:).
2) Function body
All the indented lines that follow the function definition make up the function’s body. The text string surrounded by
triple quotes is called a docstring. It describes what the function does. Python uses the docstring to generate
documentation for the function automatically. The line print('Hi') is the only line of actual code in the function
body. The greet () function does one task: print('Hi').
Calling a function
When we want to use a function, will need to call it. A function call instructs Python to execute the code
inside the function.
To call a function, write the function’s name, followed by the information that the function needs in
parentheses.
The following example calls the greet () function. Since the greet () function
doesn’t need any information, you need to specify empty parentheses like this:
The value that you pass into a function is called an argument. In this
example 'Yumna' is an argument.
Returning a value
A function can perform a task like the greet() function. Or it can return a value. The value that a function returns is
called a return value. To return a value from a function, we use the return statement inside the function body.
The following example modifies the greet () function to return an output instead of displaying it on the screen:
The following example defines a function called sum () that calculates the sum of two numbers:
In this example, the sum () function has two parameters a and b, and returns the
sum of them.
When a function has multiple parameters, you need to use a comma to
separate them.
When you call the function, you need to pass all the arguments. If you
pass more or fewer arguments to the function, you’ll get an error.
In this syntax, you specify default values (value2, value3, …) for each parameter using the assignment
operator (=). When you call a function and pass an argument to the parameter that has a default value, the
function will use that argument instead of the default value. However, if you don’t pass the argument, the function
will use the default value.
To use default parameters, you need to place parameters with the default values after other parameters. Otherwise,
you’ll get a syntax error.
Multiple default parameters