Python Basic Syntax

Python Module and Import Syntax

What is a module

Consider a module to be the same as a code library. A file containing a set of functions you want to include in your application.

How to create a module

To create a module just save the code you want in a file with the file extension .py.

Use a Module by import

We can use a module by using the import statement. The three import syntax are:

  • import turtle – recommanded. Best option to avoid naming conflict
  • import turtle as t – good for small to medium size project. Module name t could be overridden later.
  • from turtle import * – good only for small project. All module methods will be loaded into global name space.
  • from turtle import Pen

You can choose to import only parts from a module, by using the from keyword.

from turtle import *
p = Pen()
print(type(p))
def Pen():
print('my pen')
Pen()

<class 'turtle.Turtle'>
my pen

Namespace

Everything in Python is an object. Name is a way to access the underlying object. A namespace is a collection of names.

** Keypoints for namespace:**

  • A GLOBAL namespace containing all the built-in names is created when we start the Python and exists as long as the program runs.
  • Different namespaces can co-exist at a given time but are completely isolated.
  • Each module creates its own global namespace.

Namespace vs. Symbol Table

  • A symbol table is a data structure maintained by a compiler which contains all necessary information about the program. These include variable names, methods, classes, etc.
  • Symbol table is not namespace, but it’s related.
  • There are mainly two kinds of symbol table: Local symbol table and Global symbol table.
  • Global symbol table stores all information related to the global scope of the program, and is accessed in Python using globals() funtion.
  • Local symbol table stores all information related to the local scope of the program, and is accessed in Python using locals() method.

Function dir()

There is a built-in function to list all the function names (or variable names) in a module.

Function globals()

The globals() function returns the dictionary of the current global symbol table.

Function locals()

len(dir())
len(globals())
len(locals())

Python Variables

Python variables are containers to hold data values. Unlike other programming languages, Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.

Variable naming convention:

  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive (age, Age and AGE are three different variables)

Assign Value to Multiple Variables

comments..

”’
first line comments
second line comments
thrid line comments
'''
print(msg)
_a = 1
a4 = 'test'
A4 = 2

Python Comments

  • 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.
  • Comments starts with a #, and Python will ignore them

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.

 Python Data Type

Strings

Function print() is used to print output.

print("Hello World")

Variable – a place to hold value

A variable name can be used to hold the text value and pass into print function as parameter. Variable names need to start with letter or underscore, cannot start with number. But number can be inside variable names.

text = 'Hello World'
print(text)

Single Quote / Double Quote

There is no difference in string using either of them. But we need to use the same quote for a string. If there is quote inside the string itself, we need to use a different quote or to escape the string using \.

text = "Jenny's Home"
txt2 = 'Jenny\'s Home'
print(f'{text} {txt2}')

Jenny's Home Jenny's Home

Multi-Quotes

We can use string with multiple lines by using three single/double quotes before and after the lines.

multi_line = '''
This is the first line.
This is the second line.
This is the third line
'''
print(multi_line)

This is the first line.
This is the second line.
This is the third line

Find out length of a stirng

We can use function len() to find out how many characters are there in a string.

length = len(multi_line)
length # 85

Using index to access each letter in a string

Format var[index] is used to access each character of a string. Index always starts with ZERO, not one. So var[0] returns the first character of stirng var. And var[len(var)-1] returns the last character of the string.

text = 'Hello World'
print('The fist character of text is:')
print(text[0])
print('The last character of text is:')
print(text[len(text)-1])

The fist character of text is:
H
The last character of text is:
d

Slice string using syntax str[start-index : end-index]

We can get part of string by using the format of str[0:5], which mean to start with the fist character, and stop at the fifth character (index 4).

text = 'Presidential Election 2020'
new_text = text[0:5]
print(new_text) # Presi

If the first index number is ignored, then we use 0 as the default starting index. If the second index number is ignored, then we will go to the end of the string.

text = 'Presidential Election 2020'
new_text = text[:5]
print(new_text)
new_text = text[5:]
print(new_text)

Presi
dential Election 2020

Userful String Methods

lower() / upper() / count() / find() / replace() / + operator

print(text.lower())
print(text.upper())
print(text.count('e'))
print(text.find('Election'))
print(text.find('election'))
print(text.replace('tion', 'ted'))
text = 'Biden won the ' + text
print(text)

presidential election 2020
PRESIDENTIAL ELECTION 2020
3
13
-1
Presidential Elected 2020
Biden won the Presidential Election 2020

String Formatting: Place holder with {} & f string

winner = 'Biden'
text = 'Presidential Election 2020'
text = f'{winner}
won the {text}'
print(text)

Biden won the Presidential Election 2020

System Function dir()

dir(text)

['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmod__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'capitalize',
 'casefold',
 'center',
 'count',
 'encode',
 'endswith',
 'expandtabs',
 'find',
 'format',
 'format_map',
 'index',
 'isalnum',
 'isalpha',
 'isascii',
 'isdecimal',
 'isdigit',
 'isidentifier',
 'islower',
 'isnumeric',
 'isprintable',
 'isspace',
 'istitle',
 'isupper',
 'join',
 'ljust',
 'lower',
 'lstrip',
 'maketrans',
 'partition',
 'replace',
 'rfind',
 'rindex',
 'rjust',
 'rpartition',
 'rsplit',
 'rstrip',
 'split',
 'splitlines',
 'startswith',
 'strip',
 'swapcase',
 'title',
 'translate',
 'upper',
 'zfill']

System Function help()

help(str.lower)

Help on method_descriptor:

lower(self, /)
    Return a copy of the string converted to lowercase.

Numeric Data Type – Integers and Floats

Integer is a whole number and float is a decimal one.

num = 5
print(type(num))
num = 5.0
print(type(num))

<class 'int'>
<class 'float'>

Arithmetic Operators

  • Additioin: 1 + 2
  • Substration: 3 – 1
  • Multiplication: 4 * 5
  • Division: 6 / 2
  • Floor Division: 9 // 4
  • Exponent: 2 ** 3
  • Modules: 9 % 3

Comparisons

  • Equal: 4 == 3
  • Not Equal: 4 != 3
  • Greater Than: 4 > 3
  • Less Than:      4 < 3
  • Greater or Equal:  4 >= 3
  • Less or Equal:    4 <= 3

Order of operations

Just like in math, order of operation can be changed by adding parentheses – ().

Operator +=, -=, *=, /=

num = 2
num += 10
print(num)
num -= 2
print(num)
num *= 2
print(num)
num /= 5
print(num)

12
10
20
4.0

Common Functions – abs(), round()

abs() – return absolute value of an integer
round() – return the round up integer

num = abs(-11)
print(num)
num /= 3
print(num)
num = round(num)
print(num)

11
3.6666666666666665
4

Convert String to Number

String could be casting into integer by function int().

a = '1234'
b = '2345'
print(int(a) + int(b)) # result is 3579

Boolean

Booleans represent one of two values: True or False. The usage of boolean is that in programming we often need to know if an expression is True or False. We can evaluate any expression in Python, and get one of two answers, True or False.

When we compare two values, the expression is evaluated and Python returns the Boolean answer:

x = max(22, 36)
y = min(34, 105)
print(f'{x} - {y}')
print(x > y)

36 - 34
True

What values are True

  • Almost any value is evaluated to True if it has some sort of content.
  • Any string is True, except empty strings.
  • Any number is True, except 0.
  • Any list, tuple, set, and dictionary are True, except empty ones.

What Values are False

In fact, there are not many values that evaluates to False, except empty values, such as ( ), [ ], { }, “”, the number 0, and the value None. And of course the value False evaluates to False.

if "False": print('String "False" is evaluated to True')
if "False" == True: print('"False" == True')
else: print('Statement: ("False" == True) is evaluated to False ')
if 1 == True: print('1 == True')
if 0 == False: print('0 == False')

String "False" is evaluated to True
Statement: ("False" == True) is evaluated to False 
1 == True
0 == False