Decision Making Tools
Lecture # 02
1
Contents
● Basics of Python
● White Spaces and Indentation
● Comments
● Python docstring
● Identifiers
● String literals
● Variables
● Python strings
2
Basics of Python
● Do you have any idea about the variables?
● In other programming languages like C, C++, and Java, you will need to
declare the type of variables.
● In python, we do not need to declare the variables.
● We just type the variable(s) and assign the value(s) to it/them.
● It will be automatically known that the variable is of type int, char, float,
and string.
3
Whitespaces and indentation
● In other programming languages such
as C, C++,C# etc, all the statements
are separated by a semicolon (;).
● However, Python uses whitespaces
and indentation for the construction of
code structure.
● The meaning of the code isn’t
important to you now. Please pay
attention to the code structure
instead.
4
Advantages:
By using whitespace and indentation to organize the code, Python code gains the
following advantages:
● First, you’ll never miss the beginning or ending code of a block like in other
programming languages such as Java or C#.
● Second, the coding style is essentially uniform. If you have to maintain
another developer’s code, that code looks the same as yours.
● Third, the code is more readable and clear in comparison with other
programming languages.
5
Comments
● The comments are as important as the code because they describe why a
piece of code was written.
● Python interpreter ignores the comments while executing the code.
● In Python, a single-line comment begins with a hash (#) symbol followed by
the comment. For example:
○ # This is a single line comment in Python
6
Python docstrings
● Python provides two kinds of docstrings: one-line docstrings and multi-line
docstrings.
One-line docstrings:
● A one-line docstring fits one line. A one-line docstring begins with triple quotes (""")
and also ends with triple quotes (""").
○ def quicksort():
""" sort the list using quicksort algorithm """…
Multi-line docstrings:
● A multi-line docstring can span multiple lines.
○ def increase(salary, percentage, rating):
○ """ increase salary base on rating and percentage
○ rating 1 - 2 no increase
○ rating 3 - 4 increase 5%
○ rating 4 - 6 increase 10%
○ """
7
Continuation of statements
● Python uses a newline character to separate statements. It places each statement on
one line.
● However, a long statement can span multiple lines by using the backslash (\)
character.
○ if (a == True) and (b == False) and \
○ (c == True):
○ print("Continuation of statements")
8
Identifiers
● Identifiers are names that identify variables, functions, modules, classes, and
other objects in Python.
● The name of an identifier needs to begin with a letter or underscore (_).
The following characters can be alphanumeric or underscore.
● Python identifiers are case-sensitive. For example, the counter and Counter
are different identifiers.
● You can not use python keywords for naming identifiers
9
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
● Python is a growing and evolving language. So its keywords will keep increasing and
changing.
● Python provides a special module for listing its keywords called keyword.
○ import keyword
○ print([Link])
10
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.
○ s = 'This is a string'
○ print(s)
○ s = "Another string using double quotes"
○ print(s)
○ s = ''' string can span
○ multiple line '''
○ print(s)
11
Variables
● To develop a program, you need to manage values, a lot of them.
● To store values, you use variables.
● In Python, a variable is a label that you can assign a value to it. And a variable is
always associated with a value. For example:
○ message = 'Hello, World!'
Output
○ print(message)
○ message = 'Good Bye!' Hello, World!
○ print(message) Good Bye!
In this example,what do you think which one is a variable?
A variable can hold various values at different times. And its value can change
throughout the program.
12
Creating variables
● To define a variable, you use the following syntax:
○ variable_name = value
● The = is the assignment operator. In this syntax, you assign a value to the variable_name.
● The value can be anything like a number, a string, etc., that you assign to the variable.
● The value can be anything like a number, string, etc., that you assign to the variable.
● The following defines a variable named counter and assigns the number 1 to it:
○ counter = 1
13
Naming variables
● Naming variable(s) requires knowledge about some rules. If you don’t follow them,
you’ll get error(s).
● The following are the variable rules that you should keep in mind:
○ Variable names can contain only letters, numbers, and underscores (_). They
can start with a letter or an underscore (_), not with a number.
○ Variable names cannot contain spaces. To separate words in variables, you
use underscores for example sorted_list.
○ Variable names cannot be the same as keywords, reserved words, and built-
in functions in Python.
● Variable names should be concise and descriptive. For example, the active_user
variable is more descriptive than the au.
● Use underscores (_) to separate multiple words in the variable names.
14
A simple Example
# Python program to declare variables
myNumber = 3
Output
print(myNumber) 3
4.5
myNumber2 = 4.5 Hello World!
print(myNumber2)
myNumber ="Hello World!"
print(myNumber)
15
Introduction to Python string
● Up to this point, you probably know what is string and how to declare a
string.
○ A string is a series of characters. In Python, anything inside quotes is a
string. And you can use either single or double quotes. For example:
○ message = 'This is a string in Python'
○ message = "This is also a string"
● Creating multiline strings:
○ To span a string multiple lines, you use triple-quotes “””…””” or ”’…”’. For example:
○ help_message = '''
○ Usage: mysql command
○ -u username
○ -p password
○ '''
○ print(help_message)
16
String with -f
● Sometimes, you want to use the values of variables in a string.
● For example, you may want to use the value of the name variable inside the
message string variable:
○ name = ‘kamran'
○ message = 'Hello'
● Place the letter f before the opening quotation mark and put the brace around the
variable name:
○ name = ‘kamran'
○ message = f'Hello {name}'
○ print(message)
● Python will replace the {name} by the value of the name variable.
Output: Hello kamran!
17
Concatenating Python strings
● When you place the string literals next to each other, Python
automatically concatenates them into one string. For example:
○ greeting = 'Good' 'Morning!'
○ print(greeting) Output: Good Morning!
● To concatenate two string variables, you use the operator +:
○ greeting = 'Good '
○ time = 'Afternoon'
○ greeting = greeting + time + '!'
Output: Good
○ print(greeting)
Afternoon!
18
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. For
example:
○ str = "Python String"
○ print(str[0]) # P
○ print(str[1]) # y
● If you use a negative index, Python returns the character starting from the
end of the string. For example:
○ str = "Python String"
○ print(str[-1]) # g
○ print(str[-2]) # n
● The following illustrates the indexes of the string "Python String":
○ +---+---+---+---+---+---+---+---+---+---+---+---+---+
○ | P | y | t | h | o | n | | S | t | r | i | n | g |
○ +---+---+---+---+---+---+---+---+---+---+---+---+---+
○ 0 1 2 3 4 5 6 7 8 9 10 11 12
○ -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
19
Getting length of a string
● To get the length of a string, you use the len() function. For example:
○ str = "Python String"
○ str_len = len(str)
Output: 13
○ print(str_len)
● Slicing strings
● Slicing allows you to get a substring from a string. For example:
○ str = "Python String"
○ print(str[0:2]) Output: Py
● The syntax for slicing is as follows:
○ string[start:end]
20
Python strings are immutable
● Python strings are immutable. It means that
Error:
you cannot change the string. Traceback (most recent call last):
File "[Link]", line 2, in <module>
● For example, you’ll get an error if you str[0] = 'J'
update one or more characters in a string: TypeError: 'str' object does not support
○ str = "Python String" item assignment</module>
○ str[0] = 'J'
● When want to modify a string, you need to
create a new one from the existing string. Output: Jython String
For example:
○ str = "Python String"
○ new_str = 'J' + str[1:] 21
○ print(new_str)
Summary
● In Python, a string is a series of characters. Also, Python strings are immutable.
● Use quotes, either single quotes or double quotes to create string literals.
● Use the backslash \ to escape quotes in strings
● Use f-strings to insert substitute variables in literal strings.
● Place literal strings next to each other to concatenate them. And use the +
operator to concatenate string variables.
● Use the len() function to get the size of a string.
● Use the str[n] to access the character at the position n of the string str.
● Use slicing to extract a substring from a string.
22