Sunteți pe pagina 1din 34

01/03/2020 PyLecture2

ArtificiAl
intelligence
with python

file:///C:/Users/Zayan/Desktop/PyLecture2.html 1/6
01/03/2020 PyLecture2

Lecture No 1

Python Programming
Programming Fundamentals
Object Oriented Programming
Data Structures

Python Programming Fundamentals


Python for Windows

1 - python.org

https://www.python.org/ (https://www.python.org/) - Python Official Link


https://www.python.org/downloads/release/python-381/ (https://www.python.org/downloads/release/python-
381/) - Release Date: Dec. 18, 2019
Windows x86-64 executable installer - 26.3 MB or
Windows x86 executable installer - 25.2 MB
Python 3.8.1 Installer
Python Programming Language
Python Standard Libraries
Pip (Download & Install other Python packages) - https://pypi.org/ (https://pypi.org/)
IDLE & tkinter
Python Official Documentation

2 - vs code

https://code.visualstudio.com/ (https://code.visualstudio.com/) - Visual Studio Code Official Link


https://code.visualstudio.com/Download (https://code.visualstudio.com/Download) - Release Date: January
2020 (version 1.42)
Windows 7, 8, 10 (User Installer) 64 bit - 56.9 MB or
Windows 7, 8, 10 (User Installer) 32 bit - 54.9 MB
VS Code Extensions
Python (Microsoft)
vscode-icons
Debugger for Chrome
Getting Started with Python in VS Code
https://code.visualstudio.com/docs/python/python-tutorial
(https://code.visualstudio.com/docs/python/python-tutorial)

Program in Python 3.x


Windows-cmd, Python-interpreter & IDLE
file:///C:/Users/Zayan/Desktop/PyLecture2.html 2/6
01/03/2020 PyLecture2

Windows-cmd

In [1]:

(AMD64)] on win32

In [2]:

Hello, World!

Happy Learning

Lecture No 2

Python Programming Fundamentals

First Program in Python - 'Hello, World!'


Python-interpreter, IDLE & VS Code

Python Interpreter
In [1]:

In [2]:

Hello, World!

'Hello, World!'
print ('Hello, World!')
We are using the 'print' statement
Text strings (str) are always put in 'single' or "double" quotes
Python interpreter can be used as a calculator
Try the following one by one:
5 + 2, 5 - 2, 5 * 2, 5 ** 2, 5 / 2, 5 % 2, 5.0 / 2, 5 / 2.0, 5.0 / 2.0
+, -, * etc. are operators
5 and 2 are operands

file:///C:/Users/Zayan/Desktop/PyLecture2.html 3/6
01/03/2020 PyLecture2

In [3]:

Hello, World!
In [4]:

Docstring:

print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.


Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout. sep:
string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
Type: builtin_function_or_method

In [5]: print("Hello, World!")

Hello, World!

Python simple calculator

In [6]: 5 + 2

Out[6]: 7

In [7]: 5 - 2

Out[7]: 3

In [8]: 5 * 2

Out[8]: 10

In [9]: 5 ** 2

Out[9]: 25

In [10]: 5 / 2

Out[10]: 2.5

In [11]: 5 % 2

Out[11]: 1

In [12]: 5.0 / 2

Out[12]: 2.5

file:///C:/Users/Zayan/Desktop/PyLecture2.html 4/6
01/03/2020 PyLecture2

In [13]: 5 / 2.0

Out[13]: 2.5

In [14]: 5.0 / 2.0

Out[14]: 2.5

In [15]: 5 // 2

Out[15]: 2

Values and Types


Programs work with values e.g. 5, 2, 'Hello, World!'
Values can be of different types
Basic Data Types (value types) are given below:
Numbers (int, float, bool)
Strings (str)
type(5), type(2), type(5.0), type(2.0), type('Hello, World!')
type('5'), type('2.0'), type(True), type(False)
Values sometimes can be converted from one type to the other

In [16]:

Out[16]: str

In [17]:

Out[17]: float

In [18]:

Out[18]: int

In [19]:

Out[19]: int

In [20]:

Out[20]: float

In [21]:

Out[21]: str

file:///C:/Users/Zayan/Desktop/PyLecture2.html 3/6
01/03/2020 PyLecture2

In [22]:

Out[22]:
bool

Variables

Variables hold values


Variables can be assigned any values
x = 2 (x takes the value of 2 or x is assigned the value of 2)
x is the variable and 2 is the value assigned to this variable
y = 'Hello, World!'
type(x), type(y)
Variable names have to start with a letter, generally use lowercase and underscores
and can contain both letters and numbers

In [23]: x = 2

In [24]: print(x)

In [25]: type(x)

Out[25]: Int
In [26]:

In [27]:

Hello, World!

In [28]:

Out[28]: str

In [29]:

In [30]:

In [31]:

In [32]:

In [33]:

Out[33]: str

file:///C:/Users/Zayan/Desktop/PyLecture2.html 4/6
01/03/2020 PyLecture2

In [34]: value = int('10')

In [35]: print(value)

10

In [36]: type(value)

Out[36]: Int

In [37]:

In [38]:

10.0

In [39]:

Out[39]: float

Interactive vs Script Mode

Try the following in both modes:


4*3
print (4 * 3)

In [40]:

Out[40]: 12

In [41]:

12

Ctrl + Z then Enter or exit() then Enter

VS Code
Link: https://code.visualstudio.com/ (https://code.visualstudio.com/)
Python extension for Visual Studio Code: https://marketplace.visualstudio.com/items?itemName=ms-
python.python (https://marketplace.visualstudio.com/items?itemName=ms-python.python)

file:///C:/Users/Zayan/Desktop/PyLecture2.html 5/6
01/03/2020 PyLecture3

Getting Started with Python in VS Code

https://code.visualstudio.com/docs/python/python-tutorial (https://code.visualstudio.com/docs/python/python-
tutorial)

Create a Python Hello World Program in VS Code

Open VS Code
Close Welcome Screen
Click Explorer (Ctrl + Shift + E)
Open Folder
Click New File with .py
Example: main.py
Write Hello World Python Program
Ctrl + S
Ctrl + `
python main.py
Enter

Note:
Install Python Extension
Ctrl + Shift + P - Select Interpreter

Lecture No 3

Python Programming Fundamentals


Python Built-in Functions

Print Function

In [1]: # help(print)

In [2]: print?

Docstring:
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

Prints the values to a stream, or to sys.stdout by default.


Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
Type: builtin_function_or_method
file:///C:/Users/Zayan/Desktop/PyLecture3.html 6/17
01/03/2020 PyLecture3

In [3]:

In [4]:

In [5]: print(end='')

In [6]: print('Hello, ')


print('World!')

Hello,
World!

In [7]: print('Hello, ', end="")


print('World!')

Hello, World!

In [8]:

45
(6-9j)
True
245.8
Python
Programming
20 True
ML NLP
<class 'str'>

In [9]:

AI AP

In [10]:

AIAP

In [11]:

AI - AP

file:///C:/Users/Zayan/Desktop/PyLecture3.html 7/17
01/03/2020 PyLecture3

In [12]:

AI & AP

In [13]: x = 35

In [14]:

35
25.8
SIn [15]:

35 25.8

In [16]:

In [17]:

5 10 20.9

In [18]:

print(5 + 10)
print(8 / 5)
print(8 // 5)
print(3 ** 4)

5
15
1.6
1
81

Basic Data Types Functions


Integer, Complex, Boolean, Floating, String

Integer

In [19]: v1 = 10

In [20]:

file:///C:/Users/Zayan/Desktop/PyLecture3.html 8/17
01/03/2020 PyLecture3

In [21]: print(v3)

25

In [22]: v4 = int('34')

In [23]: print(v4)

34

In [24]: v5 = int(True)

In [25]: print(v5)

In [26]: v6 = int(False)

In [27]: print(v6)

In [28]:

Init signature: int(self, /, *args, **kwargs)


Docstring:
int([x]) -> integer
int(x, base=10) -> integer

Convert a number or string to an integer, or return 0 if no arguments are


given. If x is a number, return x. int (). For floating point numbers,
this truncates towards zero.

If x is not a number or if base is given, then x must be a string,


bytes, or bytearray instance representing an integer literal in the
given base. The literal can be preceded by '+' or '-' and be surrounded
by whitespace. The base defaults to 10. Valid bases are 0 and 2-36.
Base 0 means to interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4
Type: type
Subclasses: bool, IntEnum, IntFlag, _NamedIntConstant, Handle

Complex

In [29]:

In [30]:

(4+8j)

file:///C:/Users/Zayan/Desktop/PyLecture3.html 9/17
01/03/2020 PyLecture3

In [31]:

In [32]:

Init signature: complex(real=0, imag=0) Docstring:

Create a complex number from a real part and an optional imaginary part.

This is equivalent to (real + imag*1j) where imag defaults to 0.


Type: type

Subclasses:

Boolean

In [33]: b1 = True
b2 = False

In [34]:

In [35]:

In [36]: print(b4)

True

In [37]: bool?

Init signature: bool(self, /, *args, **kwargs)


Docstring:
bool(x) -> bool

Returns True when the argument x is true, False otherwise.


The builtins True and False are the only two instances of the class bool.
The class bool is a subclass of the class int, and cannot be subclassed.
Type: type

Subclasses:

Float

In [38]:

In [39]:

In [40]:

In [41]: print(f3)

47.0

In [42]: f4 = float('37.9')

file:///C:/Users/Zayan/Desktop/PyLecture3.html 10
01/03/2020 PyLecture3

In [43]: print(f4)

37.9

In [44]: float?

Init signature: float(x=0, /)


Docstring: Convert a string or number to a floating point number, if pos
sible.
Type: type
Subclasses:

String Manipulation
Display String

In [45]: print('python programming')

python programming

In [46]: print("python programming")

python programming

In [47]: print('''python programming''')

python programming

In [48]: print("""python programming""")

python programming

In [49]: print('Basic "Python" Programming')

Basic "Python" Programming

In [50]: print("Basic 'Python' Programming")

Basic 'Python' Programming

In [51]: print("Basic 'Python' 'Programming'")

Basic 'Python' 'Programming'

In [52]: print('''Basic 'Python' "Programming"''')

file:///C:/Users/Zayan/Desktop/PyLecture3.html 11
01/03/2020 PyLecture3

Basic 'Python' "Programming"

String Variables

In [53]:

In [54]:

In [55]:

In [56]:

python for data science

In [57]:

In [58]:

In [59]:

In [60]:

In [61]:

In [62]: s9 = str('101')

In [63]: print(type(s9))

<class 'str'>

In [64]: print(s9)

101
In [65]:

Init signature: str(self, /, *args, **kwargs)


Docstring:

str(object='') -> str


str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or


errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object. str () (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.
Type: type
Subclasses: _rstr, LSString, include, SortKey
file:///C:/Users/Zayan/Desktop/PyLecture3.html 12
01/03/2020 PyLecture3

String Operations

Strings are immutable


We can perform certain operations on strings
Try the following:
'5' – '2',
'hello' – 'world'
'hello' + 'world'
'hello' + ' ' + 'world'
'hello' * 3
'hello' * 'hello'
len('hello')

In [66]:

In [67]:

In [68]:

Out[68]: 'helloworld'

In [69]:

Out[69]: 'hello world'

In [70]:

Out[70]: 'hellohellohello'

In [71]:

Out[71]: 'hello hello hello '

file:///C:/Users/Zayan/Desktop/PyLecture3.html 13
01/03/2020 PyLecture3

In [72]:

In [73]:

Out[73]: 5

The in Operator
Try the following:
'e' in 'hello'
'a' in 'hello'

In [74]: 'e' in 'hello'

Out[74]: True

In [75]: 'a' in 'hello'

Out[75]: False

Indexing and Slicing and Other String Operations

Indexing and Slicing are very common String Operations


Each character in a string is identified by an index
Index starts from 0 (not 1)
Slicing is when we select multiple characters from a string
m1 = 'hello', m1[0] will give us 'h'
m2 = 'hello', m2[:2] gives us 'he'
Try: m3 = 'abcdefghij', m3[2:8:2]

In [76]: m1 =

In [77]:

Out[77]: 'h'

In [78]:

Out[78]:
'he'

In [79]: m3 =

In [80]:

Out[80]: 'ceg'

In [81]:

In [82]:
file:///C:/Users/Zayan/Desktop/PyLecture3.html 14
01/03/2020 PyLecture3

In [83]:

Out[83]: 'p'

In [84]:

Out[84]: 'n'

In [85]:

Out[85]: 'p'

In [86]:

Out[86]: 'n'

In [87]:

In [88]:

Out[88]: 18

In [89]:

Out[89]: 'thon programming'

In [90]:

Out[90]: 'thon programming'

In [91]: course[2:len(course)]

Out[91]: 'thon programming'

In [92]: course[2:19]

Out[92]: 'thon programming'

In [93]: course[:18]

Out[93]: 'python programming'

In [94]: course[:len(course)]

Out[94]: 'python programming'

In [95]: course[2:5]

Out[95]: 'tho'

In [96]: course[:]

Out[96]: 'python programming'

In [97]: course[0: len(course): 1]

file:///C:/Users/Zayan/Desktop/PyLecture3.html 15
01/03/2020 PyLecture3

Out[97]: 'python programming'

In [98]: course[0: 18: 2]

Out[98]: 'pto rgamn'

In [99]: course[ : : ]

Out[99]: 'python programming'

In [100]: course[ : : -1]


Out[100]: 'gnimmargorp nohtyp'

In [101]: course[:-2]

Out[101]: 'python programmi'

file:///C:/Users/Zayan/Desktop/PyLecture3.html 16
01/03/2020 PyLecture3

Basic Data Type Conversions


In [102]: a = 10.5

In [103]: print(type(a))

<class 'float'>

In [104]: b = int(a)

In [105]: print(type(b))

<class 'int'>

In [106]: print(b)

10
In [107]: n1 = int(45.6)

In [108]: print(n1)

45

In [109]: # n2 = int('45.6') # invalid literal for int() with base 10: '45.6'

In [110]: n2 = int('45')

In [111]: print(n2)

45

In [112]: print(type(n2))

<class 'int'>
In [113]: n3 = float(45)

In [114]: print(n3)

45.0

In [115]: n4 = float('35.6')

In [116]: print(n4)

35.6

In [117]: n5 = str(45)

file:///C:/Users/Zayan/Desktop/PyLecture3.html 13
01/03/2020 PyLecture3

In [118]: n6 = str(45.7)

In [119]: print(n6)

45.7

In [120]: n7 = str(True)

In [121]: print(n7)

True

Built-in String Methods


Below are some of String Methods:
upper
lower
swapcase
replace
count
capitalize
find
strip
startswith
Method call is know as Invocation
Multiple methods can be invoked in a single line
Try the following code:
x = 'hello world'
x.startswith('h')
x.startswith('H')
x.capitalize().startswith('H')

In [122]: s = 'string'

In [123]: print(dir(s))

[' add ', ' class ', ' contains ', ' delattr ', ' dir ', ' doc ',
' eq ', ' format ', ' ge ', ' getattribute ', ' getitem ', ' getne
wargs ', ' 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', 'c
enter', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'forma
t_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'is
identifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'is
upper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replac
e', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 's
plitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper',
'zfill']

file:///C:/Users/Zayan/Desktop/PyLecture3.html 14
01/03/2020 PyLecture3

String 45 Methods

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'

In [124]: # s.

In [125]: # s.<tab_press>

In [126]: # str.<tab_press>

String Upper Method

In [127]: str.upper?

Signature: str.upper(self, /)

Docstring: Return a copy of the string converted to uppercase.


Type: method_descriptor

The string upper() method converts all lowercase characters in a string into uppercase characters and returns it.

The syntax of upper() method is:


str.upper()

String upper() Parameters()

The upper() method doesn't take any parameters.

Return value from String upper()

The upper() method returns the uppercased string from the given string. It converts all lowecase characters to
uppercase.

If no lowercase characters exist, it returns the original string.

Example: Convert a string to uppercase

In [128]: str.upper('python programming')


Out[128]: 'PYTHON PROGRAMMING'

In [129]: s1 = 'python programming'

In [130]: s1.upper()

Out[130]: 'PYTHON PROGRAMMING'

In [131]: s1

Out[131]: 'python programming'

file:///C:/Users/Zayan/Desktop/PyLecture3.html 15
01/03/2020 PyLecture3

s2
In [132]:
In [133]: s2 = s1.upper()
Out[133]: 'PYTHON PROGRAMMING'

In [134]: s1

Out[134]: 'python programming'

In [135]: s1 == s2

Out[135]: False

In [136]: s1.upper() == s2.upper()

Out[136]: True

Note: self-try other string built-in methods

Python Assignments
Assignment 1 - PEP 8 (Style Guide for Python Code - Python.org)

Assignment 2 - String Parsing using Built-in String Methods

Assignment 2 Hint

Example - String Parsing

String or Text Parsing is analyzing the string or text


Consider the below string/text (Email IDs)
From kashif@corvit.com Wed February 24 20:05:37 2020
From rizwan.datahub@gmail.com Wed February 24 23:05:37 2020
Extract the domain info from this string
Step 1: Find location of '@'
Step 2: Find location of space (' ') after '@'
Extract text between these two locations
In [1]:
x = 'From kashif@corvit.com Wed February 24 20:05:37 2020'

file:///C:/Users/Zayan/Desktop/PyLecture3.html 16
01/03/2020 PyLecture4

Lecture no 4

Python Programming Fundamentals


Python Built-in String Methods
A string is a sequence of characters enclosed in quotation marks.

In [1]:

In [2]:

[' add ', ' class ', ' contains ', ' delattr ', ' dir ', ' doc ',
' eq ', ' format ', ' ge ', ' getattribute ', ' getitem ', ' getne
wargs ', ' 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', 'c
enter', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'forma
t_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'is
identifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'is
upper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replac
e', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 's
plitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper',
'zfill']

String Find Method


In [3]:

Docstring:

S.find(sub[, start[, end]]) -> int

Return the lowest index in S where substring sub is found,


such that sub is contained within S[start:end]. Optional
arguments start and end are interpreted as in slice notation.

Return -1 on failure.
Type: method_descriptor

The find() method returns the index of first occurrence of the substring (if found). If not found, it returns -1.

file:///C:/Users/Zayan/Desktop/PyLecture4.html 1/27
01/03/2020 PyLecture4

The syntax of find() method is:


str.find(sub[, start[, end]])

String find() Parameters()


The find() method takes maximum of three parameters:
sub - It's the substring to be searched in the str string.
start and end (optional) - substring is searched within str[start:end]

Return Value from find()


The find() method returns an integer value.
If substring exists inside the string, it returns the index of first occurence of the substring.
If substring doesn't exist inside the string, it returns -1.

Example 1: find() With No start and end Argument


In [4]: s1 = 'rizwan.datahub@gmail.com'

In [5]: print(s1.find('gmail'))

15

In [6]: print(s1.find('com'))

21

In [7]: print(s1.find('outlook'))

-1

In [8]: print(s1.find('outlook') == -1)

True

In [9]: print(s1.find(' '))

-1

Example 2: find() With start and end Arguments

file:///C:/Users/Zayan/Desktop/PyLecture4.html 2/27
01/03/2020 PyLecture4

In [10]:
Out[10]:
'rizwan.datahub@gmail.com'

In [11]:

14

In [12]:

14

In [13]:

-1

In [14]:

14

In [15]:

-1

Solution - String Parsing Problem


In [16]: m = 'From rizwan.datahub@gmail.com Wed February 24 20:05:37 2020'

Expected Output: gmail.com

In [17]:

gmail.com

String Format Method


In [18]:

Docstring:

S.format(*args, **kwargs) -> str

Return a formatted version of S, using substitutions from args and kwargs.


The substitutions are identified by braces ('{' and '}').
Type: method_descriptor

file:///C:/Users/Zayan/Desktop/PyLecture4.html 3/27
01/03/2020 PyLecture4

The string format() method formats the given string into a nicer output in Python.

Link1: https://docs.python.org/3/library/stdtypes.html#str.format
(https://docs.python.org/3/library/stdtypes.html#str.format)
Link2: https://docs.python.org/3/library/string.html#formatstrings
(https://docs.python.org/3/library/string.html#formatstrings)

The syntax of format() method is:


template_string.format(pos0, pos1, ..., key0=val0, key1=val1, ...)

Here, pos0, pos1,... are positional arguments and, key0, key1,... are keyword arguments with values
val0, val1,... respectively.

And, template_string is a mixture of format codes with placeholders for the arguments.

String format() Parameters


format() method takes any number of parameters. But, is divided into two types of parameters:
Positional parameters - list of parameters that can be accessed with index of parameter inside curly
braces {index}
Keyword parameters - list of parameters of type key=value, that can be accessed with key of
parameter inside curly braces {key}

Return value from String format()


The format() method returns the formatted string.

How String format() works?


The format() reads the type of arguments passed to it and formats it according to the format codes defined in the
string.

For positional arguments

In [19]:

Out[19]: 'Hi Rizwan, your current amount is 50000.99'

Here, Argument 0 is a string "Rizwan" and Argument 1 is a floating number 50000.989.


Note: Argument list starts from 0 in Python.

The string "Hi {0}, your current amount is {1:9.2f}" is the template string. This contains the format
codes for formatting.

file:///C:/Users/Zayan/Desktop/PyLecture4.html 13
01/03/2020 PyLecture4

The curly braces are just placeholders for the arguments to be placed. In the above example, {0} is
placeholder for "Rizwan" and {1:9.2f} is placeholder for 50000.989 .

Since the template string references format() arguments as {0} and {1}, the arguments are positional arguments.
They both can also be referenced without the numbers as {} and Python internally converts them to numbers.

Internally,

Since "Rizwan" is the 0th argument, it is placed in place of {0}. Since, {0} doesn't contain any other format
codes, it doesn't perform any other operations.
However, it is not the case for 1st argument 50000.989 . Here, {1:9.2f} places 50000.989 in its place
and performs the operation 9.2f.
f specifies the format is dealing with a float number. If not correctly specified, it will give out an error.
The part before the "." (9) specifies the minimum width/padding the number (50000.989) can take. In this
case, 50000.989 is allotted a minimum of 9 places including the ".".
If no alignment option is specified, it is aligned to the right of the remaining spaces. (For strings, it is aligned
to the left.)
The part after the "." (2) truncates the decimal part (989) upto the given number. In this case, 989 is
truncated after 2 places.
Remaining numbers (9) is rounded off outputting 99.

For keyword arguments

In [20]:

Out[20]: 'Hi Rizwan, your current amount is 50000.99'

I've used the same example from above to show the difference between keyword and positional arguments.

Here, instead of just the parameters, we've used a key-value for the parameters. Namely, name="Rizwan" and
amt=50000.989 .

Since, these parameters are referenced by their keys as {name} and {amt:9.2f} , they are known as
keyword or named arguments.

Internally,

The placeholder {name} is replaced by the value of name - "Rizwan". Since, it doesn't
contain any other format codes, "Rizwan" is placed.
For the argument amt=50000.989, the placeholder {amt:9.2f} is replaced by the value
50000.989. But before replacing it, like previous example, it performs 9.2f operation
on it.
This outputs 50000.99. The decimal part is truncated after 2 places and remaining
digits are rounded off. Likewise, the total width is assigned 9 leaving one spaces to
the left.

file:///C:/Users/Zayan/Desktop/PyLecture4.html 14
01/03/2020 PyLecture4

Basic formatting with format():


The format() method allows the use of simple placeholders for formatting.
Example 1: Basic formatting for default, positional and keyword arguments

In [21]:

Out[21]: Hi Rizwan, your current amount is 50000.989.

In [22]:

Out[22]: Hi Rizwan, your current amount is 50000.989.

In [23]:

Out[23]: Hi Rizwan, your current amount is 50000.989.

In [24]:

Out[24]: Hi Rizwan, your current amount is 50000.989.

Note: In case of mixed arguments, keyword arguments has to always follow positional arguments.

Numbers formatting with format():

You can format numbers using the format specifier given below:
Type - Meaning
d-Decimal integer
c-Corresponding Unicode character
b-Binary format
o-Octal format
x-Hexadecimal format (lower case)
X-Hexadecimal format (upper case)
n-Same as 'd'. Except it uses current locale setting for number separator
e-Exponential notation. (lowercase e)
E-Exponential notation (uppercase E)
- Displays fixed point number (Default: 6)
file:///C:/Users/Zayan/Desktop/PyLecture4.html 15
01/03/2020 PyLecture4

- Same as 'f'. Except displays 'inf' as 'INF' and 'nan' as 'NAN'


- General format. Rounds number to p significant digits. (Default precision: 6)
G-Same as 'g'. Except switches to 'E' if the number is large.
%-Percentage. Multiples by 100 and puts % at the end.

Example 2: Simple number formatting

In [25]:

The number is - 123

In [26]:
# float arguments

print("The float number is - {0:f}".format(123.4567898))

The float number is - 123.456790

In [27]:
# octal, binary and hexadecimal format

print("bin - {0:b}, oct - {0:o}, hex - {0:X}".format(15))

bin - 1111, oct - 17, hex - F

Example 3: Number formatting with padding for int and floats

In [28]:
# integer numbers with minimum width

print("{0:5d}".format(12))

Out [28]: 12

In [29]:
# width doesn't work for numbers longer than padding

print("{:2d}".format(1234))

Out [29]: 1234

file:///C:/Users/Zayan/Desktop/PyLecture4.html 16
01/03/2020 PyLecture4

In [30]:
# padding for float numbers

print("{:8.3f}".format(12.2346))

Out [30]: 12.235


In [31]:
# integer numbers with minimum width filled with zeros

print("{:05d}".format(12))

Out [31]: 00012

In [32]:
# padding for float numbers filled with zeros

print("{:08.3f}".format(12.2346))

Out [32]: 0012.235

Here,
In the first statement, {0:5d} takes an integer argument and assigns a minimum width of 5. Since, no alignment is
specified, it is aligned to the right.
In the second statement, you can see the width (2) is less than the number (1234), so it doesn't take
any space to the left but also doesn't truncate the number.
Unlike integers, floats has both integer and decimal parts. And, the mininum width defined to the number
is for both parts as a whole including ".".
In the third statement, {:8.3f} truncates the decimal part into 3 places rounding off the last 2 digits. And,
the number, now 12.235, takes a width of 8 as a whole leaving 2 places to the left.
If you want to fill the remaining places with zero, placing a zero before the format specifier does this. It
works both for integers and floats: {:05d} and {:08.3f}.

Number formatting with alignment:


The operators <, ^, > and = are used for alignment when assigned a certain width to the numbers.
< Left aligned to the remaining space
^ Center aligned to the remaining space
> Right aligned to the remaining space
= Forces the signed (+) (-) to the leftmost position

Example 4: Number formatting with left, right and center alignment

In [33]:
# integer numbers with right alignment

print("{:5d}".format(12))

Out [33]: 12

file:///C:/Users/Zayan/Desktop/PyLecture4.html 17
01/03/2020 PyLecture4

In [34]:
# float numbers with center alignment

print("{:*^10.3f}".format(12.2346))

Out [34]: **12.235**

Example 5: String formatting with padding and alignment

In [35]:
# string padding with left alignment

print("{:8}".format("python"))

Out [35]: python

In [36]:
# string padding with right alignment

print("{:>8}".format("python"))

Out [36]: python

In [37]:
# string padding with center alignment

print("{:^8}".format("python"))

Out [37]: python

In [38]:
# string padding with center alignment #
and '*' padding character
print("{:*^8}".format("python"))

Out [38]: *python*

Python String Formatting:


'Old Style' String Concatenation (+ Operator)
'Old Style' String Formatting (% Operator)
'New Style' String Formatting (str.format)
String Interpolation / f-Strings (Python 3.6+)
Template Strings (Standard Library)

file:///C:/Users/Zayan/Desktop/PyLecture4.html 18
01/03/2020 PyLecture4

'Old Style' String Concatenation (+Operator)

In [39]: name = "ahamd"

cgpa = 3.9

In [40]:
name + str(cgpa)

Out [40]: 'ahamd3.9'

In [41]:
name + " " + str(cgpa)

Out [41]: 'ahamd 3.9'

In [42]:
print('My Info - Name : ' + name + ', CGPA : ' + str(cgpa))

Out [42]: My Info - Name : ahamd, CGPA : 3.9

'Old Style' String Formatting (% Operator)


https://docs.python.org/3/library/stdtypes.html#old-string-formatting
(https://docs.python.org/3/library/stdtypes.html#old-string-formatting)

'New Style' String Formatting (str.format)

In [43]: print('My Info - Name : {}, CGPA : {}'.format(cgpa, name))

Out [43]: My Info - Name : 3.9, CGPA : ahamd

In [44]:
print('My Info - Name : {1}, CGPA : {0}'.format(cgpa, name))

Out [28]: My Info - Name : ahamd, CGPA : 3.9

file:///C:/Users/Zayan/Desktop/PyLecture4.html 19
01/03/2020 PyLecture4

In [45]:
print('My Info - Name : {name}, CGPA : {cgpa}'.format(cgpa=3.9, name='ahmad'))

Out [45]: My Info - Name : ahmad, CGPA : 3.9

String Interpolation / f-Strings (Python 3.6+) </b>

In [46]:
print(f'My Info - Name : {name}, CGPA : {cgpa}')

Out [46]: My Info - Name : ahamd, CGPA : 3.9

(f-string)

PEP 3101, PEP 498, PEP 501

file:///C:/Users/Zayan/Desktop/PyLecture4.html 20
01/03/2020 PyLecture4

file:///C:/Users/Zayan/Desktop/PyLecture4.html 21

S-ar putea să vă placă și