[go: up one dir, main page]

0% found this document useful (0 votes)
66 views18 pages

Python Basics - Python Syntax: Whitespace and Indentation

Python uses whitespace and indentation to structure code. Keywords like False, None, and True have special meanings, and strings can be created using single, double, or triple quotes. Variables are labels assigned values, and different data types like integers, floats, strings, and Booleans can be used. Comparison and logical operators allow values to be compared and logical expressions to be evaluated.

Uploaded by

يُ يَ
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views18 pages

Python Basics - Python Syntax: Whitespace and Indentation

Python uses whitespace and indentation to structure code. Keywords like False, None, and True have special meanings, and strings can be created using single, double, or triple quotes. Variables are labels assigned values, and different data types like integers, floats, strings, and Booleans can be used. Comparison and logical operators allow values to be compared and logical expressions to be evaluated.

Uploaded by

يُ يَ
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Python Basics – Python Syntax

Whitespace and indentation


Python uses whitespace and indentation to construct the code structure.

# define main function to


print out something
def main():
i = 1
max = 10
while (i < max):
print(i)
i = i + 1

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.

The following shows the list of keywords in Python:

False class finally is return


None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise

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.

The following shows some examples of string literals:

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:

a is a variable which hold the string ‘hello world’, where the


print() function show what is inside the variable.

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.

If a string contains a single quote, you should place it in double-quotes:

when a string contains double quotes, we can use the single quotes:

Creating the Multiple Strings


To span a string multiple lines, you use triple-quotes “””…””” or ”’…”’

Concatenating Python Strings


Accessing String Elements
Since a string is a sequence of characters, you can access its elements using an index. The first character in the string
has an index of zero. (access by indexes)
Getting the Length of String
Using len() command

Slicing Strings
Slicing allows you to get a substring from a string.

Python Strings are Immutable.


Python strings are immutable. It means that you cannot change the string. For example, will get an error if you
update one or more characters in 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.

- Addition - subtraction - multiplication

- Division with reminder - Division show reminder only - Division no reminder

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)

Introduction to Python Boolean data type


In programming, you often want to check if a condition is true or not and perform some actions based on the result.

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 bool() function


To find out if a value is True or False
Python Type Conversion
Introduction to type conversion in Python:
To get input from users, you use the input() function. When you execute this code, it’ll prompt for input on the
Terminal.

However, the input() function returns a string, not an integer.

Since the input values are strings, you


cannot apply the arithmetic operator (+) to them. To solve this issue, you need to convert the strings to numbers
before performing calculations. To convert a string to a number, you use the int() function. More precisely, the
int() function converts a string to an integer.

The following example uses the int() function to convert the input strings to numbers:

Other types of conversion functions


Besides the int(str) functions, Python supports other types of conversion functions:

 float(str)  convert a string to a floating-point number.


 bool(val)  convert a value to a Boolean value, either True or False.
 str(val)  return the string representation of a value.

Getting the type of a value


To get the type of a value, you use the type(value) function.
Python Comparison Operators
Introduction to Python comparison operators
In programming, you often want to compare a value with another value. To do that, you use comparison operators.

Python has six comparison operators:

 Less than ( < )


 Less than or equal to (<=)
 Greater than (>)
 Greater than or equal to (>=)
 Equal to ( == )
 Not equal to ( != )

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.

Python Logical Operators


Summary: in this tutorial, you’ll learn about Python logical operators and how to use them to combine multiple
conditions.

Introduction to Python logical operators


Sometimes, we may want to check multiple conditions at the same time. To do so, you use logical operators.

Python has three logical operators:

 and
 or
 not

The and operator


The and operator checks whether two conditions are both True simultaneously, It returns True if both conditions are
True. And it returns False if either condition a or b is False.

The following table illustrates


the result of the and operator when combining two conditions:

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.

The not operator


 The not operator applies to one condition. And it reverses the result of that condition, True becomes False
and False becomes True.
 If the condition is True, the not operator returns False and vice versa.
 The following example uses the not operator. The price > 10 returns False, the not price > 10
returns True:

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.

If you don’t use the


indentation correctly, the
program will work
differently.

Python if…else statement


Typically, you want to perform an action when a condition is True and another action when the condition is False.
the if...else will execute the if-block if condition evaluates True. Otherwise, it’ll execute the else-block.

Python if…elif…else
statement
When we want to check multiple conditions and perform an action accordingly.

The if...elif...else statement checks each condition (if-


condition, elif-condition1, elif-condition2, …) in the order
that they appear in the statement until it finds the one that evaluates to True.
When the if...elif...else statement finds one, it executes the statement that follows the condition and skips
testing the remaining conditions. If no condition evaluates to True, the if...elif...else statement executes
the statement in the else branch.

Note: the else block is optional. If you omit it and no condition is True, the statement does nothing.

Python for Loop with Range


Introduction to Python for loop statement with the range() function
In programming, you often want to execute a block of code multiple times. To do so, you use a for loop.

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

To display 5 number from zero to 4 show 5 numbers from 1 to 5x


Specifying the starting value for the sequence
By default, the range () function uses zero as the starting number for the sequence. In addition, the range ()
function allows you to specify the starting number like this: range(start, stop)

Show 5 numbers from 1 to 5:

Specifying the increment for the sequence


By default, the range (start, stop) increases the start value by one in each loop iteration. To increase the
start value by a different number, you use the following function: range (start, stop, step).

Using Python for loop to calculate the sum of a sequence.


for loop statement to calculate the sum of numbers from 1 to 100:

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.

syntax of the Python while:

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

Python while statement examples


1) Simple Python while statement example
Uses a while statement to show 5 numbers from 0 to 4:

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:

Note: the command.lower() returns the command in lowercase


format. This allows you to enter the quit command such
as quit, QUIT, or Quit

Python Functions
What is a function?
A function is a named code block that performs a job or returns a value.

Why do you need functions in Python?


Sometimes, you need to perform a task multiple times in a program. And you don’t want to copy the code for that
same task all over places. To do so, you wrap the code in a function and use this function to perform the task
whenever you need it.

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.

Defining a Python function


A function has two main parts: a function definition and body.

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:

Passing information to Python functions


Suppose that you want to greet users by their names. To do it, you need to specify a name in
parentheses of the function definition as follows:
The name is called a function parameter or simply a parameter.
When you add a parameter to the function definition, you can use
it as a variable inside the function body. we can access the
name parameter only within the body of the greet () function,
not the outside.

When we call a function with a parameter, we need to pass the


information. For example:

The value that you pass into a function is called an argument. In this
example 'Yumna' is an argument.

Also, we can call the function by passing a variable into it:

Parameters vs. Arguments


Sometimes, parameters and arguments are used interchangeably. It’s important to distinguish between the
parameters and arguments of a function. A parameter is a piece of information that a function needs. And you
specify the parameter in the function definition. For example, the greet() function has a parameter called name.
An argument is a piece of data that you pass into the function. For example, the text string 'Yumna' is the function
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:

Python functions with multiple parameters


A function can have zero, one, or multiple parameters.

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.

Python Default Parameters


Helps on simplifying function calls.

Introduction to Python default parameters


When you define a function, we can specify a default value for each parameter. To specify default values for
parameters, we use the following syntax:

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

You might also like