kopia lustrzana https://github.com/animator/learn-python
7838 wiersze
522 KiB
HTML
7838 wiersze
522 KiB
HTML
<!doctype html>
|
||
<html lang="en">
|
||
|
||
<head>
|
||
<meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||
<title>Learn Python 3 by Ankit Mahato</title>
|
||
<link rel="icon" href="/favicon.ico">
|
||
<meta name="author" content="Ankit Mahato">
|
||
<meta property="og:url" content="https://animator.github.io/learn-python/">
|
||
<meta property="og:title" content="Learn Python 3 - A Free and Open Source Book by Ankit Mahato">
|
||
<meta name="twitter:title" content="Learn Python 3 - A Free and Open Source Book by Ankit Mahato">
|
||
<meta name="description"
|
||
content="Learn Python 3 is Free and Open Source Book that can help you master the fundamentals of Python programming. You can read it online or download it as a PDF. GitHub repository - https://github.com/animator/learn-python">
|
||
<meta property="og:description"
|
||
content="Learn Python 3 is Free and Open Source Book that can help you master the fundamentals of Python programming. You can read it online or download it as a PDF. GitHub repository - https://github.com/animator/learn-python">
|
||
<meta name="twitter:description"
|
||
content="Learn Python 3 is Free and Open Source Book that can help you master the fundamentals of Python programming. You can read it online or download it as a PDF. GitHub repository - https://github.com/animator/learn-python">
|
||
<meta property="og:image" content="https://animator.github.io/learn-python/images/banner.png">
|
||
<meta name="twitter:image" content="https://animator.github.io/learn-python/images/banner.png">
|
||
<meta name="twitter:card" content="summary_large_image">
|
||
<style>
|
||
*,
|
||
::after,
|
||
::before {
|
||
box-sizing: border-box;
|
||
border-width: 0;
|
||
border-style: solid;
|
||
border-color: currentColor
|
||
}
|
||
|
||
html {
|
||
font-size: 16px;
|
||
line-height: 1;
|
||
-webkit-text-size-adjust: 100%
|
||
}
|
||
|
||
ol,
|
||
ul {
|
||
padding: 0;
|
||
list-style-type: none
|
||
}
|
||
|
||
blockquote,
|
||
body,
|
||
h1,
|
||
h2,
|
||
h3,
|
||
h4,
|
||
h5,
|
||
h6,
|
||
hr,
|
||
input,
|
||
li,
|
||
ol,
|
||
p,
|
||
pre,
|
||
ul {
|
||
margin: 0
|
||
}
|
||
|
||
h1,
|
||
h2,
|
||
h3,
|
||
h4,
|
||
h5,
|
||
h6,
|
||
th {
|
||
font: inherit
|
||
}
|
||
|
||
a {
|
||
text-decoration: none
|
||
}
|
||
|
||
button {
|
||
display: block;
|
||
padding: 0;
|
||
border: 0;
|
||
margin: 0;
|
||
background-color: transparent;
|
||
border-radius: 0
|
||
}
|
||
|
||
:root {
|
||
--base-font-size-sm: 15px;
|
||
--base-font-size-md: 16px;
|
||
--base-font-size-lg: 18px;
|
||
--base-font-size-xl: 20px;
|
||
--border-radius: 0.25rem;
|
||
--color-bg-1: #fff;
|
||
--color-bg-2: #f5f5f5;
|
||
--color-fg-1: #000;
|
||
--color-fg-2: #303030;
|
||
--color-fg-3: #7f7f7f;
|
||
--color-fg-4: #a6a6a6;
|
||
--color-fg-5: #ccc;
|
||
--color-accent: #946709;
|
||
--color-addition-fg: #22863a;
|
||
--color-addition-bg: #f0fff4;
|
||
--color-deletion-fg: #b31d28;
|
||
--color-deletion-bg: #ffeef0;
|
||
--font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji';
|
||
--font-family-code: SFMono-Regular, Consolas, 'Liberation Mono', Menlo, monospace;
|
||
--font-weight-regular: normal;
|
||
--font-weight-bold: bold;
|
||
--font-size-code: 90%;
|
||
--font-size-sm: 0.8rem;
|
||
--font-size-md: 1rem;
|
||
--line-height-sm: 1.25rem;
|
||
--line-height-md: 1.75rem;
|
||
--size-1: 0.25rem;
|
||
--size-2: 0.5rem;
|
||
--size-3: 0.75rem;
|
||
--size-4: 1rem;
|
||
--size-5: 1.25rem;
|
||
--size-6: 1.5rem;
|
||
--size-7: 1.75rem;
|
||
--size-8: 2rem;
|
||
--size-9: 2.25rem;
|
||
--size-10: 2.5rem;
|
||
--size-12: 3rem;
|
||
--size-16: 4rem;
|
||
--size-20: 5rem;
|
||
--size-24: 6rem;
|
||
--z-index-1: 1;
|
||
--scroll-margin-top: calc(var(--top-bar-height) + 40px);
|
||
--toc-width: 16rem;
|
||
--top-bar-height: 3rem
|
||
}
|
||
|
||
@media (prefers-color-scheme:dark) {
|
||
:root {
|
||
color-scheme: dark;
|
||
--color-bg-1: #000;
|
||
--color-bg-2: #141414;
|
||
--color-fg-1: #fff;
|
||
--color-fg-2: #ccc;
|
||
--color-fg-3: #7f7f7f;
|
||
--color-fg-4: #595959;
|
||
--color-fg-5: #333;
|
||
--color-accent: #f7eab2;
|
||
--color-addition-fg: #aff5b4;
|
||
--color-addition-bg: #033a16;
|
||
--color-deletion-fg: #ffdcd7;
|
||
--color-deletion-bg: #67060c
|
||
}
|
||
}
|
||
|
||
html {
|
||
font-size: var(--base-font-size-sm)
|
||
}
|
||
|
||
body {
|
||
background-color: var(--color-bg-1);
|
||
color: var(--color-fg-1);
|
||
font-family: var(--font-family)
|
||
}
|
||
|
||
.--menu-visible {
|
||
overflow: hidden
|
||
}
|
||
|
||
@media (min-width:640px) {
|
||
html {
|
||
font-size: var(--base-font-size-md)
|
||
}
|
||
|
||
.--menu-visible {
|
||
overflow: visible
|
||
}
|
||
}
|
||
|
||
@media (min-width:960px) {
|
||
html {
|
||
font-size: var(--base-font-size-lg)
|
||
}
|
||
}
|
||
|
||
@media (min-width:1280px) {
|
||
html {
|
||
font-size: var(--base-font-size-xl)
|
||
}
|
||
}
|
||
|
||
.content {
|
||
padding: 0 var(--size-4) 0 var(--size-4);
|
||
font-size: var(--font-size-md);
|
||
font-weight: var(--font-weight-regular);
|
||
line-height: var(--line-height-md)
|
||
}
|
||
|
||
.content__inner {
|
||
padding: var(--top-bar-height) 0 var(--size-12) 0
|
||
}
|
||
|
||
.content__inner>:not(pre) {
|
||
overflow-wrap: break-word
|
||
}
|
||
|
||
.content h1,
|
||
.content h2,
|
||
.content h3,
|
||
.content h4,
|
||
.content h5,
|
||
.content h6 {
|
||
font-weight: var(--font-weight-bold)
|
||
}
|
||
|
||
.content h1 {
|
||
margin-top: var(--size-20);
|
||
margin-bottom: var(--size-4);
|
||
font-size: var(--size-8);
|
||
font-weight: var(--font-weight-bold);
|
||
letter-spacing: -.0625rem;
|
||
line-height: var(--size-10)
|
||
}
|
||
|
||
.content h2 {
|
||
margin-top: var(--size-12);
|
||
font-size: var(--size-6);
|
||
letter-spacing: -.03125rem;
|
||
line-height: var(--size-9)
|
||
}
|
||
|
||
.content h3 {
|
||
margin-top: var(--size-8);
|
||
font-size: var(--size-5);
|
||
letter-spacing: -.03125rem;
|
||
line-height: var(--size-8)
|
||
}
|
||
|
||
.content h4 {
|
||
margin-top: var(--size-6);
|
||
font-size: var(--size-4)
|
||
}
|
||
|
||
.content h5 {
|
||
margin-top: var(--size-4);
|
||
font-size: var(--size-3)
|
||
}
|
||
|
||
.content h6 {
|
||
margin-top: var(--size-4);
|
||
color: var(--color-fg-2);
|
||
font-size: var(--size-3);
|
||
font-style: italic
|
||
}
|
||
|
||
.content [id] {
|
||
scroll-margin-top: var(--scroll-margin-top)
|
||
}
|
||
|
||
.header-link {
|
||
display: inline-block;
|
||
padding: 0 var(--size-4);
|
||
color: var(--color-fg-3);
|
||
font-size: var(--font-size-md);
|
||
font-weight: var(--font-weight-bold)
|
||
}
|
||
|
||
.header-link:hover {
|
||
color: var(--color-fg-2)
|
||
}
|
||
|
||
.content hr {
|
||
width: 100%;
|
||
height: 1px;
|
||
border: 0;
|
||
margin-top: var(--size-12);
|
||
background-color: var(--color-fg-5)
|
||
}
|
||
|
||
.content a:not(.header-link) {
|
||
color: currentColor;
|
||
text-decoration: underline;
|
||
text-decoration-thickness: 1px;
|
||
text-underline-offset: 0.1875rem
|
||
}
|
||
|
||
.content a:not(.header-link):hover {
|
||
text-decoration: none
|
||
}
|
||
|
||
.content a:focus-visible,
|
||
.content a:focus-visible code {
|
||
background-color: var(--color-fg-1);
|
||
color: var(--color-bg-1);
|
||
outline: 0
|
||
}
|
||
|
||
.content__inner div p,
|
||
.content__inner>blockquote,
|
||
.content__inner>ol,
|
||
.content__inner>p,
|
||
.content__inner>table,
|
||
.content__inner>ul {
|
||
margin-top: var(--size-4)
|
||
}
|
||
|
||
.content blockquote {
|
||
position: relative;
|
||
padding: var(--size-2) 0 var(--size-2) var(--size-7);
|
||
color: var(--color-fg-3)
|
||
}
|
||
|
||
.content blockquote:before {
|
||
position: absolute;
|
||
top: 0;
|
||
bottom: 0;
|
||
left: 2px;
|
||
display: block;
|
||
width: 1px;
|
||
background-color: var(--color-fg-5);
|
||
content: ''
|
||
}
|
||
|
||
.content li {
|
||
position: relative;
|
||
padding-left: var(--size-7)
|
||
}
|
||
|
||
.content li:before {
|
||
position: absolute;
|
||
top: 0;
|
||
left: 0;
|
||
display: block
|
||
}
|
||
|
||
.content ul li:before {
|
||
content: '◦'
|
||
}
|
||
|
||
.content ol {
|
||
counter-reset: count
|
||
}
|
||
|
||
.content ol li {
|
||
counter-increment: count
|
||
}
|
||
|
||
.content ol li:before {
|
||
content: counter(count);
|
||
font-variant-numeric: tabular-nums
|
||
}
|
||
|
||
.content table th {
|
||
color: var(--color-fg-3)
|
||
}
|
||
|
||
.content img {
|
||
display: inline-block;
|
||
max-width: 100%
|
||
}
|
||
|
||
.content code {
|
||
padding: var(--size-1);
|
||
background-color: var(--color-bg-2);
|
||
border-radius: var(--border-radius);
|
||
color: var(--color-fg-2);
|
||
font-family: var(--font-family-code);
|
||
font-size: var(--font-size-code)
|
||
}
|
||
|
||
.content pre {
|
||
margin: var(--size-6) 0;
|
||
color: var(--color-fg-2)
|
||
}
|
||
|
||
.content pre code {
|
||
display: block;
|
||
padding: var(--size-4);
|
||
overflow-x: auto
|
||
}
|
||
|
||
.content strong {
|
||
font-weight: var(--font-weight-bold)
|
||
}
|
||
|
||
@media (min-width:640px) {
|
||
.content__inner {
|
||
max-width: 70ch;
|
||
margin: 0 auto
|
||
}
|
||
}
|
||
|
||
@media (min-width:1280px) {
|
||
.content {
|
||
margin-left: var(--toc-width)
|
||
}
|
||
|
||
.content__inner {
|
||
max-width: 66ch
|
||
}
|
||
}
|
||
|
||
@media (min-width:1600px) {
|
||
.content__inner {
|
||
max-width: 70ch
|
||
}
|
||
|
||
.content h1,
|
||
.content h2,
|
||
.content h3,
|
||
.content h4,
|
||
.content h5,
|
||
.content h6 {
|
||
position: relative;
|
||
display: block;
|
||
padding-left: var(--size-9);
|
||
margin-left: calc(-1 * var(--size-9))
|
||
}
|
||
|
||
.header-link {
|
||
position: absolute;
|
||
top: 0;
|
||
bottom: 0;
|
||
left: 0;
|
||
display: block;
|
||
padding: 0 var(--size-3)
|
||
}
|
||
}
|
||
|
||
@media (hover:hover) {
|
||
.header-link {
|
||
opacity: 0
|
||
}
|
||
|
||
.content h1:hover .header-link,
|
||
.content h2:hover .header-link,
|
||
.content h3:hover .header-link,
|
||
.content h4:hover .header-link,
|
||
.content h5:hover .header-link,
|
||
.content h6:hover .header-link {
|
||
opacity: 1
|
||
}
|
||
}
|
||
|
||
.hljs-strong {
|
||
font-weight: var(--font-weight-bold)
|
||
}
|
||
|
||
.hljs-emphasis,
|
||
.hljs-params {
|
||
font-style: italic
|
||
}
|
||
|
||
.hljs-comment,
|
||
.hljs-function,
|
||
.hljs-keyword,
|
||
.hljs-meta,
|
||
.hljs-section,
|
||
.hljs-selector-class,
|
||
.hljs-selector-id,
|
||
.hljs-selector-pseudo,
|
||
.hljs-variable,
|
||
.language-html .hljs-tag,
|
||
.language-json.hljs {
|
||
color: var(--color-fg-3)
|
||
}
|
||
|
||
.hljs,
|
||
.hljs-attr,
|
||
.hljs-params,
|
||
.hljs-title,
|
||
.language-html .hljs-tag .hljs-name,
|
||
.language-js .xml .hljs-tag .hljs-name,
|
||
.language-ts .xml .hljs-tag .hljs-name {
|
||
color: var(--color-fg-2)
|
||
}
|
||
|
||
.hljs-attribute,
|
||
.hljs-built_in,
|
||
.hljs-builtin-name,
|
||
.hljs-string,
|
||
.hljs-symbol,
|
||
.hljs-template-tag,
|
||
.hljs-template-variable {
|
||
color: var(--color-fg-1)
|
||
}
|
||
|
||
.hljs-bullet,
|
||
.hljs-link,
|
||
.hljs-literal,
|
||
.hljs-name,
|
||
.hljs-number,
|
||
.hljs-quote,
|
||
.hljs-regexp,
|
||
.hljs-selector-attr,
|
||
.hljs-selector-tag,
|
||
.language-html .hljs-attr,
|
||
.language-js .xml .hljs-attr,
|
||
.language-ts .xml .hljs-attr {
|
||
color: var(--color-accent)
|
||
}
|
||
|
||
.hljs-deletion {
|
||
background-color: var(--color-deletion-bg);
|
||
color: var(--color-deletion-fg)
|
||
}
|
||
|
||
.hljs-addition {
|
||
background-color: var(--color-addition-bg);
|
||
color: var(--color-addition-fg)
|
||
}
|
||
|
||
.menu {
|
||
position: fixed;
|
||
top: var(--top-bar-height);
|
||
bottom: 0;
|
||
left: 0;
|
||
display: none;
|
||
width: 100%;
|
||
padding: var(--size-3) 0;
|
||
border-right: 1px solid var(--color-fg-5);
|
||
background-color: var(--color-bg-1);
|
||
font-size: var(--font-size-md);
|
||
line-height: var(--line-height-md);
|
||
overflow-y: auto
|
||
}
|
||
|
||
.--menu-visible .menu {
|
||
display: block
|
||
}
|
||
|
||
.menu a {
|
||
position: relative;
|
||
display: block;
|
||
padding: var(--size-1) var(--size-4);
|
||
color: var(--color-fg-3);
|
||
overflow-wrap: break-word
|
||
}
|
||
|
||
.menu li li a {
|
||
padding-left: var(--size-8)
|
||
}
|
||
|
||
.menu li li li a {
|
||
padding-left: var(--size-12)
|
||
}
|
||
|
||
.menu li li li li a {
|
||
padding-left: var(--size-16)
|
||
}
|
||
|
||
.menu li li li li li a {
|
||
padding-left: var(--size-20)
|
||
}
|
||
|
||
.menu li li li li li li a {
|
||
padding-left: var(--size-24)
|
||
}
|
||
|
||
.menu a:not(.--scroll-spy-active):hover {
|
||
color: var(--color-fg-2)
|
||
}
|
||
|
||
.menu a:focus-visible {
|
||
background-color: var(--color-fg-1);
|
||
color: var(--color-bg-1);
|
||
outline: 0
|
||
}
|
||
|
||
.menu a[target='_blank']:after {
|
||
content: ' ↗'
|
||
}
|
||
|
||
.menu .--scroll-spy-active {
|
||
color: var(--color-fg-1)
|
||
}
|
||
|
||
.menu code {
|
||
font-family: var(--font-family-code);
|
||
font-size: var(--font-size-code)
|
||
}
|
||
|
||
@media (min-width:960px) {
|
||
.menu {
|
||
width: var(--toc-width);
|
||
font-size: var(--font-size-sm);
|
||
line-height: var(--line-height-sm)
|
||
}
|
||
|
||
.--no-toc .menu {
|
||
display: none
|
||
}
|
||
|
||
.menu__links {
|
||
display: none
|
||
}
|
||
}
|
||
|
||
@media (min-width:1280px) {
|
||
.menu {
|
||
display: block;
|
||
border-right: 0
|
||
}
|
||
}
|
||
|
||
.top-bar {
|
||
position: fixed;
|
||
z-index: var(--z-index-1);
|
||
top: 0;
|
||
right: 0;
|
||
left: 0;
|
||
display: flex;
|
||
background-color: var(--color-bg-1);
|
||
font-size: var(--font-size-md);
|
||
line-height: var(--top-bar-height);
|
||
overflow-x: auto;
|
||
white-space: nowrap
|
||
}
|
||
|
||
.top-bar:before {
|
||
position: fixed;
|
||
top: var(--top-bar-height);
|
||
right: 0;
|
||
left: 0;
|
||
display: block;
|
||
height: 1px;
|
||
background-color: var(--color-fg-5);
|
||
content: '';
|
||
pointer-events: none
|
||
}
|
||
|
||
.top-bar a {
|
||
position: relative;
|
||
z-index: var(--z-index-1);
|
||
display: block;
|
||
padding: 0 var(--size-2);
|
||
color: var(--color-fg-3)
|
||
}
|
||
|
||
.top-bar a:not(.--scroll-spy-active):hover {
|
||
color: var(--color-fg-2)
|
||
}
|
||
|
||
.top-bar a:focus-visible {
|
||
background-color: var(--color-fg-1);
|
||
color: var(--color-bg-1);
|
||
outline: 0
|
||
}
|
||
|
||
.top-bar .--scroll-spy-active {
|
||
border-bottom: 1px solid var(--color-fg-1);
|
||
color: var(--color-fg-1)
|
||
}
|
||
|
||
.top-bar__menu-toggle-button {
|
||
position: relative;
|
||
display: flex;
|
||
height: var(--top-bar-height);
|
||
align-items: center;
|
||
padding: 0 var(--size-4);
|
||
margin-right: calc(-1 * var(--size-2));
|
||
color: var(--color-fg-3);
|
||
cursor: pointer
|
||
}
|
||
|
||
.top-bar__menu-toggle-button:hover {
|
||
color: var(--color-fg-2)
|
||
}
|
||
|
||
.top-bar__menu-toggle-button:focus {
|
||
outline: 0
|
||
}
|
||
|
||
.top-bar__menu-toggle-button:focus-visible {
|
||
background-color: var(--color-fg-1);
|
||
color: var(--color-bg-1);
|
||
outline: 0
|
||
}
|
||
|
||
.top-bar__menu-toggle-button-close-svg,
|
||
.top-bar__menu-toggle-button-menu-svg {
|
||
width: var(--font-size-md);
|
||
height: var(--font-size-md)
|
||
}
|
||
|
||
.top-bar__menu-toggle-button-menu-svg {
|
||
display: block
|
||
}
|
||
|
||
.--menu-visible .top-bar__menu-toggle-button-menu-svg {
|
||
display: none
|
||
}
|
||
|
||
.top-bar__menu-toggle-button-close-svg {
|
||
display: none
|
||
}
|
||
|
||
.--menu-visible .top-bar__menu-toggle-button-close-svg {
|
||
display: block
|
||
}
|
||
|
||
.top-bar__title {
|
||
flex-grow: 1;
|
||
padding-left: var(--size-2);
|
||
color: var(--color-fg-3)
|
||
}
|
||
|
||
.top-bar .top-bar__title-link {
|
||
display: inline-block
|
||
}
|
||
|
||
.top-bar__title-version {
|
||
display: inline-block;
|
||
color: var(--color-fg-4)
|
||
}
|
||
|
||
.top-bar__items {
|
||
display: none
|
||
}
|
||
|
||
@media (min-width:960px) {
|
||
.top-bar {
|
||
font-size: var(--font-size-sm)
|
||
}
|
||
|
||
.--no-toc .top-bar__menu-toggle-button {
|
||
display: none
|
||
}
|
||
|
||
.top-bar__items {
|
||
display: flex;
|
||
padding-right: var(--size-2)
|
||
}
|
||
|
||
.top-bar__items>ul,
|
||
.top-bar__items>ul li {
|
||
display: flex
|
||
}
|
||
|
||
.top-bar__items a[target='_blank']:after {
|
||
content: ' ↗'
|
||
}
|
||
}
|
||
|
||
@media (min-width:1280px) {
|
||
.top-bar__menu-toggle-button {
|
||
display: none
|
||
}
|
||
}
|
||
</style>
|
||
<script async defer src="https://buttons.github.io/buttons.js"></script>
|
||
</head>
|
||
|
||
<body class="">
|
||
<main class="content" data-js="content">
|
||
<div class="content__inner">
|
||
<p><img src="images/learn-python.png" alt="Learn Python 3 Logo"></p>
|
||
<div><a class="github-button" href="https://github.com/animator/learn-python" data-icon="octicon-star"
|
||
data-size="large" aria-label="Star animator/learn-python on GitHub">Star this
|
||
Book on GitHub</a></div>
|
||
<h1 style="margin-top: 10px;" id="learn-python-3">Learn Python 3<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#learn-python-3">#</a></h1>
|
||
<p>by <strong>Ankit Mahato</strong> [<a href="https://animator.github.io" target="_blank"
|
||
rel="nofollow">About</a>]<br><em>Version 2022.10</em></p>
|
||
<h1 id="how-to-read-this-book">How to read this book?<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#how-to-read-this-book">#</a></h1>
|
||
<p>This book can be consumed in 3 ways:</p>
|
||
<ul>
|
||
<li>A nice web interface - <a href="https://animator.github.io/learn-python/" target="_blank"
|
||
rel="nofollow">Link</a></li>
|
||
<li>A Downloadable PDF - <a
|
||
href="https://github.com/animator/learn-python/blob/main/pdf/learn-python-v2022.10.pdf"
|
||
target="_blank">Link</a></li>
|
||
<li>Directly on GitHub - <a href="https://github.com/animator/learn-python" target="_blank"
|
||
rel="nofollow">Link</a></li>
|
||
</ul>
|
||
<h1 id="table-of-contents">Table of Contents<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#table-of-contents">#</a></h1>
|
||
<ul>
|
||
<li><a href="#introduction">Introduction</a>
|
||
<ul>
|
||
<li><a href="#introduction-to-programming-languages">Introduction to Programming Languages</a>
|
||
</li>
|
||
<li><a href="#introduction-to-python">Introduction to Python</a></li>
|
||
<li><a href="#advantages-of-python">Advantages of Python</a></li>
|
||
<li><a href="#installing-python-in-windows">Installing Python in Windows</a></li>
|
||
<li><a href="#installing-python-in-macos-apple">Installing Python in macOS (Apple)</a></li>
|
||
<li><a href="#execution-modes">Execution Modes</a></li>
|
||
<li><a href="#interactive-mode-of-execution">Interactive Mode of Execution</a></li>
|
||
<li><a href="#script-mode-of-execution">Script Mode of Execution</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#python-fundamentals">Python Fundamentals</a>
|
||
<ul>
|
||
<li><a href="#tokens-introduction">Tokens: Introduction</a></li>
|
||
<li><a href="#tokens-keywords">Tokens: Keywords</a></li>
|
||
<li><a href="#tokens-identifiers">Tokens: Identifiers</a></li>
|
||
<li><a href="#tokens-literals">Tokens: Literals</a></li>
|
||
<li><a href="#tokens-operators">Tokens: Operators</a></li>
|
||
<li><a href="#tokens-delimiters">Tokens: Delimiters</a></li>
|
||
<li><a href="#character-set">Character Set</a></li>
|
||
<li><a href="#blocks-and-indentation">Blocks and Indentation</a></li>
|
||
<li><a href="#comments">Comments</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#variables-objects--data-types">Variables, Objects & Data Types</a>
|
||
<ul>
|
||
<li><a href="#what-are-objects--variables">What are Objects & Variables?</a></li>
|
||
<li><a href="#variables--assignment-statements">Variables & Assignment Statements</a></li>
|
||
<li><a href="#built-in-data-types">Built-in Data Types</a></li>
|
||
<li><a href="#type-checking">Type Checking</a></li>
|
||
<li><a href="#type-casting">Type Casting</a>
|
||
<ul>
|
||
<li><a href="#implicit-type-casting">Implicit Type Casting</a></li>
|
||
<li><a href="#explicit-type-casting">Explicit Type Casting</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#mutable--immutable-data-types">Mutable & Immutable Data Types</a>
|
||
<ul>
|
||
<li><a href="#immutable-data-types">Immutable Data Types</a></li>
|
||
<li><a href="#mutable-data-types">Mutable Data Types</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#input--output">Input / Output</a>
|
||
<ul>
|
||
<li><a href="#how-to-accept-user-input">How to Accept User Input</a></li>
|
||
<li><a href="#displaying-output">Displaying Output</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#operators--expressions">Operators & Expressions</a>
|
||
<ul>
|
||
<li><a href="#introduction-to-operators">Introduction to Operators</a></li>
|
||
<li><a href="#arithmetic-operators">Arithmetic Operators</a></li>
|
||
<li><a href="#relational-operators">Relational Operators</a></li>
|
||
<li><a href="#assignment-operators">Assignment Operators</a></li>
|
||
<li><a href="#logical-operators">Logical Operators</a></li>
|
||
<li><a href="#identity-operators">Identity Operators</a></li>
|
||
<li><a href="#membership-operators">Membership Operators</a></li>
|
||
<li><a href="#expressions">Expressions</a></li>
|
||
<li><a href="#operator-precedence-with-examples">Operator Precedence with Examples</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#errors--exception-handling">Errors & Exception Handling</a>
|
||
<ul>
|
||
<li><a href="#error-types">Error Types</a></li>
|
||
<li><a href="#syntax-error">Syntax Error</a></li>
|
||
<li><a href="#runtime-error">Runtime Error</a></li>
|
||
<li><a href="#logical-error">Logical Error</a></li>
|
||
<li><a href="#exceptions">Exceptions</a></li>
|
||
<li><a href="#exception-handling">Exception Handling</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#control-flow">Control Flow</a>
|
||
<ul>
|
||
<li><a href="#introduction-to-control-flow">Introduction to Control Flow</a></li>
|
||
<li><a href="#sequential-flow">Sequential Flow</a></li>
|
||
<li><a href="#selection-statements-if--else">Selection Statements: if .. else</a></li>
|
||
<li><a href="#iteration-for">Iteration: for</a></li>
|
||
<li><a href="#iteration-while">Iteration: while</a></li>
|
||
<li><a href="#jump-statements">Jump Statements</a>
|
||
<ul>
|
||
<li><a href="#pass">pass</a></li>
|
||
<li><a href="#break">break</a></li>
|
||
<li><a href="#continue">continue</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#nested-loops">Nested Loops</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#strings">Strings</a>
|
||
<ul>
|
||
<li><a href="#strings-introduction--creation">Strings: Introduction & Creation</a></li>
|
||
<li><a href="#accessing-characters-of-a-string">Accessing Characters of a String</a></li>
|
||
<li><a href="#string-operations">String Operations</a></li>
|
||
<li><a href="#introduction-to-string-methods">Introduction to String Methods</a></li>
|
||
<li><a href="#convert-case-of-strings">Convert Case of Strings</a></li>
|
||
<li><a href="#check-characters-of-a-string">Check Characters of a String</a></li>
|
||
<li><a href="#split-a-string">Split a String</a></li>
|
||
<li><a href="#strip-characters-from-a-string">Strip Characters from a String</a></li>
|
||
<li><a href="#check-prefix-or-suffix-in-a-string">Check Prefix or Suffix in a String</a></li>
|
||
<li><a href="#find--replace-characters-in-a-string">Find & Replace Characters in a
|
||
String</a></li>
|
||
<li><a href="#traversing-a-string">Traversing a String</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#list">List</a>
|
||
<ul>
|
||
<li><a href="#what-is-a-python-list-how-to-create-a-list">What is a Python List? How to Create a
|
||
List?</a></li>
|
||
<li><a href="#accessing-items-of-a-list">Accessing Items of a List</a>
|
||
<ul>
|
||
<li><a href="#negative-indexing">Negative Indexing</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#modifying-a-list">Modifying a List</a></li>
|
||
<li><a href="#removing-item-from-a-list">Removing Item from a List</a></li>
|
||
<li><a href="#list-operations">List Operations</a></li>
|
||
<li><a href="#traversing-a-list">Traversing a List</a></li>
|
||
<li><a href="#built-in-functions-that-can-be-used-for-a-list">Built-in Functions that can be
|
||
used for a List</a></li>
|
||
<li><a href="#introduction-to-list-methods">Introduction to List Methods</a></li>
|
||
<li><a href="#adding-items-to-a-list">Adding Items to a List</a></li>
|
||
<li><a href="#removing-items-from-a-list">Removing Items from a List</a></li>
|
||
<li><a href="#counting-or-locating-items-in-a-list">Counting or Locating Items in a List</a>
|
||
</li>
|
||
<li><a href="#reversing-items">Reversing Items</a></li>
|
||
<li><a href="#sorting-a-list">Sorting a List</a></li>
|
||
<li><a href="#copying-a-list">Copying a List</a></li>
|
||
<li><a href="#nested-list">Nested List</a></li>
|
||
<li><a href="#list-comprehension">List Comprehension</a>
|
||
<ul>
|
||
<li><a href="#member-wise-operation">Member-wise Operation</a></li>
|
||
<li><a href="#filtering-or-subsequence">Filtering or Subsequence</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#sample-programs">Sample Programs</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#tuple">Tuple</a>
|
||
<ul>
|
||
<li><a href="#list-vs-tuple">List vs Tuple</a></li>
|
||
<li><a href="#how-to-create-tuple">How to Create Tuple?</a></li>
|
||
<li><a href="#what-is-a-singleton">What is a Singleton?</a></li>
|
||
<li><a href="#accessing-items-of-a-tuple">Accessing Items of a Tuple</a></li>
|
||
<li><a href="#tuples-are-immutable">Tuples are Immutable</a></li>
|
||
<li><a href="#tuple-operations">Tuple Operations</a></li>
|
||
<li><a href="#traversing-a-tuple">Traversing a Tuple</a></li>
|
||
<li><a href="#built-in-functions-that-can-be-used-for-a-tuple">Built-in Functions that can be
|
||
used for a Tuple</a></li>
|
||
<li><a href="#locating-items-in-a-tuple">Locating Items in a Tuple</a></li>
|
||
<li><a href="#counting-the-occurrence-of-an-item">Counting the Occurrence of an Item</a></li>
|
||
<li><a href="#new-tuple-with-reversed-items">New Tuple with Reversed Items</a></li>
|
||
<li><a href="#new-tuple-with-sorted-items">New Tuple with Sorted Items</a></li>
|
||
<li><a href="#nested-tuple">Nested Tuple</a></li>
|
||
<li><a href="#understanding-the-immutable-nature-of-tuples">Understanding the Immutable Nature
|
||
of Tuples</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#dictionary">Dictionary</a>
|
||
<ul>
|
||
<li><a href="#what-is-a-dictionary">What is a Dictionary?</a></li>
|
||
<li><a href="#how-to-create-a-dictionary">How to Create a Dictionary</a>
|
||
<ul>
|
||
<li><a href="#key-value-pairs">Key: Value Pairs</a></li>
|
||
<li><a href="#sequence-of-key-value-tuples">Sequence of (key, value) Tuples</a></li>
|
||
<li><a href="#keywordnamed-arguments">Keyword/Named Arguments</a></li>
|
||
<li><a href="#key-and-value-lists">Key and Value Lists</a></li>
|
||
<li><a href="#keys-with-default-value">Keys with Default Value</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#accessing-items-keyvalue-of-a-dictionary">Accessing Items (Key:Value) of a
|
||
Dictionary</a></li>
|
||
<li><a href="#updating-a-dictionary">Updating a Dictionary</a></li>
|
||
<li><a href="#removing-an-item-keyvalue-from-a-dictionary">Removing an Item (Key:Value) from a
|
||
Dictionary</a></li>
|
||
<li><a href="#dictionary-operations">Dictionary Operations</a></li>
|
||
<li><a href="#traversing-a-dictionary">Traversing a Dictionary</a></li>
|
||
<li><a href="#built-in-functions-for-a-dictionary">Built-in Functions for a Dictionary</a></li>
|
||
<li><a href="#creating-a-copy-of-a-dictionary">Creating a Copy of a Dictionary</a></li>
|
||
<li><a href="#nested-dictionary">Nested Dictionary</a></li>
|
||
<li><a href="#sample-programs-1">Sample Programs</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#python-standard-library">Python Standard Library</a>
|
||
<ul>
|
||
<li><a href="#built-in-functions">Built-in Functions</a></li>
|
||
<li><a href="#mathematical-functions">Mathematical Functions</a></li>
|
||
<li><a href="#type-functions">Type Functions</a>
|
||
<ul>
|
||
<li><a href="#type-checking-1">Type Checking</a></li>
|
||
<li><a href="#built-in-type-functions">Built-in Type Functions</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#io-functions">I/O Functions</a></li>
|
||
<li><a href="#baseunicode-conversion-functions">Base/Unicode Conversion Functions</a></li>
|
||
<li><a href="#what-are-built-in-modules">What are Built-in Modules?</a></li>
|
||
<li><a href="#math-module">math Module</a>
|
||
<ul>
|
||
<li><a href="#constants">Constants</a></li>
|
||
<li><a href="#functions">Functions</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#random-module">random Module</a></li>
|
||
<li><a href="#statistics-module">statistics Module</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#file-handling">File Handling</a>
|
||
<ul>
|
||
<li><a href="#file-handling-in-python---introduction--overview">File Handling in Python -
|
||
Introduction & Overview</a></li>
|
||
<li><a href="#text-files-vs-binary-files---use-case-file-formats-examples">Text Files vs Binary
|
||
Files - Use Case, File Formats, Examples</a></li>
|
||
<li><a href="#file-opening--closing">File Opening & Closing</a></li>
|
||
<li><a href="#file-reading">File Reading</a>
|
||
<ul>
|
||
<li><a href="#sequential-reading">Sequential Reading</a></li>
|
||
<li><a href="#ad-hoc-reading">Ad-hoc Reading</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#writing-a-file">Writing a File</a></li>
|
||
<li><a href="#reading--writing-binary-files-using-pickle-module">Reading & Writing Binary
|
||
Files using pickle Module</a>
|
||
<ul>
|
||
<li><a href="#dumping-data">Dumping Data</a></li>
|
||
<li><a href="#loading-data">Loading Data</a></li>
|
||
<li><a href="#example-traversing-a-binary-file">Example: Traversing a Binary File</a>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#reading--writing-a-csv-file-using-csv-module">Reading & Writing a CSV File
|
||
using csv Module</a>
|
||
<ul>
|
||
<li><a href="#reading-csv-file">Reading CSV File</a></li>
|
||
<li><a href="#writing-csv-file">Writing CSV File</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#user-defined-functions-modules--packages">User Defined Functions, Modules &
|
||
Packages</a>
|
||
<ul>
|
||
<li><a href="#user-defined-functions">User Defined Functions</a></li>
|
||
<li><a href="#function-structure">Function Structure</a>
|
||
<ul>
|
||
<li><a href="#function-header">Function Header</a></li>
|
||
<li><a href="#function-body">Function Body</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#parameters-and-arguments">Parameters and Arguments</a></li>
|
||
<li><a href="#scope-of-variables">Scope of Variables</a>
|
||
<ul>
|
||
<li><a href="#local-variables">Local Variables</a></li>
|
||
<li><a href="#global-variables">Global Variables</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#passing-objects-of-mutable-type-to-a-function">Passing Objects of Mutable Type to
|
||
a Function</a>
|
||
<ul>
|
||
<li><a href="#passing-a-list">Passing a List</a></li>
|
||
<li><a href="#passing-a-dictionary">Passing a Dictionary</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#what-is-a-module-how-to-create-a-module">What is a Module? How to Create a
|
||
Module?</a></li>
|
||
<li><a href="#executable-scripts--modules">Executable Scripts / Modules</a></li>
|
||
<li><a href="#what-is-a-package-introduction-to-pypi-how-to-create-a-python-package">What is a
|
||
Package? Introduction to PyPi. How to Create a Python Package?</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
<h1 id="introduction">Introduction<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#introduction">#</a></h1>
|
||
<h2 id="introduction-to-programming-languages">Introduction to Programming Languages<a aria-hidden
|
||
class="header-link" tabindex="-1" href="#introduction-to-programming-languages">#</a></h2>
|
||
<p>In today's digital era, we depend on computers, smartphones and the internet to perform a plethora of
|
||
tasks, like:</p>
|
||
<ul>
|
||
<li>A mathematical task, such as finding the square root of a number or solving a set of simultaneous
|
||
equations.</li>
|
||
<li>A text-based task such as reading a document and performing search/replace.</li>
|
||
<li>Streaming and playing multimedia files containing audio and video.</li>
|
||
<li>Using a search engine to find and visit a website.</li>
|
||
<li>Playing an online multiplayer game with friends.</li>
|
||
<li>and many more...</li>
|
||
</ul>
|
||
<p>Softwares play an important role as they translate human activity into corresponding machine instructions
|
||
which are executed to accomplish these tasks.</p>
|
||
<p>A <strong>software</strong> is a collection of programs where each program provides a sequence of
|
||
instructions specifying how the computer should act.</p>
|
||
<p>These instructions have to be provided in <strong>machine language</strong> or <strong>low level
|
||
language</strong> (0s and 1s) that is difficult to read or write for a human being.</p>
|
||
<p>This led to the invention of <strong>high-level programming languages</strong> in which programs can be
|
||
easily written and managed. The human-readable programs written using high-level languages are converted
|
||
into computer-readable machine code or bytecode using <strong>compilers</strong> or
|
||
<strong>interpreters</strong>.
|
||
</p>
|
||
<p>There are many high-level programming languages that are currently in wide use.</p>
|
||
<p>Some of the popular languages are Java, C, C++, C#, Go, Swift, JavaScript, PHP, Dart, Kotlin and Python.
|
||
</p>
|
||
<h2 id="introduction-to-python">Introduction to Python<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#introduction-to-python">#</a></h2>
|
||
<p>Guido van Rossum started the development of Python in December 1989. He released the first version
|
||
(0.9.9) of Python for general public on February 20, 1991.</p>
|
||
<p>The language evolved over the next few decades and so did its definition, the current version of which is
|
||
stated below:</p>
|
||
<blockquote>
|
||
<p>Python is a high-level, interpreted, object-oriented programming language with dynamic semantics.</p>
|
||
</blockquote>
|
||
<p>Let us break down and analyze the above definition to gain a better understanding of Python:</p>
|
||
<p><strong>High-level</strong></p>
|
||
<p>Python is a <strong>high-level programming language</strong> which can be used to write a program in
|
||
natural language (english) making it readable, writable, shareable and manageable.</p>
|
||
<p>While developing a Python program one is not required to handle the various components of computer
|
||
architecture like registers, memory addresses and call stacks which have to be handled if an assembly
|
||
language or a low-level language is used for development.</p>
|
||
<p>Python includes high-level language features like variables, data structures (lists, dictionaries, etc.),
|
||
objects, expressions, modules, classes, functions, loops, threads, file handling, string handling, error
|
||
handling and other computer science abstraction concepts.</p>
|
||
<p><strong>Interpreted</strong></p>
|
||
<p>In traditional programming languages like C or C++, codes are compiled into computer-readable machine
|
||
code before it can be executed.</p>
|
||
<p>Python is an <strong>interpreted language</strong> where the Python interpreter reads and executes the
|
||
program line by line.</p>
|
||
<p>The process is more time consuming compared to compiled code execution, but allows faster development as
|
||
one does not have to go through the entire compilation step during testing and debugging. Also, the code
|
||
can run on any platform as long as it has a valid Python installation (which includes interpreter) as
|
||
there is no generation of platform dependent binaries.</p>
|
||
<p><strong>Object-oriented</strong></p>
|
||
<p>Python does not enforce <strong>Object-oriented programming (OOP)</strong>, but completely supports it.
|
||
</p>
|
||
<p>A programmer can define Classes specifying the data in the form of attributes (or properties) and some
|
||
programming logic in the form of member functions (or methods). Once a class is defined, the user can
|
||
create an instance of that class which is known as an object.</p>
|
||
<p>In Python, everything (<code>int</code>, <code>list</code>, <code>dict</code>, etc.) is an object. We
|
||
will cover more about objects in detail in the later sections.</p>
|
||
<p><strong>Dynamic Semantics</strong></p>
|
||
<p>As Python is an interpreted language in which the code is executed line-by-line, a python statement or
|
||
expression is evaluated during run-time. This allows <strong>dynamic typing</strong> (type of a variable
|
||
can change over its lifetime) and creation of dynamic objects during run-time, which provides more
|
||
flexibility, usability and fewer lines of code as compared to statically-typed compiled languages like
|
||
C/C++.</p>
|
||
<h2 id="advantages-of-python">Advantages of Python<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#advantages-of-python">#</a></h2>
|
||
<p>The key advantages of Python are as follows:</p>
|
||
<p><strong>1. Easy to Learn</strong></p>
|
||
<p>The Python programming language is easy to learn with low technical and conceptual overhead. This makes
|
||
it an ideal language for beginners to learn programming.</p>
|
||
<p><strong>2. Clear Syntax & Fewer Lines of Code</strong></p>
|
||
<p>Python's simple and easy to learn syntax increases code readability and leads to fewer lines of code.</p>
|
||
<p>A typical task which requires an average of twenty lines of code in C and seven in Java can often be done
|
||
with just one line in Python.</p>
|
||
<p>Also, due to fewer lines of code the chances of making any error is significantly reduced.</p>
|
||
<p><strong>3. Open Source</strong></p>
|
||
<p>Python is an open source programming language, so anyone can view and contribute to its source code.</p>
|
||
<p><strong>4. Portable & Platform Independent</strong></p>
|
||
<p>The Python programming language is portable & platform independent as it can work on any Linux,
|
||
MacOS or Windows device.</p>
|
||
<p><strong>5. Standard Library & Python Packages</strong></p>
|
||
<p>Python has a rich and extensive Standard Library, a collection of predefined functions for various tasks.
|
||
</p>
|
||
<p>Python programmers also have at their disposal the vast ecosystem of more than 250,000 community
|
||
contributed libraries in the Python Package Index (PyPI), where one can find a solution to every
|
||
conceivable task.</p>
|
||
<p><strong>6. Web Application Development</strong></p>
|
||
<p>Some of the most popular web development frameworks (django, flask, etc.) are written in Python. This
|
||
coupled with the availablity of packages to connect to any database makes Python a great choice for web
|
||
application development.</p>
|
||
<h2 id="installing-python-in-windows">Installing Python in Windows<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#installing-python-in-windows">#</a></h2>
|
||
<p>Let's start with the Python 3 installation process on Windows operating system.</p>
|
||
<p><strong>Step 1: Download Installer</strong></p>
|
||
<p>Download the latest Windows installer from the <a href="https://www.python.org/downloads/"
|
||
target="_blank" rel="nofollow">Python Software Foundation website</a>.</p>
|
||
<p><img src="images/0201a.png" alt="Step 1: Download Installer"></p>
|
||
<p><strong>Step 2: Install Python 3</strong></p>
|
||
<p>Once the download is complete double-click and run it.</p>
|
||
<p><img src="images/0201b.png" alt="Step 2: Install Python 3"></p>
|
||
<p>Select the checkbox ✅ <code>Add Python 3.9 to PATH</code>. This will enable you to install python
|
||
packages and run python script via command-line.</p>
|
||
<p>Hit 🛡️ <code>Install Now</code> and complete the setup.</p>
|
||
<p><strong>Step 3: Verify Installation</strong></p>
|
||
<p>Once the setup is complete, click on the <code>Start</code> menu and open
|
||
<code>Python 3.9 -> IDLE (Python 3.9 64 bit)</code> to launch the Python interpreter.
|
||
</p>
|
||
<p><img src="images/0201c.png" alt="Step 3: Launch Python Interpreter"></p>
|
||
<p>Python 3.9 is now successfully installed on your computer.</p>
|
||
<p><img src="images/0201d.png" alt="Step 3: Verify Installation"></p>
|
||
<h2 id="installing-python-in-macos-apple">Installing Python in macOS (Apple)<a aria-hidden
|
||
class="header-link" tabindex="-1" href="#installing-python-in-macos-apple">#</a></h2>
|
||
<p>Let's start with the Python 3 installation process on macOS operating system.</p>
|
||
<p><strong>Step 1: Download Installer</strong></p>
|
||
<p>Download the latest macOS installer from the <a href="https://www.python.org/downloads/" target="_blank"
|
||
rel="nofollow">Python Software Foundation website</a>.</p>
|
||
<p><img src="images/0202a.png" alt="Step 1: Download Installer"></p>
|
||
<p><strong>Step 2: Install Python 3</strong></p>
|
||
<p>Once the download is complete double-click and run it.</p>
|
||
<p><img src="images/0202b.png" alt="Step 2: Install Python 3"></p>
|
||
<p>Hit <code>Continue</code> and complete the setup.</p>
|
||
<p><strong>Step 3: Verify Installation</strong></p>
|
||
<p>Once the setup is complete, click on the <code>Launchpad -> IDLE</code> to launch the Python interpreter.
|
||
</p>
|
||
<p><img src="images/0202c.png" alt="Step 3: Verify Installation"></p>
|
||
<p>Python 3.9 is now successfully installed on your computer.</p>
|
||
<h2 id="execution-modes">Execution Modes<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#execution-modes">#</a></h2>
|
||
<p>After installing the latest version of the Python interpreter, we can now write and execute some basic
|
||
Python codes.</p>
|
||
<p>There are two ways to execute a Python program:</p>
|
||
<ol>
|
||
<li><strong>Interactive Mode</strong>: When the IDLE application is launched, the Python interpreter or
|
||
the Python shell pops up on the screen. User can interact with the Python interpreter and execute
|
||
statements (single line or multiline code snippets) directly in this Python shell.</li>
|
||
<li><strong>Script Mode</strong>: This is the most commonly used method for executing a Python program.
|
||
The entire Python program is written and saved in a file (<code>.py</code> extension) which can be
|
||
executed using the IDLE application.</li>
|
||
</ol>
|
||
<h2 id="interactive-mode-of-execution">Interactive Mode of Execution<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#interactive-mode-of-execution">#</a></h2>
|
||
<p>Let us execute some basic Python statements and interact with the Python shell.</p>
|
||
<p><strong>Launching the Python Shell</strong></p>
|
||
<p>To launch the IDLE application click
|
||
<code>[Windows Start Menu Button] -> [Python 3.9 Folder] -> [IDLE (Python 3.9 64 bit)]</code>.
|
||
</p>
|
||
<p><img src="images/0201c.png" alt="Launch IDLE"></p>
|
||
<p>The Python interpreter or the Python shell will pop-up on the screen.</p>
|
||
<p><img src="images/0201d.png" alt="Python Shell"></p>
|
||
<p>The version (<code>3.9</code>) of the Python interpreter is displayed at the top of the window followed
|
||
by the <code>>>></code> symbol which indicates that the interpreter is ready to take instructions.</p>
|
||
<p>Python commands or statements can be input on this prompt. The input statements are executed
|
||
instantaneously and any variable assignments are retained as long as the session is not terminated.</p>
|
||
<p><strong>Basic Arithmetic</strong></p>
|
||
<p>Let us perform some basic arithmetic operations in the interactive mode using an integer number
|
||
(<code>2</code>) and a floating-point number (<code>3.5</code>):</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-number">2</span> + <span class="hljs-number">2</span>
|
||
<span class="hljs-number">4</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-number">2</span> * <span class="hljs-number">3.5</span>
|
||
<span class="hljs-number">7.0</span>
|
||
</code></pre>
|
||
<p>It can be observed that the results of each of the above computations are displayed immediately in the
|
||
shell.</p>
|
||
<p><strong>Storing Values/Results</strong></p>
|
||
<p>Instead of immediately displaying the results, they can also be stored in variables using the assignment
|
||
symbol (<code>=</code>) as shown below:</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>a = <span class="hljs-number">2</span> + <span class="hljs-number">2</span>
|
||
<span class="hljs-meta">>>> </span>b = <span class="hljs-number">2</span> * <span class="hljs-number">3.5</span>
|
||
</code></pre>
|
||
<p>The values of <code>a</code> and <code>b</code> can be accessed later for future calculations as shown
|
||
below:</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>a
|
||
<span class="hljs-number">4</span>
|
||
<span class="hljs-meta">>>> </span>b
|
||
<span class="hljs-number">7.0</span>
|
||
<span class="hljs-meta">>>> </span>a * <span class="hljs-number">5</span>
|
||
<span class="hljs-number">20</span>
|
||
<span class="hljs-meta">>>> </span>b / <span class="hljs-number">3</span>
|
||
<span class="hljs-number">2.3333333333333335</span>
|
||
</code></pre>
|
||
<p><strong>Basic String Operation</strong></p>
|
||
<p>Interactive mode is not just restricted to basic arithmetic or assignments. Let us join two strings -
|
||
<code>"Hello, "</code> and <code>"world!"</code>.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"Hello, "</span> + <span class="hljs-string">"world!"</span>
|
||
<span class="hljs-string">'Hello, world!'</span>
|
||
</code></pre>
|
||
<p>The complete functionality of Python is easily accessible to a user via the <strong>Interactive
|
||
Mode</strong>.</p>
|
||
<p>This makes it convenient for testing and instant execution of small code snippets (single line or few
|
||
lines of code), a feature not available in compiled languages like C, C++ and Java.</p>
|
||
<p>But, the statements cannot be saved for future use and have to retyped for re-execution. This
|
||
disadvantage is overcome by the use of Python in <strong>Script Mode</strong> as described in the next
|
||
section.</p>
|
||
<h2 id="script-mode-of-execution">Script Mode of Execution<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#script-mode-of-execution">#</a></h2>
|
||
<p>To write reusable codes, script mode is the most preferred mode of code execution.</p>
|
||
<p><strong>File Creation</strong></p>
|
||
<p>To create a new file using the IDLE application click <code>[File] -> [New File]</code></p>
|
||
<p><img src="images/0303a.png" alt="Create New File"></p>
|
||
<p>Write a simple Python program as shown below</p>
|
||
<pre><code class="hljs language-python">a = <span class="hljs-number">2</span> + <span class="hljs-number">2</span>
|
||
a
|
||
</code></pre>
|
||
<p>and save the script as <code>example.py</code> (<code>.py</code> file extension for all Python scripts)
|
||
using <code>[File] -> [Save As...]</code></p>
|
||
<p><img src="images/0303b.png" alt="Save File"></p>
|
||
<p><strong>Script Execution</strong></p>
|
||
<p>Now run this script using <code>[Run] -> [Run Module]</code>.</p>
|
||
<p><img src="images/0303c.png" alt="Execute File"></p>
|
||
<p>It can be observed that the code has been executed, but no output is displayed on the console (or the
|
||
standard output) as all outputs have to be explicitly specified when running a code in the script mode.
|
||
</p>
|
||
<p>This can be done by using the <code>print()</code> function which is used in Python scripts to display
|
||
output on the output stream. Let us quickly add the <code>print()</code> function in the above code and
|
||
execute it.</p>
|
||
<pre><code class="hljs language-python">a = <span class="hljs-number">2</span> + <span class="hljs-number">2</span>
|
||
<span class="hljs-built_in">print</span>(a)
|
||
</code></pre>
|
||
<p>Now, when you run the script you will observe that the value of <code>a</code>, that is <code>4</code>,
|
||
is now displayed on the console.</p>
|
||
<h1 id="python-fundamentals">Python Fundamentals<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#python-fundamentals">#</a></h1>
|
||
<h2 id="tokens-introduction">Tokens: Introduction<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#tokens-introduction">#</a></h2>
|
||
<p>When a Python code is executed, the Python interpreter reads each logical line and breaks it into a
|
||
sequence of lexical units.</p>
|
||
<p>These lexical units are better known as <strong>tokens</strong> - the smallest individual units of a
|
||
program. They are the building blocks of a Python code and can be classified into one of the following
|
||
categories:</p>
|
||
<ul>
|
||
<li><strong>Keywords</strong> : Reserved words that convey special meaning when processed by the Python
|
||
interpreter.</li>
|
||
<li><strong>Identifiers</strong> : Names defined by the programmer to refer to objects that can
|
||
represent variables, functions, classes, etc.</li>
|
||
<li><strong>Literals</strong> : Values specified in the program which belong to exactly one of the
|
||
Python's built-in data types.</li>
|
||
<li><strong>Delimiters</strong> : Symbols that denote grouping, punctuation, and assignment/binding.
|
||
</li>
|
||
<li><strong>Operators</strong> : Symbols that can operate on data and compute results.</li>
|
||
</ul>
|
||
<h2 id="tokens-keywords">Tokens: Keywords<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#tokens-keywords">#</a></h2>
|
||
<p>Keywords are reserved words that have special meaning when processed by the Python interpreter. They are
|
||
case-sensitive and cannot be used for naming identifiers (class, function, variable or structure names).
|
||
</p>
|
||
<p>The list of keywords in Python are provided below:</p>
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th></th>
|
||
<th></th>
|
||
<th></th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr>
|
||
<td><code>True</code></td>
|
||
<td><code>False</code></td>
|
||
<td><code>import</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>from</code></td>
|
||
<td><code>as</code></td>
|
||
<td><code>None</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>and</code></td>
|
||
<td><code>or</code></td>
|
||
<td><code>not</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>in</code></td>
|
||
<td><code>is</code></td>
|
||
<td><code>try</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>except</code></td>
|
||
<td><code>finally</code></td>
|
||
<td><code>raise</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>del</code></td>
|
||
<td><code>global</code></td>
|
||
<td><code>nonlocal</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>lambda</code></td>
|
||
<td><code>def</code></td>
|
||
<td><code>class</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>with</code></td>
|
||
<td><code>if</code></td>
|
||
<td><code>elif</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>else</code></td>
|
||
<td><code>pass</code></td>
|
||
<td><code>for</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>while</code></td>
|
||
<td><code>continue</code></td>
|
||
<td><code>break</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>assert</code></td>
|
||
<td><code>return</code></td>
|
||
<td><code>yield</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>async</code></td>
|
||
<td><code>await</code></td>
|
||
<td></td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
<h2 id="tokens-identifiers">Tokens: Identifiers<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#tokens-identifiers">#</a></h2>
|
||
<p>Identifiers are used for defining the names of Python objects such as variables, functions, classes,
|
||
modules, etc. The naming convention for identifiers is as follows:</p>
|
||
<ul>
|
||
<li>Must begin with a lowercase character (<code>a-z</code>) or an uppercase character
|
||
(<code>A-Z</code>) or underscore sign (<code>_</code>).</li>
|
||
<li>Followed by any number of letters (<code>a-z</code>, <code>A-Z</code>), digits (<code>0-9</code>),
|
||
or underscores (<code>_</code>).</li>
|
||
<li>Should not be a keyword.</li>
|
||
<li>No special symbols are allowed like <code>!</code>, <code>@</code>, <code>#</code>, <code>$</code>,
|
||
<code>%</code>, etc.
|
||
</li>
|
||
</ul>
|
||
<p>Some points to keep in mind while naming identifiers:</p>
|
||
<ul>
|
||
<li>Identifiers are case-sensitive in nature and any difference in case of any character refers to a
|
||
different identifier. e.g., <code>length</code> and <code>Length</code> are different identifiers.
|
||
</li>
|
||
<li>Identifiers differing by only underscores are different. e.g., <code>unitlength</code> and
|
||
<code>unit_length</code> are different identifiers.
|
||
</li>
|
||
</ul>
|
||
<p>It is also a good practice (although not compulsory) to follow the following procedure while naming
|
||
identifiers:</p>
|
||
<ul>
|
||
<li>Identifiers should be named carefully with an emphasis on clarity and readability. For example, in a
|
||
program that calculates the area of a rectangle, a good choice for identifier names are -
|
||
<code>length</code>, <code>breadth</code> and <code>area</code>.
|
||
</li>
|
||
<li>Class names should start with uppercase character.</li>
|
||
<li>Identifiers starting with an underscore have special meaning in a program.</li>
|
||
<li>Variable, function and method names should be in lowercase characters, with underscores separating
|
||
multiple words like <code>area_of_square</code>, <code>area_of_triangle</code>, etc.</li>
|
||
</ul>
|
||
<h2 id="tokens-literals">Tokens: Literals<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#tokens-literals">#</a></h2>
|
||
<p>Literals are tokens in the source code which represent fixed or constant values. They are often used in
|
||
assignment statements for initializing variables or in comparison expressions.</p>
|
||
<p>The various types of literals available in Python are as follows:</p>
|
||
<h3 id="numeric-literals">Numeric Literals<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#numeric-literals">#</a></h3>
|
||
<p>Numeric literals are used for representing numeric values in the source code. They can be of three types
|
||
- integers, float point numbers and imaginary numbers.</p>
|
||
<h4 id="integer-literals">Integer Literals<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#integer-literals">#</a></h4>
|
||
<p>Integer literals are numbers without any fractional component.</p>
|
||
<p>In Python, integer literals can be written in four positional (base) numeral systems:</p>
|
||
<p><strong>i. Decimal or base-10 Integer</strong></p>
|
||
<p>A decimal integer literal consists of one or more digits (<code>0-9</code>) and cannot have any zeros
|
||
preceding the first non-zero digit, except when the number is <code>0</code>.</p>
|
||
<p>Example base-10 integers:</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-number">34</span>
|
||
<span class="hljs-number">3283298</span>
|
||
<span class="hljs-number">864</span>
|
||
<span class="hljs-number">0</span>
|
||
</code></pre>
|
||
<p><code>092</code> is not a valid decimal integer literal as a zero precedes the first non-zero digit
|
||
<code>9</code>.
|
||
</p>
|
||
<p><strong>ii. Binary or base-2 Integer</strong></p>
|
||
<p>A binary integer or base-2 integer begins with <code>0b</code> or <code>0B</code> followed by binary
|
||
digits <code>0-1</code>.</p>
|
||
<p>For example, <code>27</code> can be written as a binary integer literal <code>0b11011</code>.</p>
|
||
<p><strong>iii. Octal or base-8 Integer</strong></p>
|
||
<p>An octal integer or base-8 integer begins with <code>0o</code> or <code>0O</code> followed by octal
|
||
digits <code>0-7</code>.</p>
|
||
<p>For example, <code>27</code> can be written as an octal integer literal <code>0o33</code>.</p>
|
||
<p><strong>iv. Hexadecimal or base-16 Integer</strong></p>
|
||
<p>A hexadecimal integer or base-16 integer begins with <code>0x</code> or <code>0X</code> followed by
|
||
digits <code>0-9</code> or letters <code>A-F</code> (case insensitive).</p>
|
||
<p>For example, <code>27</code> can be written as a hexadecimal integer literal <code>0x1B</code> or
|
||
<code>0x1b</code>.
|
||
</p>
|
||
<p>Thus, it can be observed that number <code>27</code> can be written in the program as <code>27</code>
|
||
(decimal), <code>0b11011</code> (binary), <code>0o33</code> (octal) or <code>0x1B</code> (hexadecimal).
|
||
</p>
|
||
<p><strong>Underscores in Integer Literals</strong></p>
|
||
<p>An optional character <code>_</code> (underscore) is also allowed in an integer literal to group digits
|
||
for enhanced readability.</p>
|
||
<p>One underscore can occur between digits, and after base specifiers like <code>0o</code>.</p>
|
||
<p>They are ignored while determining the actual numerical value of the literal.</p>
|
||
<p>Some valid underscore usages are - <code>10_00_00_000</code>, <code>0b_1110_0101</code>,
|
||
<code>0x23_123</code>.
|
||
</p>
|
||
<h4 id="floating-point-literals">Floating Point Literals<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#floating-point-literals">#</a></h4>
|
||
<p>Floating point literals are real numbers present in the source code. They contain fractional component
|
||
and/or exponential component.</p>
|
||
<p>The fractional component includes the digits after the decimal point (<code>.</code>).</p>
|
||
<p>Example floating point literals:</p>
|
||
<pre><code>3.4
|
||
.4
|
||
8.
|
||
3.4E2
|
||
3.4e-2
|
||
</code></pre>
|
||
<p>In the above example, <code>.4</code> is equivalent to <code>0.4</code> and <code>8.</code> is equivalent
|
||
to <code>8.0</code>.</p>
|
||
<p>The exponential component can be identified by the letter <code>e</code> or <code>E</code> followed by an
|
||
optional sign (<code>+</code> or <code>-</code>) and digits (<code>0-9</code>). This exponent is
|
||
equivalent to multiplying the real number with the power of <code>10</code>.</p>
|
||
<p>For example, <code>3.4E2</code> is equivalent to <code>3.4 x 10^2</code> or <code>340.0</code>, whereas
|
||
<code>3.4e-2</code> is equivalent to <code>3.4 x 10^-2</code> or <code>.034</code>.
|
||
</p>
|
||
<h4 id="imaginary-literals">Imaginary Literals<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#imaginary-literals">#</a></h4>
|
||
<p>To specify complex numbers and perform complex number mathematics, Python supports imaginary literals
|
||
which are given by real or integer number followed by the letter <code>j</code> or <code>J</code> which
|
||
represents the unit imaginary number.</p>
|
||
<p>Example imaginary literals:</p>
|
||
<pre><code>3.5j
|
||
15.j
|
||
12j
|
||
.005j
|
||
3e100j
|
||
3.5e-10j
|
||
</code></pre>
|
||
<p><strong>Points to Note</strong></p>
|
||
<p>In Python,</p>
|
||
<ul>
|
||
<li>there is no specialized literal such as a complex literal. A complex number is actually represented
|
||
in the program using an expression comprising a real number (integer/float numeric literal) and an
|
||
imaginary number (imaginary literal). For example, <code>1 + 2j</code> consists of an integer
|
||
literal (<code>1</code>) and a imaginary literal (<code>2j</code>).</li>
|
||
<li>numeric literals do not include the minus sign (<code>-</code>). <code>-</code> is actually a unary
|
||
operator it combines with a numeric literal to represent negative numbers. For example, in
|
||
<code>-3.14</code> the numeric literal is <code>3.14</code> and <code>-</code> is an operator.
|
||
</li>
|
||
</ul>
|
||
<h3 id="boolean-literals">Boolean Literals<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#boolean-literals">#</a></h3>
|
||
<p>The reserved words <code>True</code> and <code>False</code> are also boolean literals which can be used
|
||
to specify the truth value in a program.</p>
|
||
<h3 id="string-literals">String Literals<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#string-literals">#</a></h3>
|
||
<p>String literals are texts which can be specified in a variety of ways in Python:</p>
|
||
<ul>
|
||
<li>Single quotes: <code>'python'</code></li>
|
||
<li>Double quotes: <code>"python"</code></li>
|
||
<li>Triple quoted: <code>'''Triple python'''</code>, <code>"""Three python"""</code>.</li>
|
||
</ul>
|
||
<p>Triple quoted strings can also span multiple lines.</p>
|
||
<p>Example:</p>
|
||
<pre><code class="hljs language-python">s = <span class="hljs-string">"I am a String"</span>
|
||
|
||
s1 = <span class="hljs-string">"""A
|
||
multiline
|
||
String"""</span>
|
||
|
||
s2 = <span class="hljs-string">'''Also a
|
||
multiline
|
||
String'''</span>
|
||
</code></pre>
|
||
<p>The backslash (<code>\</code>) character can be used in a string literal to escape characters that
|
||
otherwise have a special meaning, such as newline, linefeed, or the quote character.</p>
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th>Escape Sequence</th>
|
||
<th>Meaning</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr>
|
||
<td><code>\\</code></td>
|
||
<td>Backslash (<code>\</code>)</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>\'</code></td>
|
||
<td>Single quote (<code>'</code>)</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>\"</code></td>
|
||
<td>Double quote (<code>"</code>)</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>\a</code></td>
|
||
<td>ASCII Bell (BEL)</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>\b</code></td>
|
||
<td>ASCII Backspace (BS)</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>\f</code></td>
|
||
<td>ASCII Formfeed (FF)</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>\n</code></td>
|
||
<td>ASCII Linefeed (LF)</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>\r</code></td>
|
||
<td>ASCII Carriage Return (CR)</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>\t</code></td>
|
||
<td>ASCII Horizontal Tab (TAB)</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>\v</code></td>
|
||
<td>ASCII Vertical Tab (VT)</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
<p>Although <code>\'</code> and <code>\"</code> can be used to specify quote characters, Python allows
|
||
embedding double quotes inside a single-quoted string (<code>'My name is "Python".'</code>) and single
|
||
quotes inside a double-quoted string (<code>"Python's World"</code>).</p>
|
||
<p>String literals also support unicode characters which can be specified using <code>\u</code> escape
|
||
sequence followed by the 4 letter unicode.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span>(<span class="hljs-string">"E = mc\u00B2"</span>)
|
||
E = mc²
|
||
</code></pre>
|
||
<p>In the above example, <code>\u00B2</code> is the unicode character which represents the 'SUPERSCRIPT
|
||
TWO'.</p>
|
||
<h3 id="special-literal">Special Literal<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#special-literal">#</a></h3>
|
||
<p><code>None</code> is a special literal which is used to denote the absence of value.</p>
|
||
<p>It should not be confused with <code>0</code> as <code>0</code> is an integer literal with a defined
|
||
finite value, whereas <code>None</code> implies nothingness.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>a = <span class="hljs-literal">None</span>
|
||
<span class="hljs-meta">>>> </span>a
|
||
>>>
|
||
</code></pre>
|
||
<p>In the above example, the Python shell does not display any value of <code>a</code> as it is assigned as
|
||
<code>None</code> which has no value.
|
||
</p>
|
||
<h3 id="collection-of-literals">Collection of Literals<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#collection-of-literals">#</a></h3>
|
||
<p>Python has the provision for specifying a collection of literals in the source code using a special
|
||
syntax known as <strong>"displays"</strong>.</p>
|
||
<p>One can create specialized containers like list, set and dictionary using this syntax.</p>
|
||
<p>Some example collection of literals (displays) are provided below:</p>
|
||
<ul>
|
||
<li><strong>List</strong>: <code>a = ['a', 'b', 'c']</code></li>
|
||
<li><strong>Set</strong>: <code>a = {'a', 'b', 'c'}</code></li>
|
||
<li><strong>Dictionary</strong>: <code>a = {'a':1, 'b':2, 'c':3}</code></li>
|
||
</ul>
|
||
<p>List, set and dictionary will be covered in detail in later chapters.</p>
|
||
<h2 id="tokens-operators">Tokens: Operators<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#tokens-operators">#</a></h2>
|
||
<p>Operators are tokens which can be combined with values and variables to create expressions which evaluate
|
||
to a single value. Python supports a rich set of operators:</p>
|
||
<pre><code class="hljs language-python">+ - * **
|
||
/ // % @
|
||
<< >>
|
||
& | ^ ~
|
||
:= < >
|
||
<= >= == !=
|
||
</code></pre>
|
||
<p>Each of the above operators are covered in detail in the chapter - Operators.</p>
|
||
<h2 id="tokens-delimiters">Tokens: Delimiters<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#tokens-delimiters">#</a></h2>
|
||
<p>Delimiters are tokens which are useful for organizing a program and are used in statements, expressions,
|
||
functions, literal collections, and various other code structures.</p>
|
||
<p>They can be classified based on utility as follows:</p>
|
||
<h3 id="grouping">Grouping<a aria-hidden class="header-link" tabindex="-1" href="#grouping">#</a></h3>
|
||
<p><code>()</code>, <code>[]</code> and <code>{}</code> are delimiters used for:</p>
|
||
<ul>
|
||
<li>grouping expressions which can be spread across multiple physical lines.</li>
|
||
<li>creating collection of literals like list display, dictionary display, set display.</li>
|
||
<li>creating parenthesized sub-expression having the highest operator precedence (evaluated first) in a
|
||
complex expression.</li>
|
||
</ul>
|
||
<p><strong>Example</strong></p>
|
||
<pre><code class="hljs language-python">days = [<span class="hljs-string">'Sunday'</span>, <span class="hljs-string">'Monday'</span>,
|
||
<span class="hljs-string">'Tuesday'</span>, <span class="hljs-string">'Wednesday'</span>,
|
||
<span class="hljs-string">'Thursday'</span>, <span class="hljs-string">'Friday'</span>,
|
||
<span class="hljs-string">'Saturday'</span>]
|
||
|
||
sum_6 = (<span class="hljs-number">1</span> + <span class="hljs-number">2</span> +
|
||
<span class="hljs-number">3</span> + <span class="hljs-number">4</span> +
|
||
<span class="hljs-number">5</span> + <span class="hljs-number">6</span>)
|
||
</code></pre>
|
||
<p>is equivalent to</p>
|
||
<pre><code class="hljs language-python">days = [<span class="hljs-string">'Sunday'</span>, <span class="hljs-string">'Monday'</span>, <span class="hljs-string">'Tuesday'</span>, <span class="hljs-string">'Wednesday'</span>, <span class="hljs-string">'Thursday'</span>, <span class="hljs-string">'Friday'</span>, <span class="hljs-string">'Saturday'</span>]
|
||
|
||
sum_6 = (<span class="hljs-number">1</span> + <span class="hljs-number">2</span> + <span class="hljs-number">3</span> + <span class="hljs-number">4</span> + <span class="hljs-number">5</span> + <span class="hljs-number">6</span>)
|
||
</code></pre>
|
||
<h3 id="punctuation-decoration-and-annotation">Punctuation, Decoration and Annotation<a aria-hidden
|
||
class="header-link" tabindex="-1" href="#punctuation-decoration-and-annotation">#</a></h3>
|
||
<p>Tokens in Python which are used for punctuation, decoration and annotation are:</p>
|
||
<pre><code>. , :
|
||
; @ ->
|
||
</code></pre>
|
||
<h3 id="assignmentbinding">Assignment/Binding<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#assignmentbinding">#</a></h3>
|
||
<p>The assignment or binding delimiters are used for binding objects to names via assignment statements. The
|
||
complete list of tokens are provided below:</p>
|
||
<pre><code>= += -= *=
|
||
/= //= %= **=
|
||
@= &= |= ^=
|
||
<<= >>=
|
||
</code></pre>
|
||
<p>Except <code>=</code>, the rest of the tokens have an operator followed by <code>=</code> character.</p>
|
||
<p>These delimiters are also known as augmented assignment operators as they perform an operation in
|
||
combination with assignment.</p>
|
||
<h2 id="character-set">Character Set<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#character-set">#</a></h2>
|
||
<p>A set of valid characters that a programming language recognizes is known as its <strong>character
|
||
set</strong>.</p>
|
||
<p>Python is a new age programming language which supports Unicode encoding standard. The default encoding
|
||
for Python source code is UTF-8 (Unicode Transformation Format – 8-bit) which enables developers to use
|
||
Unicode characters not only as literals, but also as identifiers.</p>
|
||
<p>This makes Python one of the very few programming languages that support multiple languages as shown in
|
||
the example below:</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">message = <span class="hljs-string">"हिन्दी में print करे"</span>
|
||
<span class="hljs-built_in">print</span>(message)
|
||
|
||
क = <span class="hljs-number">1</span> <span class="hljs-comment"># Devanagari Letter KA</span>
|
||
ক = <span class="hljs-number">2</span> <span class="hljs-comment"># Bengali Letter KA</span>
|
||
க = <span class="hljs-number">3</span> <span class="hljs-comment"># Tamil Letter KA</span>
|
||
ક = <span class="hljs-number">4</span> <span class="hljs-comment"># Gujarati Letter KA</span>
|
||
<span class="hljs-built_in">print</span>(क + ক + க + ક)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>हिन्दी में print करे
|
||
10
|
||
</code></pre>
|
||
<h2 id="blocks-and-indentation">Blocks and Indentation<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#blocks-and-indentation">#</a></h2>
|
||
<p>In traditional programming languages like C++ or Java, programs are organised in form of code blocks.</p>
|
||
<p>Each code block contains one or more statements which are enclosed between braces - <code>{</code> and
|
||
<code>}</code> and are executed sequentially.
|
||
</p>
|
||
<p>A sample C++/Java code is provided below which checks for an input <code>x</code>.</p>
|
||
<p><strong>C++</strong></p>
|
||
<pre><code class="hljs language-c++"><span class="hljs-keyword">if</span> (x < <span class="hljs-number">10</span>) {
|
||
cout << <span class="hljs-string">"x is less than 10"</span> << endl;
|
||
<span class="hljs-keyword">if</span> (x <= <span class="hljs-number">5</span>) {
|
||
cout << <span class="hljs-string">"x is less than or equal to 5"</span> << endl;
|
||
}
|
||
<span class="hljs-keyword">else</span> {
|
||
cout << <span class="hljs-string">"x is more than 5 but less than 10"</span> << endl;
|
||
}
|
||
}
|
||
<span class="hljs-keyword">else</span> {
|
||
cout << <span class="hljs-string">"x is not less than 10"</span> << endl;
|
||
}
|
||
</code></pre>
|
||
<p><strong>Java</strong></p>
|
||
<pre><code class="hljs language-java"><span class="hljs-keyword">if</span> (x < <span class="hljs-number">10</span>) {
|
||
System.out.println(<span class="hljs-string">"x is less than 10"</span>);
|
||
<span class="hljs-keyword">if</span> (x <= <span class="hljs-number">5</span>) {
|
||
System.out.println(<span class="hljs-string">"x is less than or equal to 5"</span>);
|
||
}
|
||
<span class="hljs-keyword">else</span> {
|
||
System.out.println(<span class="hljs-string">"x is more than 5 but less than 10"</span>);
|
||
}
|
||
}
|
||
<span class="hljs-keyword">else</span> {
|
||
System.out.print(<span class="hljs-string">"x is not less than 10"</span>);
|
||
}
|
||
</code></pre>
|
||
<p>It can be seen how indentations (<code>tab</code> at the beginning of line) are added (not required by
|
||
programming language) to the code to increase readability, which helps in guiding readers through the
|
||
code.</p>
|
||
<p><strong>Python</strong></p>
|
||
<p>Code blocks in Python are inspired by this idea as it makes it easier to understand a Python code.</p>
|
||
<p>A block of code is denoted by line indentation, typically <strong>4 spaces</strong> (preferred) or a
|
||
<strong>tab</strong>. This indentation is used to determine the logical group of statements, with all
|
||
statements within a group having the same level of indentation.
|
||
</p>
|
||
<p>The corresponding Python code for the above C++/java examples is provided below.</p>
|
||
<p>Notice how the code blocks are indented according to the logic.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">if</span> x < <span class="hljs-number">10</span>:
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"x is less than 10"</span>)
|
||
<span class="hljs-keyword">if</span> x <= <span class="hljs-number">5</span>:
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"x is less than or equal to 5"</span>)
|
||
<span class="hljs-keyword">else</span>:
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"x is more than 5 but less than 10"</span>)
|
||
<span class="hljs-keyword">else</span>:
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"x is not less than 10"</span>)
|
||
</code></pre>
|
||
<h2 id="comments">Comments<a aria-hidden class="header-link" tabindex="-1" href="#comments">#</a></h2>
|
||
<p>Python supports single-line comments and multi-line comments to enhance code readability via adding
|
||
documentation.</p>
|
||
<h3 id="single-line-comments">Single Line Comments<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#single-line-comments">#</a></h3>
|
||
<p>A single line comment begins with <code>#</code>. Everything between <code>#</code> and the end of line
|
||
is ignored by the Python interpreter.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-comment"># A single line comment.</span>
|
||
a = <span class="hljs-number">1</span> <span class="hljs-comment"># assign a</span>
|
||
</code></pre>
|
||
<h3 id="multiline-comments">Multiline comments<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#multiline-comments">#</a></h3>
|
||
<p>A multiline comment begins with <code>'''</code> or <code>"""</code> and ends with the same.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-string">"""
|
||
I am
|
||
a multiline
|
||
comment.
|
||
"""</span>
|
||
|
||
<span class="hljs-string">'''
|
||
I am
|
||
also a multiline
|
||
comment.
|
||
'''</span>
|
||
</code></pre>
|
||
<p>As compared to single line comments, multiline comments should begin at the same indentation level
|
||
corresponding to their code block.</p>
|
||
<p>For example,</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-string">"""
|
||
Begin program
|
||
here
|
||
"""</span>
|
||
<span class="hljs-keyword">if</span> x < <span class="hljs-number">10</span>:
|
||
<span class="hljs-string">"""
|
||
Enter code block when x
|
||
is less than 10
|
||
"""</span>
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"x is less than 10"</span>)
|
||
<span class="hljs-keyword">if</span> x <= <span class="hljs-number">5</span>:
|
||
<span class="hljs-string">"""
|
||
Enter code block when x
|
||
is less than or equal to 5
|
||
"""</span>
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"x is less than or equal to 5"</span>)
|
||
<span class="hljs-keyword">else</span>:
|
||
<span class="hljs-string">"""
|
||
Enter code block when x
|
||
is more than 5 but less than 10
|
||
"""</span>
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"x is more than 5 but less than 10"</span>)
|
||
<span class="hljs-keyword">else</span>:
|
||
<span class="hljs-string">"""
|
||
Enter code block when x
|
||
is not less than 10
|
||
"""</span>
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"x is not less than 10"</span>)
|
||
</code></pre>
|
||
<h1 id="variables-objects--data-types">Variables, Objects & Data Types<a aria-hidden
|
||
class="header-link" tabindex="-1" href="#variables-objects--data-types">#</a></h1>
|
||
<h2 id="what-are-objects--variables">What are Objects & Variables?<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#what-are-objects--variables">#</a></h2>
|
||
<p>A program is a sequence of instructions which often acts on information (data) provided by the user.</p>
|
||
<p>The process of creating, storing and manipulating this data helps in the computation of new data or the
|
||
end result.</p>
|
||
<p><strong>Variables are the fundamental building blocks of a program</strong> which provide a way to store,
|
||
access and modify values during the life-cycle of a program.</p>
|
||
<p>Each variable has:</p>
|
||
<ul>
|
||
<li>a name (handle),</li>
|
||
<li>a type or data-type (kind of data), and</li>
|
||
<li>a value (actual data).</li>
|
||
</ul>
|
||
<p>In traditional programming languages like Java or C++, the type of the variable is pre-defined.</p>
|
||
<p>For example, if you want to use the value <code>1</code> inside the program, you can store it in a
|
||
variable named <code>a</code> of type <code>int</code>.</p>
|
||
<pre><code>int a = 1;
|
||
</code></pre>
|
||
<p>This <code>a</code> is synonymous to a box of fixed dimensions (fixed type) holding something (value
|
||
<code>1</code>) inside it.
|
||
</p>
|
||
<p><img src="images/0501a.png" alt="Box 'a'"></p>
|
||
<p>In case we want to change the contents of the box, we can replace it with something similar (same type).
|
||
</p>
|
||
<pre><code>a = 2;
|
||
</code></pre>
|
||
<p><img src="images/0501b.png" alt="Filled box 'a'"></p>
|
||
<p>The contents of this box can be replicated and placed in a similar (same type) box:</p>
|
||
<pre><code>int b = a;
|
||
</code></pre>
|
||
<p><img src="images/0501c.png" alt="Copy box 'a' contents"></p>
|
||
<p>Multiple boxes can exist, each containing an item having the same value.</p>
|
||
<pre><code>int x = 3;
|
||
int y = 3;
|
||
int z = 3;
|
||
</code></pre>
|
||
<p><img src="images/0501d.png" alt="Boxes 'x', 'y' & 'z'"></p>
|
||
<p>As shown above, the programming languages in which the variables (named boxes) are declared along with
|
||
their types (size of the boxes) are known as <strong>statically typed</strong> languages.</p>
|
||
<p>The size of these boxes cannot change later in the program until the variable is re-initialized with the
|
||
same name and different type.</p>
|
||
<p><strong>Python is a dynamically-typed language</strong>, where every value or data item (of any type like
|
||
numeric, string, etc.) is an object.</p>
|
||
<p>The variable names are just name-tags pointing to the actual object containing data of any type.</p>
|
||
<p>As there is no need of any variable declaration in Python before usage, there is no concept of default
|
||
value (an empty box or <code>null</code>) which exists in other programming languages.</p>
|
||
<p>Whenever a new object is created in Python, it is assigned a unique identity (ID) which remains the same
|
||
throughout the lifetime of that object. This ID is the address of the object in memory and the built-in
|
||
function <code>id()</code> returns the value of this address.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>a = <span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">id</span>(a)
|
||
<span class="hljs-number">140407745943856</span>
|
||
<span class="hljs-meta">>>> </span>a = <span class="hljs-number">2</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">id</span>(a)
|
||
<span class="hljs-number">140407745943888</span>
|
||
</code></pre>
|
||
<p>In the above example, the ID of <code>a</code> changes as it points to a new object (<code>2</code>).</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>b = a
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">id</span>(b)
|
||
<span class="hljs-number">140407745943888</span>
|
||
</code></pre>
|
||
<p>Also, when <code>a</code> is assigned to <code>b</code>, instead of creating a new copy, <code>b</code>
|
||
points to the same object as <code>a</code>.</p>
|
||
<h2 id="variables--assignment-statements">Variables & Assignment Statements<a aria-hidden
|
||
class="header-link" tabindex="-1" href="#variables--assignment-statements">#</a></h2>
|
||
<p>A variable is uniquely identified by a name (identifier) and follows the same naming convention:</p>
|
||
<ul>
|
||
<li>Must begin with a lowercase character (<code>a-z</code>) or an uppercase character
|
||
(<code>A-Z</code>) or underscore sign (<code>_</code>).</li>
|
||
<li>Followed by any number of letters (<code>a-z</code>, <code>A-Z</code>), digits (<code>0-9</code>),
|
||
or underscores (<code>_</code>).</li>
|
||
<li>Should not be a keyword.</li>
|
||
<li>No special symbols are allowed like <code>!</code>, <code>@</code>, <code>#</code>, <code>$</code>,
|
||
<code>%</code>, etc.
|
||
</li>
|
||
</ul>
|
||
<h3 id="assignment">Assignment<a aria-hidden class="header-link" tabindex="-1" href="#assignment">#</a></h3>
|
||
<p>Variables can be bound to a reference of an object (of any type) using assignment statements.</p>
|
||
<p>You can create an object (data) and bind it's reference to a variable using equal sign (<code>=</code>):
|
||
</p>
|
||
<pre><code class="hljs language-python">count = <span class="hljs-number">100</span> <span class="hljs-comment"># integer</span>
|
||
pi = <span class="hljs-number">3.141</span> <span class="hljs-comment"># real number</span>
|
||
name = <span class="hljs-string">"Python"</span> <span class="hljs-comment"># string</span>
|
||
</code></pre>
|
||
<p>Here, L-value refers to the assignable variables (<code>count</code>, <code>pi</code>, <code>name</code>)
|
||
on the left side of the assignment and R-value refers to the expression on the right side of the
|
||
assignment operator that has a value (<code>100</code>, <code>3.141</code>, <code>"Python"</code>).</p>
|
||
<p>As variables are just references, you can rebind them to another object of same or different type:</p>
|
||
<pre><code class="hljs language-python">a = <span class="hljs-number">100</span> <span class="hljs-comment"># integer </span>
|
||
a = <span class="hljs-number">3.141</span> <span class="hljs-comment"># real number</span>
|
||
a = <span class="hljs-string">"Python"</span> <span class="hljs-comment"># string</span>
|
||
</code></pre>
|
||
<h3 id="deletion">Deletion<a aria-hidden class="header-link" tabindex="-1" href="#deletion">#</a></h3>
|
||
<p>The <code>del</code> statement can be used to unbind the reference to an object.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>a = <span class="hljs-number">10</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-keyword">del</span> a
|
||
<span class="hljs-meta">>>> </span>a
|
||
Traceback (most recent call last):
|
||
File <span class="hljs-string">"<stdin>"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> <module>
|
||
NameError: name <span class="hljs-string">'a'</span> <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> defined
|
||
</code></pre>
|
||
<p>Accessing <code>a</code> results in a <code>NameError</code> as the reference (variable) to the object
|
||
holding value <code>10</code> is deleted.</p>
|
||
<p>The object is also automatically cleaned up from the memory if there is no other variable referencing to
|
||
it (garbage collection).</p>
|
||
<h3 id="multiple-assignment">Multiple Assignment<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#multiple-assignment">#</a></h3>
|
||
<p>In Python, multiple assignment can be used to condense variables which are set to the same value:</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>x = y = z = <span class="hljs-string">'foo'</span>
|
||
<span class="hljs-meta">>>> </span>x
|
||
<span class="hljs-string">'foo'</span>
|
||
<span class="hljs-meta">>>> </span>y
|
||
<span class="hljs-string">'foo'</span>
|
||
<span class="hljs-meta">>>> </span>z
|
||
<span class="hljs-string">'foo'</span>
|
||
</code></pre>
|
||
<h3 id="tuple-swapping">Tuple Swapping<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#tuple-swapping">#</a></h3>
|
||
<p>In Python, a temporary variable is not required to swap values of two variables. Values can be directly
|
||
swapped (tuple swapping) as shown below:</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>a = <span class="hljs-string">'Hello'</span>
|
||
<span class="hljs-meta">>>> </span>b = <span class="hljs-string">'World'</span>
|
||
<span class="hljs-meta">>>> </span>b, a = a, b
|
||
<span class="hljs-meta">>>> </span>a
|
||
<span class="hljs-string">'World'</span>
|
||
<span class="hljs-meta">>>> </span>b
|
||
<span class="hljs-string">'Hello'</span>
|
||
</code></pre>
|
||
<h2 id="built-in-data-types">Built-in Data Types<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#built-in-data-types">#</a></h2>
|
||
<p>In Python, the <code>type</code> of a data (or value) is not linked to the variable, but to the actual
|
||
object which contains it. This type is also known as the object's data type and is used for identifying
|
||
the operations that can be performed on the data.</p>
|
||
<p>The following built-in data types are available in Python:</p>
|
||
<ul>
|
||
<li><strong>Numeric Types</strong> - <code>int</code>, <code>float</code>, <code>complex</code>,
|
||
<code>bool</code>
|
||
</li>
|
||
<li><strong>Sequence Types</strong> - <code>list</code>, <code>tuple</code>, <code>str</code></li>
|
||
<li><strong>Set Type</strong> - <code>set</code></li>
|
||
<li><strong>Mapping Type</strong> - <code>dict</code></li>
|
||
<li><strong>Special Type</strong> - <code>None</code></li>
|
||
</ul>
|
||
<p>Often sequence, set and mapping types are also collectively known as <strong>iterables</strong> as they
|
||
are a collection of items on which a user can traverse (iterate).</p>
|
||
<h3 id="numeric-types---int-float-complex-bool">Numeric Types - <code>int</code>, <code>float</code>,
|
||
<code>complex</code>, <code>bool</code><a aria-hidden class="header-link" tabindex="-1"
|
||
href="#numeric-types---int-float-complex-bool">#</a>
|
||
</h3>
|
||
<p>Numeric data types are used for storing the following types of numbers:</p>
|
||
<p><strong>Integer Numbers</strong></p>
|
||
<p>Objects holding integer numbers like <code>-1, 0, 200</code> are of <code>int</code> data type.</p>
|
||
<p><strong>Real or Floating-point Numbers</strong></p>
|
||
<p>Objects holding real or floating point numbers like <code>-1.1, 3e2, 20.0</code> are of
|
||
<code>float</code> data type.
|
||
</p>
|
||
<p><strong>Complex Numbers</strong></p>
|
||
<p>Objects storing complex numbers like <code>2 + 1j, -3j, -1 + 2J</code> are of type <code>complex</code>.
|
||
</p>
|
||
<p>Each complex number has two parts, the real part which is a numeric integer or floating point literal,
|
||
and the imaginary part which is an imaginary literal.</p>
|
||
<p><strong>Boolean</strong></p>
|
||
<p>The boolean data type (<code>bool</code>) is a subtype of <code>int</code>. It stores the evaluated value
|
||
of expressions represented as keywords - <code>True</code> (integer value <code>1</code>) and
|
||
<code>False</code> (integer value <code>0</code>).
|
||
</p>
|
||
<h3 id="sequence-types---str-list-tuple">Sequence Types - <code>str</code>, <code>list</code>,
|
||
<code>tuple</code><a aria-hidden class="header-link" tabindex="-1"
|
||
href="#sequence-types---str-list-tuple">#</a>
|
||
</h3>
|
||
<p>An ordered collection of items where each item can be accessed using an integer index is known as a
|
||
sequence. The following three sequence data types are available in Python:</p>
|
||
<p><strong>String</strong></p>
|
||
<p>A string (<code>str</code> data type) is a sequence of zero or more unicode characters enclosed within a
|
||
pair of single (<code>'</code>) or double (<code>"</code>) quotes.</p>
|
||
<p>Some example strings are - <code>"42", 'hello', "python"</code>.</p>
|
||
<p><strong>List</strong></p>
|
||
<p>A <code>list</code> is sequence of items of same or different data types which are enclosed within
|
||
brackets - <code>[ ]</code>.</p>
|
||
<p>Some example lists are - <code>[1, 2, 3]</code>, <code>['abc', 23, 3.14]</code>,
|
||
<code>['edpunk', 'python']</code>.
|
||
</p>
|
||
<p><strong>Tuple</strong></p>
|
||
<p>A <code>tuple</code> is an immutable sequence of items of same or different data types which are enclosed
|
||
within parentheses - <code>( )</code>.</p>
|
||
<p>Some example tuples are - <code>(1, 2, 3)</code>, <code>('abc', 23, 3.14)</code>,
|
||
<code>('edpunk', 'python')</code>.
|
||
</p>
|
||
<h3 id="set-type---set">Set Type - <code>set</code><a aria-hidden class="header-link" tabindex="-1"
|
||
href="#set-type---set">#</a></h3>
|
||
<p>A <code>set</code> is an unordered collection of unique items of same of different data types which are
|
||
enclosed in curly braces - <code>{ }</code>.</p>
|
||
<p>Some example sets are - <code>{1, 2, 3}</code>, <code>{'abc', 23, 3.14}</code>,
|
||
<code>{'edpunk', 'python'}</code>.
|
||
</p>
|
||
<h3 id="mapping-type---dict">Mapping Type - <code>dict</code><a aria-hidden class="header-link"
|
||
tabindex="-1" href="#mapping-type---dict">#</a></h3>
|
||
<p><code>dict</code> is a mapping data type which stores values in the form of key-value pairs.</p>
|
||
<p>It is used for representing data where you can quickly access the value (any data type) corresponding to
|
||
a key (any data type except <code>list</code>, <code>set</code> or <code>dict</code>), just like a
|
||
dictionary where you can lookup the meaning of a given word.</p>
|
||
<p>Keys and corresponding values are separated by colon (<code>:</code>).</p>
|
||
<p>The key-value pairs are separated by comma (<code>,</code>) and enclosed within curly braces -
|
||
<code>{ }</code>.
|
||
</p>
|
||
<p>Some example dictionaries are - <code>{1: "a", 2: "b", 3: "c"}</code>,
|
||
<code>{"name": "edpunk", "language": "python"}</code>.
|
||
</p>
|
||
<h3 id="special-type---none">Special Type - <code>None</code><a aria-hidden class="header-link"
|
||
tabindex="-1" href="#special-type---none">#</a></h3>
|
||
<p><code>None</code> is a special data type which is used to denote the absence of value in an object.</p>
|
||
<p>It is neither <code>0</code> nor <code>False</code> as these are defined finite values, whereas
|
||
<code>None</code> implies nothingness.
|
||
</p>
|
||
<h2 id="type-checking">Type Checking<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#type-checking">#</a></h2>
|
||
<p>The built-in <code>type()</code> function can be used to fetch the data type of an object.</p>
|
||
<p>Examples:</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>count = <span class="hljs-number">100</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">type</span>(count)
|
||
<<span class="hljs-keyword">class</span> <span class="hljs-string">'int'</span>>
|
||
|
||
<span class="hljs-meta">>>> </span>pi = <span class="hljs-number">3.141</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">type</span>(pi)
|
||
<<span class="hljs-keyword">class</span> <span class="hljs-string">'float'</span>>
|
||
|
||
<span class="hljs-meta">>>> </span>name = <span class="hljs-string">"Python"</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">type</span>(name)
|
||
<<span class="hljs-keyword">class</span> <span class="hljs-string">'str'</span>>
|
||
</code></pre>
|
||
<p>This function can be used along with the <code>is</code> operator in an expression to test whether the
|
||
object is of the given type.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>count = <span class="hljs-number">100</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">type</span>(count) <span class="hljs-keyword">is</span> <span class="hljs-built_in">int</span>
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<p>The <code>in</code> operator can be used along with the <code>type()</code> function to test if the data
|
||
type is one of the mentioned types.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-comment"># count is of type int or float</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">type</span>(count) <span class="hljs-keyword">in</span> (<span class="hljs-built_in">int</span>, <span class="hljs-built_in">float</span>)
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<h2 id="type-casting">Type Casting<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#type-casting">#</a></h2>
|
||
<p>The process of converting the data type of an object from one type to another is known as <strong>Type
|
||
Casting</strong> or <strong>Type Conversion</strong>.</p>
|
||
<p>The two kinds of type casting supported in Python are:</p>
|
||
<h3 id="implicit-type-casting">Implicit Type Casting<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#implicit-type-casting">#</a></h3>
|
||
<p>The Python interpreter automatically converts the data type without the need of user intervention when
|
||
evaluating expressions to determine the final data type.</p>
|
||
<p>In the below example the final type of <code>c</code> is automatically determined as <code>float</code>
|
||
by the Python interpreter.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>a = <span class="hljs-number">1</span> <span class="hljs-comment"># int</span>
|
||
<span class="hljs-meta">>>> </span>b = <span class="hljs-number">2.0</span> <span class="hljs-comment"># float</span>
|
||
<span class="hljs-meta">>>> </span>c = a + b
|
||
<span class="hljs-meta">>>> </span>c
|
||
<span class="hljs-number">3.0</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">type</span>(c)
|
||
<<span class="hljs-keyword">class</span> <span class="hljs-string">'float'</span>>
|
||
</code></pre>
|
||
<h3 id="explicit-type-casting">Explicit Type Casting<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#explicit-type-casting">#</a></h3>
|
||
<p>When the type conversion is explicitly specified by the user using the various built-in functions
|
||
available in Python, it is known as explicit type casting.</p>
|
||
<p>The built-in functions which can be used for explicit type casting are as follows:</p>
|
||
<p><strong>1. <code>int()</code></strong></p>
|
||
<p>Creates an <code>int</code> from a <code>bool</code>, <code>float</code> or <code>str</code> containing
|
||
integer characters (with or without sign).</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">int</span>(<span class="hljs-literal">True</span>)
|
||
<span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">int</span>(<span class="hljs-number">2.3</span>)
|
||
<span class="hljs-number">2</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">int</span>(<span class="hljs-string">"2"</span>)
|
||
<span class="hljs-number">2</span>
|
||
</code></pre>
|
||
<p><strong>2. <code>float()</code></strong></p>
|
||
<p>Creates a <code>float</code> from a <code>bool</code>, <code>int</code> or <code>str</code> containing
|
||
floating point literals (with or without sign).</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">float</span>(<span class="hljs-literal">True</span>)
|
||
<span class="hljs-number">1.0</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">float</span>(<span class="hljs-number">2</span>)
|
||
<span class="hljs-number">2.0</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">float</span>(<span class="hljs-string">"2.3"</span>)
|
||
<span class="hljs-number">2.3</span>
|
||
</code></pre>
|
||
<p><code>float()</code> also accepts the following string inputs -</p>
|
||
<ul>
|
||
<li><code>"Infinity"</code></li>
|
||
<li><code>"inf"</code></li>
|
||
<li><code>"nan"</code> (not a number).</li>
|
||
</ul>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">float</span>(<span class="hljs-string">"Infinity"</span>) > <span class="hljs-number">1</span>
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">float</span>(<span class="hljs-string">"nan"</span>)
|
||
nan
|
||
</code></pre>
|
||
<p>Floating point literals can also contain the following characters -</p>
|
||
<ul>
|
||
<li><code>.</code>, which denotes the fractional part of a number.</li>
|
||
<li><code>e</code> or <code>E</code>, which denotes the exponent part of a number.</li>
|
||
</ul>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">float</span>(<span class="hljs-string">"3.14"</span>)
|
||
<span class="hljs-number">3.14</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">float</span>(<span class="hljs-string">"10."</span>)
|
||
<span class="hljs-number">10.0</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">float</span>(<span class="hljs-string">"1e100"</span>)
|
||
<span class="hljs-number">1e+100</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">float</span>(<span class="hljs-string">"3.14e-10"</span>)
|
||
<span class="hljs-number">3.14e-10</span>
|
||
</code></pre>
|
||
<p><strong>3. <code>str()</code></strong></p>
|
||
<p>Converts any object into a <code>str</code>.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">str</span>(<span class="hljs-number">2</span>)
|
||
<span class="hljs-string">'2'</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">str</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>])
|
||
<span class="hljs-string">'[1, 2, 3, 4]'</span>
|
||
</code></pre>
|
||
<p><strong>4. <code>tuple()</code></strong></p>
|
||
<p>Creates a <code>tuple</code> from an iterable of type <code>str</code>, <code>list</code>,
|
||
<code>set</code> or <code>range</code>.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">tuple</span>(<span class="hljs-string">'hello'</span>)
|
||
(<span class="hljs-string">'h'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'l'</span>, <span class="hljs-string">'l'</span>, <span class="hljs-string">'o'</span>)
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">tuple</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>])
|
||
(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>)
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">tuple</span>(<span class="hljs-built_in">range</span>(<span class="hljs-number">6</span>))
|
||
(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>)
|
||
</code></pre>
|
||
<p><strong>5. <code>list()</code></strong></p>
|
||
<p>Creates a <code>list</code> from an iterable of type <code>str</code>, <code>tuple</code>,
|
||
<code>set</code> or <code>range</code>.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">list</span>(<span class="hljs-string">'hello'</span>)
|
||
[<span class="hljs-string">'h'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'l'</span>, <span class="hljs-string">'l'</span>, <span class="hljs-string">'o'</span>]
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">list</span>({<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>})
|
||
[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">list</span>(<span class="hljs-built_in">range</span>(<span class="hljs-number">6</span>))
|
||
[<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>]
|
||
</code></pre>
|
||
<p><strong>6. <code>set()</code></strong></p>
|
||
<p>Creates a <code>set</code> from an iterable of type <code>str</code>, <code>tuple</code>,
|
||
<code>list</code> or <code>range</code>.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">set</span>(<span class="hljs-string">'hello'</span>)
|
||
{<span class="hljs-string">'o'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'l'</span>, <span class="hljs-string">'h'</span>}
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">set</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>])
|
||
{<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>}
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">set</span>(<span class="hljs-built_in">range</span>(<span class="hljs-number">6</span>))
|
||
{<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>}
|
||
</code></pre>
|
||
<h2 id="mutable--immutable-data-types">Mutable & Immutable Data Types<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#mutable--immutable-data-types">#</a></h2>
|
||
<h3 id="immutable-data-types">Immutable Data Types<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#immutable-data-types">#</a></h3>
|
||
<p>A data type is said to be immutable when the value of an object of that type cannot be modified.</p>
|
||
<p>The following data types are immutable:</p>
|
||
<ul>
|
||
<li><code>int</code></li>
|
||
<li><code>float</code></li>
|
||
<li><code>complex</code></li>
|
||
<li><code>bool</code></li>
|
||
<li><code>tuple</code></li>
|
||
<li><code>str</code></li>
|
||
<li><code>None</code></li>
|
||
</ul>
|
||
<p>You might be wondering if some of the above types are immutable then how are we able modify the values of
|
||
variables?</p>
|
||
<p>In case of variable re-assignment, the original objects are not modified, but new objects (with new
|
||
values) are created in a new memory location and are bound to the variables. The object containing the
|
||
old value is destroyed if no other variable references it.</p>
|
||
<p>Let us take an example,</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>a = <span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span>id_a = <span class="hljs-built_in">id</span>(a)
|
||
<span class="hljs-meta">>>> </span>a = <span class="hljs-number">2</span>
|
||
<span class="hljs-meta">>>> </span>id_a2 = <span class="hljs-built_in">id</span>(a)
|
||
<span class="hljs-meta">>>> </span>id_a == id_a2
|
||
<span class="hljs-literal">False</span>
|
||
</code></pre>
|
||
<p>You can witness in the above example how the object containing the value <code>1</code> is different from
|
||
the object containing the value <code>2</code>, and <code>a</code> points to the latest object.</p>
|
||
<p>Sequence data types like strings and tuples are also immutable, i.e., no modifications are permitted to
|
||
any item once it is created and any attempt to do so raises an error.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>s = <span class="hljs-string">"Hello"</span>
|
||
<span class="hljs-meta">>>> </span>s[<span class="hljs-number">1</span>] = <span class="hljs-string">"P"</span>
|
||
Traceback (most recent call last):
|
||
File <span class="hljs-string">"<stdin>"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> <module>
|
||
TypeError: <span class="hljs-string">'str'</span> <span class="hljs-built_in">object</span> does <span class="hljs-keyword">not</span> support item assignment
|
||
<span class="hljs-meta">>>> </span>t = (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
|
||
<span class="hljs-meta">>>> </span>t[<span class="hljs-number">1</span>] = <span class="hljs-number">0</span>
|
||
Traceback (most recent call last):
|
||
File <span class="hljs-string">"<stdin>"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> <module>
|
||
TypeError: <span class="hljs-string">'tuple'</span> <span class="hljs-built_in">object</span> does <span class="hljs-keyword">not</span> support item assignment
|
||
</code></pre>
|
||
<p>Although, similar to numeric types the variables can be re-assigned to new sequences.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>s = <span class="hljs-string">"Hello"</span>
|
||
<span class="hljs-meta">>>> </span>id_s = <span class="hljs-built_in">id</span>(s)
|
||
<span class="hljs-meta">>>> </span>s = <span class="hljs-string">"Help"</span>
|
||
<span class="hljs-meta">>>> </span>id_s2 = <span class="hljs-built_in">id</span>(s)
|
||
<span class="hljs-meta">>>> </span>id_s == id_s2
|
||
<span class="hljs-literal">False</span>
|
||
|
||
<span class="hljs-meta">>>> </span>t = (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
|
||
<span class="hljs-meta">>>> </span>id_t = <span class="hljs-built_in">id</span>(t)
|
||
<span class="hljs-meta">>>> </span>t = (<span class="hljs-number">0</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
|
||
<span class="hljs-meta">>>> </span>id_t2 = <span class="hljs-built_in">id</span>(t)
|
||
<span class="hljs-meta">>>> </span>id_t == id_t2
|
||
<span class="hljs-literal">False</span>
|
||
</code></pre>
|
||
<h3 id="mutable-data-types">Mutable Data Types<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#mutable-data-types">#</a></h3>
|
||
<p>In Python, the following data types are mutable, i.e., any modification does not create a new object but
|
||
modifies the existing object:</p>
|
||
<ul>
|
||
<li><code>list</code></li>
|
||
<li><code>set</code></li>
|
||
<li><code>dict</code></li>
|
||
</ul>
|
||
<p>Let us take a list and modify its contents.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
|
||
<span class="hljs-meta">>>> </span>id_l = <span class="hljs-built_in">id</span>(l)
|
||
<span class="hljs-meta">>>> </span>l[<span class="hljs-number">0</span>] = <span class="hljs-number">0</span>
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-number">0</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
|
||
<span class="hljs-meta">>>> </span>id_l2 = <span class="hljs-built_in">id</span>(l)
|
||
<span class="hljs-meta">>>> </span>id_l == id_l2
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<p>Let us take an example of a dictionary and add a new <code>key:value</code> pair.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>d = {<span class="hljs-string">"a"</span>: <span class="hljs-string">"apple"</span>, <span class="hljs-string">"b"</span>: <span class="hljs-string">"boy"</span>}
|
||
<span class="hljs-meta">>>> </span>id_d = <span class="hljs-built_in">id</span>(d)
|
||
<span class="hljs-meta">>>> </span>d[<span class="hljs-string">"c"</span>] = <span class="hljs-string">"cat"</span>
|
||
<span class="hljs-meta">>>> </span>d
|
||
{<span class="hljs-string">'a'</span>: <span class="hljs-string">'apple'</span>, <span class="hljs-string">'b'</span>: <span class="hljs-string">'boy'</span>, <span class="hljs-string">'c'</span>: <span class="hljs-string">'cat'</span>}
|
||
<span class="hljs-meta">>>> </span>id_d2 = <span class="hljs-built_in">id</span>(d)
|
||
<span class="hljs-meta">>>> </span>id_d == id_d2
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<p>Let us take an example of a set and add new item.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>s = {<span class="hljs-string">"apple"</span>, <span class="hljs-string">"bat"</span>}
|
||
<span class="hljs-meta">>>> </span>id_s = <span class="hljs-built_in">id</span>(s)
|
||
<span class="hljs-meta">>>> </span>s.add(<span class="hljs-string">"cat"</span>)
|
||
<span class="hljs-meta">>>> </span>s
|
||
{<span class="hljs-string">'cat'</span>, <span class="hljs-string">'apple'</span>, <span class="hljs-string">'bat'</span>}
|
||
<span class="hljs-meta">>>> </span>id_s2 = <span class="hljs-built_in">id</span>(s)
|
||
<span class="hljs-meta">>>> </span>id_s == id_s2
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<p>In the above examples, the <code>id</code> of the objects (<code>list</code>, <code>dict</code>,
|
||
<code>set</code>) do not change, which implies that no new objects are created and the original objects
|
||
are modified.
|
||
</p>
|
||
<h1 id="input--output">Input / Output<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#input--output">#</a></h1>
|
||
<h2 id="how-to-accept-user-input">How to Accept User Input<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#how-to-accept-user-input">#</a></h2>
|
||
<p><code>input()</code> function is used to accept new input data from the user.</p>
|
||
<p>When this function is encountered in the code, the python interpreter waits for the user to type a
|
||
response which is read as a string and assigned to a variable.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>name = <span class="hljs-built_in">input</span>()
|
||
edpunk
|
||
<span class="hljs-meta">>>> </span>name
|
||
<span class="hljs-string">'edpunk'</span>
|
||
</code></pre>
|
||
<p>The function also has an optional string argument which is used as a prompt message for the user.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>name2 = <span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter name: "</span>)
|
||
Enter name: EdPunk
|
||
<span class="hljs-meta">>>> </span>name2
|
||
<span class="hljs-string">'EdPunk'</span>
|
||
</code></pre>
|
||
<p>User input can be converted into integer or floating point numbers using the type conversion functions
|
||
<code>int()</code> and <code>float()</code>.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>num = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter n: "</span>))
|
||
Enter n: <span class="hljs-number">10</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">type</span>(num)
|
||
<<span class="hljs-keyword">class</span> <span class="hljs-string">'int'</span>>
|
||
<span class="hljs-meta">>>> </span>num
|
||
<span class="hljs-number">10</span>
|
||
|
||
<span class="hljs-meta">>>> </span>pi = <span class="hljs-built_in">float</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter pi: "</span>))
|
||
Enter pi: <span class="hljs-number">3.14</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">type</span>(pi)
|
||
<<span class="hljs-keyword">class</span> <span class="hljs-string">'float'</span>>
|
||
<span class="hljs-meta">>>> </span>pi
|
||
<span class="hljs-number">3.14</span>
|
||
</code></pre>
|
||
<h2 id="displaying-output">Displaying Output<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#displaying-output">#</a></h2>
|
||
<p>The built-in <code>print()</code> function is used to display an output (value of variables, expressions,
|
||
etc.) on the standard output.</p>
|
||
<p>Let us go through a program which computes the area of a rectangle and displays it:</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">length = <span class="hljs-number">10</span>
|
||
breadth = <span class="hljs-number">5</span>
|
||
area = length * breadth
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Area:"</span>, area)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Area: 50
|
||
</code></pre>
|
||
<p><code>print()</code> function can also be used to output the value of multiple objects when they are
|
||
provided as arguments to the function.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">a = <span class="hljs-number">2</span> + <span class="hljs-number">2</span>
|
||
b = <span class="hljs-number">2</span> * <span class="hljs-number">3.5</span>
|
||
<span class="hljs-built_in">print</span>(a, b)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>4 7.0
|
||
</code></pre>
|
||
<p>In the above code, the values of <code>a</code> and <code>b</code> are separated by a blank space (the
|
||
default value of <code>sep</code>).</p>
|
||
<p>This property can be modified by providing any user defined separator using the <code>sep</code> option.
|
||
</p>
|
||
<p>Let us modify the code and provide <code>","</code> as the separator.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">a = <span class="hljs-number">2</span> + <span class="hljs-number">2</span>
|
||
b = <span class="hljs-number">2</span> * <span class="hljs-number">3.5</span>
|
||
<span class="hljs-built_in">print</span>(a, b, sep=<span class="hljs-string">","</span>)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>4,7.0
|
||
</code></pre>
|
||
<p>When expressions are provided as arguments to the <code>print()</code> function, output is the evaluated
|
||
value of those expressions.</p>
|
||
<p>For example,</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-built_in">print</span>(<span class="hljs-number">2</span> + <span class="hljs-number">2</span>)
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-number">2</span> * <span class="hljs-number">3.5</span>)
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Hello, "</span> + <span class="hljs-string">"world!"</span>)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>4
|
||
7.0
|
||
Hello, world!
|
||
</code></pre>
|
||
<p>In the above code snippet, each <code>print()</code> function invocation creates a new line of output.
|
||
This is because <code>end</code> parameter has the newline character (<code>'\n'</code>) as the default
|
||
value in the <code>print()</code> function.</p>
|
||
<p>This can be modified by the user as shown below:</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-built_in">print</span>(<span class="hljs-number">2</span> + <span class="hljs-number">2</span>, end=<span class="hljs-string">","</span>)
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-number">2</span> * <span class="hljs-number">3.5</span>, end=<span class="hljs-string">";"</span>)
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Hello, "</span> + <span class="hljs-string">"world!"</span>)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>4,7.0;Hello, world!
|
||
</code></pre>
|
||
<p><em><strong>Note</strong></em></p>
|
||
<p>All non-keyword arguments or expressions are converted to strings and written to the output stream by the
|
||
<code>print()</code> function. They are separated by <code>sep</code> and followed by <code>end</code>.
|
||
An empty <code>print()</code> invocation writes <code>end</code> parameter (an empty line as
|
||
<code>end</code> defaults to the newline character <code>'\n'</code>).
|
||
</p>
|
||
<h1 id="operators--expressions">Operators & Expressions<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#operators--expressions">#</a></h1>
|
||
<h2 id="introduction-to-operators">Introduction to Operators<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#introduction-to-operators">#</a></h2>
|
||
<p>Operators are symbols that perform a single simple task or operation on one or more values resulting in a
|
||
single evaluated value.</p>
|
||
<p>The values on which these operators are applied are called <strong>operands</strong>.</p>
|
||
<h3 id="unary-operators">Unary Operators<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#unary-operators">#</a></h3>
|
||
<p>Unary operators are applied on a single operand positioned on right side of the operator.</p>
|
||
<p>Following are some unary operators available in Python:</p>
|
||
<ul>
|
||
<li><code>+</code> (plus): The unary <code>+</code> operator does not change the value of the operand.
|
||
</li>
|
||
<li><code>-</code> (minus): The unary <code>-</code> operator changes the sign of the operand.</li>
|
||
<li><code>~</code> (bitwise <code>NOT</code>): The unary <code>~</code> results in the bit-wise
|
||
inversion of the integer operand. The bit-wise inversion of <code>x</code> is defined as
|
||
<code>-(x+1)</code>.
|
||
</li>
|
||
</ul>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>x = <span class="hljs-number">5</span>
|
||
<span class="hljs-meta">>>> </span>-x
|
||
-<span class="hljs-number">5</span>
|
||
<span class="hljs-meta">>>> </span>+x
|
||
<span class="hljs-number">5</span>
|
||
<span class="hljs-meta">>>> </span>~x
|
||
-<span class="hljs-number">6</span>
|
||
</code></pre>
|
||
<h3 id="binary-operators">Binary Operators<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#binary-operators">#</a></h3>
|
||
<p>Binary operators are applied on two operands.</p>
|
||
<p>For example, arithmetic operators (<code>+</code>, <code>–</code>, <code>*</code>, <code>/</code>)
|
||
evaluate the result of mathematical computation of two values.</p>
|
||
<h3 id="operators-in-python">Operators in Python<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#operators-in-python">#</a></h3>
|
||
<p>A rich set of operators are available in Python which can be categorized as follows:</p>
|
||
<ul>
|
||
<li>Arithmetic Operators - <code>+</code>, <code>–</code>, <code>*</code>, <code>/</code>,
|
||
<code>%</code>, <code>**</code>, <code>//</code>
|
||
</li>
|
||
<li>Relational Operators - <code>==</code>, <code>!=</code>, <code>></code>, <code>>=</code>,
|
||
<code><</code>, <code><=</code>
|
||
</li>
|
||
<li>Assignment Operators - <code>+=</code>, <code>-=</code>, <code>*=</code>, <code>/=</code>,
|
||
<code>%=</code>, <code>**=</code>, <code>//=</code>
|
||
</li>
|
||
<li>Logical Operators - <code>not</code>, <code>or</code>, <code>and</code></li>
|
||
<li>Identity Operators - <code>is</code>, <code>is not</code></li>
|
||
<li>Membership Operators - <code>in</code>, <code>not in</code></li>
|
||
<li>Bitwise and Shift Operators - <code>&</code>, <code>|</code>, <code>^</code>, <code>~</code>,
|
||
<code><<</code>, <code>>></code>
|
||
</li>
|
||
</ul>
|
||
<h2 id="arithmetic-operators">Arithmetic Operators<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#arithmetic-operators">#</a></h2>
|
||
<p>Arithmetic operations can be performed in Python using the following arithmetic operators:</p>
|
||
<p><strong>Addition</strong></p>
|
||
<p>The <code>+</code> operator adds the values of numeric operands.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-number">2</span> + <span class="hljs-number">3</span>
|
||
<span class="hljs-number">5</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-number">2</span> + <span class="hljs-number">3.0</span>
|
||
<span class="hljs-number">5.0</span>
|
||
</code></pre>
|
||
<p>In case the operands are of type <code>str</code>, <code>list</code> or <code>tuple</code>, the
|
||
<code>+</code> operator concatenates these two sequences or strings.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">'edpunk'</span> + <span class="hljs-string">'python'</span>
|
||
<span class="hljs-string">'edpunkpython'</span>
|
||
<span class="hljs-meta">>>> </span>[<span class="hljs-string">"ed"</span>, <span class="hljs-string">"punk"</span>] + [<span class="hljs-string">"python"</span>, ]
|
||
[<span class="hljs-string">'ed'</span>, <span class="hljs-string">'punk'</span>, <span class="hljs-string">'python'</span>]
|
||
</code></pre>
|
||
<p><strong>Subtraction</strong></p>
|
||
<p>The <code>-</code> operator subtracts the value of operand on right from the value of operand on left.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-number">2</span> - <span class="hljs-number">3</span>
|
||
-<span class="hljs-number">1</span>
|
||
</code></pre>
|
||
<p><strong>Multiplication</strong></p>
|
||
<p>The <code>*</code> operator multiplies the values of numeric operands.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-number">2</span> * <span class="hljs-number">3</span>
|
||
<span class="hljs-number">6</span>
|
||
</code></pre>
|
||
<p>In case the operands are of type <code>str</code>, <code>list</code> or <code>tuple</code>, the
|
||
<code>*</code> operator returns a sequence or string self-concatenated the specified number of times.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"python"</span> * <span class="hljs-number">3</span>
|
||
<span class="hljs-string">'pythonpythonpython'</span>
|
||
<span class="hljs-meta">>>> </span>[<span class="hljs-string">'ed'</span>, <span class="hljs-string">'py'</span>] * <span class="hljs-number">3</span>
|
||
[<span class="hljs-string">'ed'</span>, <span class="hljs-string">'py'</span>, <span class="hljs-string">'ed'</span>, <span class="hljs-string">'py'</span>, <span class="hljs-string">'ed'</span>, <span class="hljs-string">'py'</span>]
|
||
</code></pre>
|
||
<p><strong>Division</strong></p>
|
||
<p>The <code>/</code> operator divides the value of operand on left by the value of operand on right and
|
||
returns the real number quotient.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-number">6</span> / <span class="hljs-number">2</span>
|
||
<span class="hljs-number">3.0</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-number">5</span> / <span class="hljs-number">2</span>
|
||
<span class="hljs-number">2.5</span>
|
||
</code></pre>
|
||
<p><strong>Floor Division</strong></p>
|
||
<p>The <code>//</code> operator divides the value of operand on left by the value of operand on right and
|
||
returns the integer quotient.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-number">5</span> // <span class="hljs-number">2</span>
|
||
<span class="hljs-number">2</span>
|
||
</code></pre>
|
||
<p><strong>Modulus</strong></p>
|
||
<p>The <code>%</code> operator divides the value of operand on left by the value of operand on right and
|
||
returns the remainder.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-number">5</span> % <span class="hljs-number">2</span>
|
||
<span class="hljs-number">1</span>
|
||
</code></pre>
|
||
<p><strong>Exponent</strong></p>
|
||
<p>The <code>**</code> operator raises the left operand to the power of the right operand.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-number">5</span> ** <span class="hljs-number">2</span>
|
||
<span class="hljs-number">25</span>
|
||
</code></pre>
|
||
<h2 id="relational-operators">Relational Operators<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#relational-operators">#</a></h2>
|
||
<p>Relational operators are useful for comparing the values of the operands to determine their relationship.
|
||
Following relational operators are available in Python:</p>
|
||
<p><strong>Equals to</strong></p>
|
||
<p>The <code>==</code> operator returns <code>True</code> if the value of operand on left is same as the
|
||
value of operand on right.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-number">2</span> == <span class="hljs-number">2</span>
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-number">2</span> == <span class="hljs-number">3</span>
|
||
<span class="hljs-literal">False</span>
|
||
</code></pre>
|
||
<p>In case of sequence operands like <code>str</code>, <code>list</code> or <code>tuple</code>, the result
|
||
is <code>True</code> if both the sequences are exactly the same.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"python"</span> == <span class="hljs-string">"python"</span>
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"pypi"</span> == <span class="hljs-string">"python"</span>
|
||
<span class="hljs-literal">False</span>
|
||
<span class="hljs-meta">>>> </span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>] == [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<p>As a sequence is an ordered collection of items, so the order in which the items are positioned is very
|
||
important.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>[<span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>] == [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
|
||
<span class="hljs-literal">False</span>
|
||
</code></pre>
|
||
<p><strong>Not equal to</strong></p>
|
||
<p>The <code>!=</code> operator returns <code>True</code> if the value of operand on left is not equal to
|
||
the value of operand on right.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-number">2</span> != <span class="hljs-number">2</span>
|
||
<span class="hljs-literal">False</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-number">2</span> != <span class="hljs-number">3</span>
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">'py'</span> != <span class="hljs-string">'oy'</span>
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span>[<span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>] != [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>] != [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
|
||
<span class="hljs-literal">False</span>
|
||
</code></pre>
|
||
<p><strong>Greater than</strong></p>
|
||
<p>The <code>></code> operator returns <code>True</code> if the value of operand on left is greater than the
|
||
value of operand on right.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-number">3</span> > <span class="hljs-number">2</span>
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-number">2</span> > <span class="hljs-number">2</span>
|
||
<span class="hljs-literal">False</span>
|
||
</code></pre>
|
||
<p>In case of strings operands, <code>></code> operator perform comparison according to the Unicode code
|
||
point (integer) of each character one-by-one.</p>
|
||
<p>The Unicode code point of a character can be obtained using the <code>ord()</code> function in Python.
|
||
</p>
|
||
<p>The code point of first character of both operands are compared. In case they are equal, the code point
|
||
of next character of both operands are compared and the process continues.</p>
|
||
<p>For example,</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"python"</span> > <span class="hljs-string">"Python"</span>
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<p>The code point of <code>"p"</code> (<code>112</code>) is greater than the code point of <code>"P"</code>
|
||
(<code>80</code>). As <code>112</code> is greater than <code>80</code> the expression evaluates to
|
||
<code>True</code>.
|
||
</p>
|
||
<p>Let us take another example:</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"pYthon"</span> > <span class="hljs-string">"python"</span>
|
||
<span class="hljs-literal">False</span>
|
||
</code></pre>
|
||
<p>The code point of first character is same (<code>112</code>), so the next set of characters are compared.
|
||
The code point of <code>"Y"</code> (<code>89</code>) is not greater than the code point of
|
||
<code>"y"</code> (<code>121</code>) so the expression evaluates to <code>False</code>.
|
||
</p>
|
||
<p>If two string operands <code>p</code> and <code>q</code> are of unequal lengths
|
||
(<code>len(p) < len(q)</code>) and <code>p</code> is a substring of <code>q</code> such that
|
||
<code>q = pt</code> where t is any string of length greater than <code>0</code>, then <code>q > p</code>
|
||
returns <code>True</code>.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"python"</span> > <span class="hljs-string">"py"</span>
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<p>In case of sequence operands like <code>list</code> or <code>tuple</code>, the items are compared
|
||
one-by-one starting from index <code>0</code>.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>[<span class="hljs-string">"p"</span>,<span class="hljs-string">"py"</span>,<span class="hljs-string">"PY"</span>] > [<span class="hljs-string">"p"</span>,<span class="hljs-string">"Py"</span>,<span class="hljs-string">"PY"</span>]
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span>[<span class="hljs-number">1</span>, <span class="hljs-number">3</span>] > [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span>[<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>] > [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<p>In the above examples, <code>"py"</code> is greater than <code>"Py"</code> and <code>3</code> is greater
|
||
than <code>2</code> respectively.</p>
|
||
<p>If two sequences are of unequal lengths and the smaller sequence is the starting subsequence of the
|
||
larger one, then the larger sequence is considered greater than the smaller one.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>] > [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<p><strong>Greater than or equal to</strong></p>
|
||
<p>The <code>>=</code> operator returns <code>True</code> if the value of operand on left is greater than or
|
||
equal to the value of operand on right.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-number">3</span> >= <span class="hljs-number">3</span>
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-number">2</span> >= <span class="hljs-number">3</span>
|
||
<span class="hljs-literal">False</span>
|
||
</code></pre>
|
||
<p>In case of sequence operands (<code>str</code>, <code>list</code>, <code>tuple</code>), the comparison
|
||
operation performed is along the same lines as the <code>></code> operator discussed above.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"python"</span> >= <span class="hljs-string">"Python"</span>
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"python"</span> >= <span class="hljs-string">"python"</span>
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span>[<span class="hljs-string">"py"</span>, <span class="hljs-string">"py"</span>, <span class="hljs-string">"PY"</span>] >= [<span class="hljs-string">"py"</span>, <span class="hljs-string">"Py"</span>, <span class="hljs-string">"PY"</span>]
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>] >= [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>] >= [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<p><strong>Less than</strong></p>
|
||
<p>The <code><</code> operator returns <code>True</code> if the value of operand on left is less than
|
||
the value of operand on right.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-number">2</span> < <span class="hljs-number">3</span>
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-number">3</span> < <span class="hljs-number">3</span>
|
||
<span class="hljs-literal">False</span>
|
||
</code></pre>
|
||
<p>In case of sequence operands (<code>str</code>, <code>list</code>, <code>tuple</code>), the comparison
|
||
operation performed is along the same lines as the <code>></code> operator discussed above.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"file"</span> < <span class="hljs-string">"Pile"</span>
|
||
<span class="hljs-literal">False</span>
|
||
<span class="hljs-comment"># f(102) is > P(80)</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"py"</span> < <span class="hljs-string">"python"</span>
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span>[<span class="hljs-string">"Py"</span>, <span class="hljs-string">"PY"</span>] < [<span class="hljs-string">"py"</span>, <span class="hljs-string">"PY"</span>]
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span>[<span class="hljs-string">'a'</span>, <span class="hljs-number">2</span>] < [<span class="hljs-string">'a'</span>, <span class="hljs-number">3</span>]
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>] < [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>]
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<p><strong>Less than or equal to</strong></p>
|
||
<p>The <code><=</code> operator returns <code>True</code> if the value of operand on left is lesser
|
||
than or equal to the value of operand on right.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-number">2</span> <= <span class="hljs-number">3</span>
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-number">3</span> <= <span class="hljs-number">3</span>
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<p>In case of sequence operands (<code>str</code>, <code>list</code>, <code>tuple</code>), the comparison
|
||
operation performed is along the same lines as the <code>></code> operator discussed above.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"file"</span> <= <span class="hljs-string">"Pile"</span>
|
||
<span class="hljs-literal">False</span>
|
||
<span class="hljs-comment"># f(102) is > P(80)</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"py"</span> <= <span class="hljs-string">"python"</span>
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span>[<span class="hljs-string">"Py"</span>, <span class="hljs-string">"PY"</span>] <= [<span class="hljs-string">"py"</span>, <span class="hljs-string">"PY"</span>]
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span>[<span class="hljs-string">'a'</span>, <span class="hljs-number">3</span>] <= [<span class="hljs-string">'b'</span>, <span class="hljs-number">2</span>]
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span>[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>] <= [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>]
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<h2 id="assignment-operators">Assignment Operators<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#assignment-operators">#</a></h2>
|
||
<p>The assignment symbol (<code>=</code>) serves as a delimiter between the name and value in an assignment
|
||
statement.</p>
|
||
<p>It binds (or rebinds) a value (data, variable, expression) on the right to the target variable on the
|
||
left.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>x = <span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span>x
|
||
<span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span>y = x
|
||
<span class="hljs-meta">>>> </span>y
|
||
<span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span>y = <span class="hljs-string">"python"</span>
|
||
<span class="hljs-meta">>>> </span>y
|
||
<span class="hljs-string">'python'</span>
|
||
</code></pre>
|
||
<p>Binary operators can be combined with the assignment symbol to create <strong>Augmented Assignment
|
||
Operators</strong>.</p>
|
||
<p>These operators perform the binary operation on the two operands and assign the result to the original
|
||
target (left operand).</p>
|
||
<p>If <code><op></code> is a binary operator, then the expression <code>a <op>= b</code>
|
||
containing the augmented assignment operator is equivalent to <code>a = a <op> b</code>.</p>
|
||
<p><strong><code>+=</code></strong></p>
|
||
<p>The <code>+=</code> operator adds a value (right operand) to the variable (left operand) and assigns the
|
||
result to that variable.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>a = <span class="hljs-number">2</span>
|
||
<span class="hljs-meta">>>> </span>a += <span class="hljs-number">3</span>
|
||
<span class="hljs-meta">>>> </span>a
|
||
<span class="hljs-number">5</span>
|
||
<span class="hljs-meta">>>> </span>x = <span class="hljs-string">"hello"</span>
|
||
<span class="hljs-meta">>>> </span>y = <span class="hljs-string">"world"</span>
|
||
<span class="hljs-meta">>>> </span>x += y
|
||
<span class="hljs-meta">>>> </span>x
|
||
<span class="hljs-string">'helloworld'</span>
|
||
</code></pre>
|
||
<p><strong><code>-=</code></strong></p>
|
||
<p>The <code>-=</code> operator subtracts a value (right operand) from the variable (left operand) and
|
||
assigns the result to that variable.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>a = <span class="hljs-number">3</span>
|
||
<span class="hljs-meta">>>> </span>a -= <span class="hljs-number">2</span>
|
||
<span class="hljs-meta">>>> </span>a
|
||
<span class="hljs-number">1</span>
|
||
</code></pre>
|
||
<p><strong><code>*=</code></strong></p>
|
||
<p>The <code>*=</code> operator multiplies a value (right operand) to the variable (left operand) and
|
||
assigns the result to that variable.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>a = <span class="hljs-number">3</span>
|
||
<span class="hljs-meta">>>> </span>a *= <span class="hljs-number">2</span>
|
||
<span class="hljs-meta">>>> </span>a
|
||
<span class="hljs-number">6</span>
|
||
<span class="hljs-meta">>>> </span>x = <span class="hljs-string">"hi"</span>
|
||
<span class="hljs-meta">>>> </span>x *= <span class="hljs-number">3</span>
|
||
<span class="hljs-meta">>>> </span>x
|
||
<span class="hljs-string">'hihihi'</span>
|
||
</code></pre>
|
||
<p><strong><code>/=</code></strong></p>
|
||
<p>The <code>/=</code> operator divides the variable (left operand) by a value (right operand) and assigns
|
||
the result to that variable.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>a = <span class="hljs-number">4</span>
|
||
<span class="hljs-meta">>>> </span>a /= <span class="hljs-number">2</span>
|
||
<span class="hljs-meta">>>> </span>a
|
||
<span class="hljs-number">2.0</span>
|
||
</code></pre>
|
||
<p><strong><code>//=</code></strong></p>
|
||
<p>The <code>//=</code> operator floor divides the variable (left operand) by a value (right operand) and
|
||
assigns the result to that variable.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>a = <span class="hljs-number">5</span>
|
||
<span class="hljs-meta">>>> </span>a //= <span class="hljs-number">2</span>
|
||
<span class="hljs-meta">>>> </span>a
|
||
<span class="hljs-number">2</span>
|
||
</code></pre>
|
||
<p><strong><code>**=</code></strong></p>
|
||
<p>The <code>**=</code> operator raises the variable (left operand) to a power (right operand) and assigns
|
||
the result to that variable.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>a = <span class="hljs-number">4</span>
|
||
<span class="hljs-meta">>>> </span>a **= <span class="hljs-number">2</span>
|
||
<span class="hljs-meta">>>> </span>a
|
||
<span class="hljs-number">16</span>
|
||
</code></pre>
|
||
<p><strong><code>%=</code></strong></p>
|
||
<p>The <code>%=</code> operator computes modulus of the variable (left operand) and a value (right operand)
|
||
and assigns the result to that variable.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>a = <span class="hljs-number">4</span>
|
||
<span class="hljs-meta">>>> </span>a %= <span class="hljs-number">3</span>
|
||
<span class="hljs-meta">>>> </span>a
|
||
<span class="hljs-number">1</span>
|
||
</code></pre>
|
||
<h2 id="logical-operators">Logical Operators<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#logical-operators">#</a></h2>
|
||
<p>Expressions using logical operators evaluate to a boolean value (<code>True</code> or <code>False</code>)
|
||
based on the logical state of the operands.</p>
|
||
<h3 id="logical-state-of-operands">Logical State of Operands<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#logical-state-of-operands">#</a></h3>
|
||
<p>In Python, all values except <code>0</code>, <code>None</code>, <code>False</code>, <code>""</code>,
|
||
<code>''</code>, <code>()</code>, <code>[]</code>, <code>{}</code> have their logical state as
|
||
<code>True</code>.
|
||
</p>
|
||
<p><code>bool()</code> built-in function can be used to determine the logical state of literals, variables
|
||
or expressions.</p>
|
||
<p>The logical state of the following literals is <code>False</code>.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">bool</span>(<span class="hljs-literal">False</span>)
|
||
<span class="hljs-literal">False</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">bool</span>(<span class="hljs-number">0</span>)
|
||
<span class="hljs-literal">False</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">bool</span>([])
|
||
<span class="hljs-literal">False</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">bool</span>(<span class="hljs-literal">None</span>)
|
||
<span class="hljs-literal">False</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">bool</span>(<span class="hljs-string">""</span>)
|
||
<span class="hljs-literal">False</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">bool</span>([])
|
||
<span class="hljs-literal">False</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">bool</span>(())
|
||
<span class="hljs-literal">False</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">bool</span>({})
|
||
<span class="hljs-literal">False</span>
|
||
</code></pre>
|
||
<p>Some example literals having boolean state as <code>True</code> are provided below.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">bool</span>(<span class="hljs-literal">True</span>)
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">bool</span>(<span class="hljs-number">1</span>)
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">bool</span>(<span class="hljs-number">2.0</span>)
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">bool</span>(<span class="hljs-number">100</span>)
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">bool</span>(<span class="hljs-string">"python"</span>)
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">bool</span>([<span class="hljs-string">"py"</span>, <span class="hljs-string">"thon"</span>])
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<p><strong><code>not</code></strong></p>
|
||
<p>The logical state of an operand can be reversed (<code>False</code> to <code>True</code>, and vice versa)
|
||
using the logical <code>not</code> operator.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>n = <span class="hljs-number">5</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">bool</span>(n)
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">bool</span>(<span class="hljs-keyword">not</span> n)
|
||
<span class="hljs-literal">False</span>
|
||
</code></pre>
|
||
<p><strong><code>or</code></strong></p>
|
||
<p>The logical <code>or</code> operator returns <code>True</code> if the logical state of any of the two
|
||
operands is <code>True</code>.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-literal">True</span> <span class="hljs-keyword">or</span> <span class="hljs-literal">False</span>
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">bool</span>(<span class="hljs-number">1</span> <span class="hljs-keyword">or</span> <span class="hljs-number">0</span>)
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-literal">False</span> <span class="hljs-keyword">or</span> <span class="hljs-literal">False</span>
|
||
<span class="hljs-literal">False</span>
|
||
</code></pre>
|
||
<p><strong><code>and</code></strong></p>
|
||
<p>The logical <code>and</code> operator returns <code>True</code> if the logical state of both the operands
|
||
is <code>True</code>.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-literal">True</span> <span class="hljs-keyword">and</span> <span class="hljs-literal">True</span>
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-literal">True</span> <span class="hljs-keyword">and</span> <span class="hljs-literal">False</span>
|
||
<span class="hljs-literal">False</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">bool</span>(<span class="hljs-number">10</span> <span class="hljs-keyword">and</span> <span class="hljs-number">20</span>)
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">bool</span>(<span class="hljs-number">1</span> <span class="hljs-keyword">and</span> <span class="hljs-number">0</span>)
|
||
<span class="hljs-literal">False</span>
|
||
</code></pre>
|
||
<h2 id="identity-operators">Identity Operators<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#identity-operators">#</a></h2>
|
||
<p>We have already witnessed how Python treats every value or data item as an object.</p>
|
||
<p>The relational operator <code>==</code> can be used to test whether the operands contain the same value.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>n = <span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span>n2 = <span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span>n == n2
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<p>This operator however does not check if both the operands are referring to the same object or different
|
||
objects.</p>
|
||
<p>The identity operators <code>is</code> and <code>is not</code> are used to test whether two objects have
|
||
the same or different identity (pointing to the same location in memory) respectively.</p>
|
||
<p><code>a is b</code> is equivalent to <code>id(a) == id(b)</code>, where <code>id()</code> is the built-in
|
||
function which returns the identity of an object.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>n = <span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span>n2 = <span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span>n <span class="hljs-keyword">is</span> n2
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<p>In the above example, both variables <code>n</code> and <code>n2</code> point to that same memory
|
||
location (same object).</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
|
||
<span class="hljs-meta">>>> </span>l2 = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
|
||
<span class="hljs-meta">>>> </span>l == l2
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span>l <span class="hljs-keyword">is</span> l2
|
||
<span class="hljs-literal">False</span>
|
||
</code></pre>
|
||
<p>In the above example, both lists <code>l</code> and <code>l2</code> although contain items with same
|
||
values, are actually two different objects occupying different memory locations.</p>
|
||
<h2 id="membership-operators">Membership Operators<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#membership-operators">#</a></h2>
|
||
<p>The operators <code>in</code> and <code>not in</code> test whether a value is present or not present in
|
||
an iterable (string, list, tuple, set, dictionary).</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-number">1</span> <span class="hljs-keyword">in</span> [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"ed"</span> <span class="hljs-keyword">in</span> [<span class="hljs-string">"ed"</span>, <span class="hljs-string">"py"</span>, <span class="hljs-string">"hi"</span>]
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"ed"</span> <span class="hljs-keyword">in</span> (<span class="hljs-string">"ed"</span>, <span class="hljs-string">"py"</span>, <span class="hljs-string">"hi"</span>)
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">'ed'</span> <span class="hljs-keyword">in</span> {<span class="hljs-string">'ed'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'py'</span>: <span class="hljs-number">2</span>}
|
||
<span class="hljs-literal">True</span>
|
||
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"pen"</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> [<span class="hljs-string">"pencil"</span>, <span class="hljs-string">"ink"</span>]
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"pen"</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> [<span class="hljs-string">"pen"</span>, <span class="hljs-string">"ink"</span>]
|
||
<span class="hljs-literal">False</span>
|
||
</code></pre>
|
||
<h2 id="expressions">Expressions<a aria-hidden class="header-link" tabindex="-1" href="#expressions">#</a>
|
||
</h2>
|
||
<p>Literals (constants), identifiers (variables) and operators can be combined to form an expression which
|
||
always evaluates to a single value.</p>
|
||
<p>For example, <code>40 + marks</code> is an expression containing a literal (<code>40</code>), a variable
|
||
(<code>marks</code>) and an operator (<code>+</code>).</p>
|
||
<p>Some valid expressions are provided below:</p>
|
||
<ul>
|
||
<li><code>10</code></li>
|
||
<li><code>a</code></li>
|
||
<li><code>-a</code></li>
|
||
<li><code>a - 10</code></li>
|
||
<li><code>a + b</code></li>
|
||
<li><code>4.0 * 3.5</code></li>
|
||
<li><code>a == b</code></li>
|
||
<li><code>c in d</code></li>
|
||
<li><code>a is T</code></li>
|
||
<li><code>"Hello" + "World"</code></li>
|
||
<li><code>15 - a*4</code></li>
|
||
<li><code>3*num + 9/4 - 10%count**2</code></li>
|
||
</ul>
|
||
<p>As shown above, standalone literals (like <code>10</code>) and variables (like <code>a</code>) are
|
||
considered as expressions, but standalone operators are not expressions.</p>
|
||
<h3 id="chained-expression">Chained Expression<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#chained-expression">#</a></h3>
|
||
<p>Comparison operators can be chained together in Python.</p>
|
||
<p>For example, <code>lower <= age <= upper</code> is a valid chained expression which is
|
||
equivalent to the expression -</p>
|
||
<p><code>lower <= age and age <= upper</code>.</p>
|
||
<p>If <code>a</code>, <code>b</code>, <code>c</code>, …, <code>y</code>, <code>z</code> are expressions and
|
||
<code>op1</code>, <code>op2</code>, …, <code>opN</code> are comparison operators, then the chained
|
||
expression <code>a op1 b op2 c ... y opN z</code> is equivalent to
|
||
<code>a op1 b and b op2 c and ... y opN z</code>.
|
||
</p>
|
||
<h3 id="conditional-expression">Conditional Expression<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#conditional-expression">#</a></h3>
|
||
<p>Python does not have ternary operators (<code>?:</code>) like other programming languages. Hence, the
|
||
keywords <code>if</code> and <code>else</code> are used to create conditional expressions which
|
||
evaluates to a value based on the given condition.</p>
|
||
<p>For example,</p>
|
||
<pre><code class="hljs language-python">var = t_val <span class="hljs-keyword">if</span> cond <span class="hljs-keyword">else</span> f_val
|
||
</code></pre>
|
||
<p>If the above condition <code>cond</code> evaluates to <code>True</code>, then the variable
|
||
<code>var</code> is assigned <code>t_val</code>, else it is assigned <code>f_val</code>.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>value = <span class="hljs-number">1</span> <span class="hljs-keyword">if</span> <span class="hljs-number">2</span> > <span class="hljs-number">3</span> <span class="hljs-keyword">else</span> -<span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span>value
|
||
-<span class="hljs-number">1</span>
|
||
</code></pre>
|
||
<h2 id="operator-precedence-with-examples">Operator Precedence with Examples<a aria-hidden
|
||
class="header-link" tabindex="-1" href="#operator-precedence-with-examples">#</a></h2>
|
||
<p>While studying mathematics in middle school, we came across the <strong>BODMAS</strong> (Bracket, Of,
|
||
Division, Multiplication, Addition, and Subtraction) rule which helps us in understanding how
|
||
mathematical expressions are computed in the presence of multiple operators (<code>of</code>,
|
||
<code>x</code>, <code>/</code>, <code>+</code>, <code>-</code>).
|
||
</p>
|
||
<p>In Python, we have a large number of operators and a similar rule to determine the order of evaluation of
|
||
an expression. This is known as <strong>operator precedence</strong> where the operator with higher
|
||
precedence is evaluated before the operator with lower precedence in an expression.</p>
|
||
<p>The table below presents the precedence of operators in Python from highest to lowest. Operators in the
|
||
same row have the same precedence, so in such cases the expression is evaluated from left to right.</p>
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th>Operator</th>
|
||
<th>Description</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr>
|
||
<td><code>(expressions...)</code></td>
|
||
<td>Parenthesized expression (Group)</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>**</code></td>
|
||
<td>Exponentiation</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>+x</code>, <code>-x</code>, <code>~x</code></td>
|
||
<td>Unary positive, Unary negative, Bitwise <code>NOT</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>*</code>, <code>@</code>, <code>/</code>, <code>//</code>, <code>%</code></td>
|
||
<td>Multiplication, Matrix multiplication, Division, Floor division, Remainder</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>+</code>, <code>-</code></td>
|
||
<td>Addition, Subtraction</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code><<</code>, <code>>></code></td>
|
||
<td>Shifts</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>&</code></td>
|
||
<td>Bitwise <code>AND</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>^</code></td>
|
||
<td>Bitwise <code>XOR</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>|</code></td>
|
||
<td>Bitwise <code>OR</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>in</code>, <code>not in</code>, <code>is</code>, <code>is not</code>,
|
||
<code><</code>, <code><=</code>, <code>></code>, <code>>=</code>, <code>!=</code>,
|
||
<code>==</code>
|
||
</td>
|
||
<td>Membership, Identity & Comparisons</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>not x</code></td>
|
||
<td>Boolean <code>NOT</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>and</code></td>
|
||
<td>Boolean <code>AND</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>or</code></td>
|
||
<td>Boolean <code>OR</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>:=</code></td>
|
||
<td>Assignment expression</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
<h3 id="exercises">Exercises<a aria-hidden class="header-link" tabindex="-1" href="#exercises">#</a></h3>
|
||
<p><strong>Example 1</strong></p>
|
||
<p>Evaluate the expression</p>
|
||
<p><code>15 - 2 * 4</code></p>
|
||
<p><strong>Solution</strong></p>
|
||
<p>Step: <code>*</code> has higher precedence over <code>-</code><br><code>15 - 2 * 4</code><br>=
|
||
<code>15 - 8</code><br>= <code>7</code>
|
||
</p>
|
||
<p><strong>Example 2</strong></p>
|
||
<p>Evaluate the expression</p>
|
||
<p><code>15 - 2 + 4</code></p>
|
||
<p><strong>Solution</strong></p>
|
||
<p>Step: <code>-</code> and <code>+</code> have the same order of precedence so the expression is evaluated
|
||
left to right<br><code>15 - 2 + 4</code><br>= <code>13 + 4</code><br>= <code>17</code></p>
|
||
<p><strong>Example 3</strong></p>
|
||
<p>Evaluate the expression</p>
|
||
<p><code>15 - (2 + 4)</code></p>
|
||
<p><strong>Solution</strong></p>
|
||
<p>Parantesized expression <code>(...)</code> has the highest precedence so <code>+</code> is evaluated
|
||
first<br><code>15 - (2 + 4)</code><br>= <code>15 - 6</code><br>= <code>9</code></p>
|
||
<p><strong>Example 4</strong></p>
|
||
<p>Evaluate the expression</p>
|
||
<p><code>3 * 2 + 9 / 4 - 10 % 2 ** 2</code></p>
|
||
<p><strong>Step 1</strong></p>
|
||
<p><code>**</code> takes precedence<br><code>3 * 2 + 9 / 4 - 10 % 2 ** 2</code><br>=
|
||
<code>3 * 2 + 9 / 4 - 10 % 4</code>
|
||
</p>
|
||
<p><strong>Step 2</strong></p>
|
||
<p><code>*</code>, <code>/</code> and <code>%</code> have the same precedence so they are evaluated left to
|
||
right.<br><code>3 * 2 + 9 / 4 - 10 % 4</code><br>= <code>6 + 2.25 - 2</code></p>
|
||
<p><strong>Step 3</strong></p>
|
||
<p><code>+</code> and <code>-</code> evaluation<br><code>6 + 2.25 - 2</code><br>= <code>6.25</code></p>
|
||
<p><strong>Example 5</strong></p>
|
||
<p>Evaluate the expression</p>
|
||
<p><code>20 / 4 // 2 * 2 - 4 + 20</code></p>
|
||
<p><strong>Step 1</strong></p>
|
||
<p><code>*</code>, <code>/</code>, <code>//</code> and <code>%</code> have the same precedence so they are
|
||
evaluated left to right.<br><code>20 / 4 // 2 * 2 - 4 + 20</code><br>=
|
||
<code>5 // 2 * 2 - 4 + 20</code><br>= <code>2 * 2 - 4 + 20</code><br>= <code>4 - 4 + 20</code>
|
||
</p>
|
||
<p><strong>Step 2</strong></p>
|
||
<p><code>+</code> and <code>-</code> evaluation<br><code>4 - 4 + 20</code><br>= <code>20</code></p>
|
||
<p><strong>Example 6</strong></p>
|
||
<p>Evaluate the expression</p>
|
||
<p><code>not 6 <= 4 and 3 ** 3 > 12 / 3</code></p>
|
||
<p><strong>Step 1</strong></p>
|
||
<p><code>**</code> takes precedence<br><code>not 6 <= 4 and 3 ** 3 > 12 / 3</code><br>=
|
||
<code>not 6 <= 4 and 27 > 12 / 3</code>
|
||
</p>
|
||
<p><strong>Step 2</strong></p>
|
||
<p><code>/</code> is next in line of precedence<br><code>not 6 <= 4 and 27 > 12 / 3</code><br>=
|
||
<code>not 6 <= 4 and 27 > 4</code>
|
||
</p>
|
||
<p><strong>Step 3</strong></p>
|
||
<p>Comparison operators are next in line of precedence<br><code>not 6 <= 4 and 27 > 4</code><br>=
|
||
<code>not False and True</code>
|
||
</p>
|
||
<p><strong>Step 4</strong></p>
|
||
<p>Boolean <code>NOT</code> is evaluated<br><code>not False and True</code><br>= <code>True and True</code>
|
||
</p>
|
||
<p><strong>Step 5</strong></p>
|
||
<p>Boolean <code>AND</code> is evaluated<br><code>True and True</code><br>= <code>True</code></p>
|
||
<h1 id="errors--exception-handling">Errors & Exception Handling<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#errors--exception-handling">#</a></h1>
|
||
<h2 id="error-types">Error Types<a aria-hidden class="header-link" tabindex="-1" href="#error-types">#</a>
|
||
</h2>
|
||
<p>A program contains <strong>"bug(s)"</strong> when it is unable to execute or produces an output which is
|
||
different from what is expected. These bugs are generally introduced by a programmer unknowingly.</p>
|
||
<p>The process of identifying and eliminating these bugs or errors is known as <strong>debugging</strong>.
|
||
</p>
|
||
<p>The three major types of errors are:</p>
|
||
<ul>
|
||
<li>Syntax Error</li>
|
||
<li>Runtime Error</li>
|
||
<li>Logical Error</li>
|
||
</ul>
|
||
<h2 id="syntax-error">Syntax Error<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#syntax-error">#</a></h2>
|
||
<p>Syntax error occurs when the program contains any statement that does not follow the prescribed Python
|
||
rules or syntax which makes it difficult for the Python interpreter to parse (understand) and execute
|
||
it.</p>
|
||
<p>Some common syntax errors are:</p>
|
||
<ul>
|
||
<li>Missing/Misspelled keyword</li>
|
||
<li>Missing colon or brackets</li>
|
||
<li>Empty block</li>
|
||
<li>Incorrect position of keyword</li>
|
||
<li>Incorrect block indentation</li>
|
||
</ul>
|
||
<h3 id="script-mode">Script Mode<a aria-hidden class="header-link" tabindex="-1" href="#script-mode">#</a>
|
||
</h3>
|
||
<p>When a code containing syntactically incorrect statement is executed using script mode via IDLE, an error
|
||
dialog box is displayed.</p>
|
||
<p><img src="images/0702a.png" alt="Syntax Error Dialog"></p>
|
||
<p>On closing the dialog box, the incorrect part of the code, the potential cause of error, is highlighted
|
||
in red.</p>
|
||
<p><img src="images/0702b.png" alt="Syntax Error Highlighted"></p>
|
||
<p>This error has to be rectified to execute the program correctly.</p>
|
||
<h3 id="interactive-mode">Interactive Mode<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#interactive-mode">#</a></h3>
|
||
<p>When a syntactically incorrect statement is executed in the Python console (interactive mode), the Python
|
||
interpreter displays it and also adds a little arrow (<code>^</code>) pointing at the entry point or
|
||
token where the error was detected.</p>
|
||
<p><strong>Example</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">while</span> <span class="hljs-literal">True</span> <span class="hljs-built_in">print</span>(<span class="hljs-string">'Hi!'</span>)
|
||
File <span class="hljs-string">"<stdin>"</span>, line <span class="hljs-number">1</span>
|
||
<span class="hljs-keyword">while</span> <span class="hljs-literal">True</span> <span class="hljs-built_in">print</span>(<span class="hljs-string">'Hi!'</span>)
|
||
^
|
||
SyntaxError: invalid syntax
|
||
</code></pre>
|
||
<p>In the above example there is a syntax error with <code>^</code> pointing to <code>print</code> function
|
||
which the parser is unable to understand as there is a missing <code>:</code> (colon) after
|
||
<code>True</code>.
|
||
</p>
|
||
<h2 id="runtime-error">Runtime Error<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#runtime-error">#</a></h2>
|
||
<p>A runtime error occurs when the program is terminated prematurely by the Python interpreter as it is
|
||
unable to execute a statement although it is correct syntactically.</p>
|
||
<p>Some runtime error examples are:</p>
|
||
<ul>
|
||
<li><strong>ImportError</strong>: Raised when the <code>import</code> statement has trouble loading a
|
||
module or any definition from a module.</li>
|
||
<li><strong>IOError</strong>: Raised when the interpreter is not able to open the file specified in the
|
||
program.</li>
|
||
<li><strong>ZeroDivisionError</strong>: Raised when a number is divided or mod by zero.</li>
|
||
<li><strong>NameError</strong>: Raised when an identifier is encountered which has not been defined.
|
||
</li>
|
||
<li><strong>ValueError</strong>: Raised when an argument or operand is of required data type, but has
|
||
undesired value.</li>
|
||
<li><strong>IndexError</strong>: Raised when the provided index in a sequence (string, list, tuple,
|
||
etc.) is out of range.</li>
|
||
<li><strong>KeyError</strong>: Raised when a dictionary key is not found in the set of existing keys.
|
||
</li>
|
||
<li><strong>TypeError</strong>: Raised while performing an operation on incompatible types.</li>
|
||
<li><strong>IndentationError</strong>: Raised when the indentation of a statement or code block is
|
||
incorrect.</li>
|
||
</ul>
|
||
<h3 id="runtime-error-examples">Runtime Error Examples<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#runtime-error-examples">#</a></h3>
|
||
<p><strong>ZeroDivisionError</strong></p>
|
||
<pre><code class="hljs language-python">n = <span class="hljs-number">100</span>
|
||
d = <span class="hljs-number">0</span>
|
||
<span class="hljs-built_in">print</span>(n/d)
|
||
</code></pre>
|
||
<pre><code class="hljs language-python">Traceback (most recent call last):
|
||
File <span class="hljs-string">"/Users/name/Desktop/test.py"</span>, line <span class="hljs-number">3</span>, <span class="hljs-keyword">in</span> <module>
|
||
<span class="hljs-built_in">print</span>(n/d)
|
||
ZeroDivisionError: division by zero
|
||
</code></pre>
|
||
<p><strong>NameError</strong></p>
|
||
<pre><code class="hljs language-python">n = <span class="hljs-number">100</span>
|
||
<span class="hljs-built_in">print</span>(d)
|
||
</code></pre>
|
||
<pre><code class="hljs language-python">Traceback (most recent call last):
|
||
File <span class="hljs-string">"/Users/name/Desktop/test.py"</span>, line <span class="hljs-number">2</span>, <span class="hljs-keyword">in</span> <module>
|
||
<span class="hljs-built_in">print</span>(d)
|
||
NameError: name <span class="hljs-string">'d'</span> <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> defined
|
||
</code></pre>
|
||
<p><strong>KeyError</strong></p>
|
||
<pre><code class="hljs language-python">d = {<span class="hljs-number">1</span>: <span class="hljs-string">"1st"</span>, <span class="hljs-number">2</span>: <span class="hljs-string">"2nd"</span>}
|
||
<span class="hljs-built_in">print</span>(d[<span class="hljs-number">3</span>])
|
||
</code></pre>
|
||
<pre><code class="hljs language-python">Traceback (most recent call last):
|
||
File <span class="hljs-string">"/Users/name/Desktop/test.py"</span>, line <span class="hljs-number">2</span>, <span class="hljs-keyword">in</span> <module>
|
||
<span class="hljs-built_in">print</span>(d[<span class="hljs-number">3</span>])
|
||
KeyError: <span class="hljs-number">3</span>
|
||
</code></pre>
|
||
<p><strong>TypeError</strong></p>
|
||
<pre><code class="hljs language-python">n =<span class="hljs-number">1</span>
|
||
s = <span class="hljs-string">"a"</span>
|
||
tot = n + s
|
||
</code></pre>
|
||
<pre><code class="hljs language-python">Traceback (most recent call last):
|
||
File <span class="hljs-string">"/Users/name/Desktop/test.py"</span>, line <span class="hljs-number">3</span>, <span class="hljs-keyword">in</span> <module>
|
||
tot = n + s
|
||
TypeError: unsupported operand <span class="hljs-built_in">type</span>(s) <span class="hljs-keyword">for</span> +: <span class="hljs-string">'int'</span> <span class="hljs-keyword">and</span> <span class="hljs-string">'str'</span>
|
||
</code></pre>
|
||
<h2 id="logical-error">Logical Error<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#logical-error">#</a></h2>
|
||
<p>Logical error or Semantic error is caused when the issue lies in the underlying meaning of the code which
|
||
leads to an incorrect output.</p>
|
||
<p>As compared to syntax or runtime error there is no termination of the program.</p>
|
||
<p>Debugging a logical error requires inspection of the entire code as no guiding error message is
|
||
displayed.</p>
|
||
<h3 id="example">Example<a aria-hidden class="header-link" tabindex="-1" href="#example">#</a></h3>
|
||
<p>Let us write a program to calculate the average of two numbers</p>
|
||
<pre><code class="hljs language-python">n = <span class="hljs-number">10</span>
|
||
m = <span class="hljs-number">20</span>
|
||
avg = n + m / <span class="hljs-number">2</span>
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Average:"</span>, avg)
|
||
</code></pre>
|
||
<p>On executing the script the result is</p>
|
||
<pre><code>Average: 20.0
|
||
</code></pre>
|
||
<p>This is incorrect as there is a logical error in the code.</p>
|
||
<p>Since <code>/</code> has a higher precedence over <code>+</code>, <code>m / 2</code> is being computed
|
||
first.</p>
|
||
<p>We can modify the code to get rid of the logical error.</p>
|
||
<pre><code class="hljs language-python">n = <span class="hljs-number">10</span>
|
||
m = <span class="hljs-number">20</span>
|
||
avg = (n + m) / <span class="hljs-number">2</span>
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Average:"</span>, avg)
|
||
</code></pre>
|
||
<p>On executing the script, we now obtain the correct result</p>
|
||
<pre><code>Average: 15.0
|
||
</code></pre>
|
||
<h2 id="exceptions">Exceptions<a aria-hidden class="header-link" tabindex="-1" href="#exceptions">#</a></h2>
|
||
<p>We have witnessed that even if a program is syntactically correct, its execution may lead to a run-time
|
||
error.</p>
|
||
<p>This error detected during execution is known as an <strong>exception</strong> which is an object created
|
||
by the Python interpreter containing information regarding the error like type of error, file name and
|
||
the location of the error (line number, token) in the program.</p>
|
||
<p>Some of the built-in exceptions that are raised by the Python interpreter are - <code>ImportError</code>,
|
||
<code>ZeroDivisionError</code>, <code>NameError</code>, <code>ValueError</code>,
|
||
<code>IndexError</code>, <code>KeyError</code>, <code>TypeError</code> and
|
||
<code>IndentationError</code>.
|
||
</p>
|
||
<p>Apart from the Python interpreter, a programmer can also trigger and raise an exception (along with a
|
||
custom message) in the code using <code>raise</code> or <code>assert</code> statement.</p>
|
||
<h3 id="raise">raise<a aria-hidden class="header-link" tabindex="-1" href="#raise">#</a></h3>
|
||
<p>The <code>raise</code> statement can be used to throw an exception in a program. The exception may or may
|
||
not contain the custom error message (recommended).</p>
|
||
<p>Let us consider a program which accepts two numbers (<code>a</code> and <code>b</code>) from the user and
|
||
prints the result <code>a/b</code>.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">a = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter a: "</span>))
|
||
b = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter b: "</span>))
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"a/b ="</span>, a/b)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Enter a: 10
|
||
Enter b: 0
|
||
Traceback (most recent call last):
|
||
File "/Users/name/test.py",
|
||
line 3, in <module>
|
||
print("a/b =", a/b)
|
||
ZeroDivisionError: division by zero
|
||
</code></pre>
|
||
<p>It can be observed that the Python interpreter raises a <code>ZeroDivisionError</code> when the value of
|
||
<code>b</code> is entered as <code>0</code>.
|
||
</p>
|
||
<p>Now we can modify the above code to raise an exception for such scenarios.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">a = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter a: "</span>))
|
||
b = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter b: "</span>))
|
||
<span class="hljs-keyword">if</span> b==<span class="hljs-number">0</span>:
|
||
<span class="hljs-keyword">raise</span> Exception()
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"a/b ="</span>, a/b)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Enter a: 10
|
||
Enter b: 0
|
||
Traceback (most recent call last):
|
||
File "/Users/name/test.py",
|
||
line 4, in <module>
|
||
raise Exception()
|
||
Exception
|
||
</code></pre>
|
||
<p>An exception is raised, but it is not helpful.</p>
|
||
<p>Let us add some custom error message.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">a = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter a: "</span>))
|
||
b = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter b: "</span>))
|
||
<span class="hljs-keyword">if</span> b==<span class="hljs-number">0</span>:
|
||
<span class="hljs-keyword">raise</span> Exception(<span class="hljs-string">"b is zero"</span>)
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"a/b ="</span>, a/b)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Enter a: 10
|
||
Enter b: 0
|
||
Traceback (most recent call last):
|
||
File "/Users/name/test.py",
|
||
line 4, in <module>
|
||
raise Exception("b is zero")
|
||
Exception: b is zero
|
||
</code></pre>
|
||
<p>We can also raise any specific type of error as per the program logic as shown below:</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">a = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter a: "</span>))
|
||
b = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter b: "</span>))
|
||
<span class="hljs-keyword">if</span> b==<span class="hljs-number">0</span>:
|
||
<span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">"The value of b cannot be zero"</span>)
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"a/b ="</span>, a/b)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Enter a: 10
|
||
Enter b: 0
|
||
Traceback (most recent call last):
|
||
File "/Users/name/test.py",
|
||
line 4, in <module>
|
||
raise ValueError("The value of b cannot be zero")
|
||
ValueError: The value of b cannot be zero
|
||
</code></pre>
|
||
<h3 id="assert">assert<a aria-hidden class="header-link" tabindex="-1" href="#assert">#</a></h3>
|
||
<p>An <code>assert</code> statement is often used during code development to act like a safety valve which
|
||
notifies the programmer in case the test expression is evaluated as <code>False</code>.</p>
|
||
<p>If the test expression’s value is <code>True</code>, the code execution continues normally.</p>
|
||
<p>An <code>AssertionError</code> is raised if the value is <code>False</code>.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">a = <span class="hljs-number">3</span>
|
||
b = <span class="hljs-number">4</span>
|
||
<span class="hljs-keyword">assert</span> a == b
|
||
c = <span class="hljs-number">5</span>
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Traceback (most recent call last):
|
||
File "/Users/name/test.py",
|
||
line 3, in <module>
|
||
assert a == b
|
||
AssertionError
|
||
</code></pre>
|
||
<p>The statement also allows for a message to be attached to the <code>AssertionError</code>.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">a = <span class="hljs-number">3</span>
|
||
b = <span class="hljs-number">4</span>
|
||
<span class="hljs-keyword">assert</span> a == b, <span class="hljs-string">"a is not equal to b"</span>
|
||
c = <span class="hljs-number">5</span>
|
||
</code></pre>
|
||
<p>Output:</p>
|
||
<pre><code>Traceback (most recent call last):
|
||
File "/Users/name/test.py",
|
||
line 3, in <module>
|
||
assert a == b, "a is not equal to b"
|
||
AssertionError: a is not equal to b
|
||
</code></pre>
|
||
<h2 id="exception-handling">Exception Handling<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#exception-handling">#</a></h2>
|
||
<p>Exception handling is the process of properly handling an exception which can potentially crash a program
|
||
during execution.</p>
|
||
<p>When an error occurs, the program throws an exception.</p>
|
||
<p>The runtime system attempts to find an <strong>exception handler</strong>, a block of code that can
|
||
handle a particular type of error. Once located, the suitable exception handler <strong>catches the
|
||
exeception</strong> and executes the code block which can attempt to recover from the error. In case
|
||
the error is unrecoverable, the handler provides a way to gently exit the program.</p>
|
||
<p>The <code>try</code> statement in Python specifies the exception handlers and/or cleanup code for a code
|
||
block.</p>
|
||
<p>The various parts of a try statement are:</p>
|
||
<ul>
|
||
<li><code>try</code> block: The block of statements within which an exception might be thrown.</li>
|
||
<li><code>except</code> clause(s): One or more exception handlers. Each <code>except</code> clause
|
||
handles a particular type of exception. In case an exception of a particular type occurs in the
|
||
<code>try</code> block, the corresponding <code>except</code> clause code block is executed.
|
||
</li>
|
||
<li><code>else</code> clause: An optional <code>else</code> clause can also be included after the last
|
||
<code>except</code> block. In case no exception is raised, none of the <code>except</code> blocks
|
||
are executed. In this case, the <code>else</code> code block is executed.
|
||
</li>
|
||
<li><code>finally</code> clause: An optional <code>finally</code> clause can be added at the end of the
|
||
try statement which includes a block of statements that are executed regardless of whether or not
|
||
any error occured inside the try block. This block is usually setup for code cleanup and closing all
|
||
open file objects.</li>
|
||
</ul>
|
||
<p>Here's the general form of these statements:</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">try</span>:
|
||
[code block]
|
||
<span class="hljs-keyword">except</span> [exception1 [<span class="hljs-keyword">as</span> identifier1]]:
|
||
[exception code block <span class="hljs-number">1</span>]
|
||
<span class="hljs-keyword">except</span> [exception2 [<span class="hljs-keyword">as</span> identifier2]]:
|
||
[exception code block <span class="hljs-number">2</span>]
|
||
...
|
||
...
|
||
<span class="hljs-keyword">else</span>:
|
||
[code block executes <span class="hljs-keyword">if</span> no error]
|
||
<span class="hljs-keyword">finally</span>:
|
||
[code block always executed]
|
||
</code></pre>
|
||
<h1 id="control-flow">Control Flow<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#control-flow">#</a></h1>
|
||
<h2 id="introduction-to-control-flow">Introduction to Control Flow<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#introduction-to-control-flow">#</a></h2>
|
||
<p>A simple Python program can be treated as a block of code where each statement is executed by the Python
|
||
interpreter in a sequential order from top to bottom.</p>
|
||
<p>But, in real world we would like to have some control over the execution of code such as:</p>
|
||
<ul>
|
||
<li>skip or execute a block (set of statements) based on certain conditions</li>
|
||
<li>execute a block repeatedly</li>
|
||
<li>redirect execution to another set of statements</li>
|
||
<li>breaking up the execution</li>
|
||
</ul>
|
||
<p>This control over the flow of execution is provided by <strong>Control Flow Statements</strong>.</p>
|
||
<p>They can be categorized as:</p>
|
||
<ul>
|
||
<li>Sequential</li>
|
||
<li>Selection</li>
|
||
<li>Iteration/Repetition</li>
|
||
<li>Jump</li>
|
||
<li>Procedural Abstraction - A sequence of statements are referenced as a single function or method call
|
||
</li>
|
||
<li>Recursion - Calling a method/function in the same method/function</li>
|
||
<li>Exception Handling</li>
|
||
</ul>
|
||
<h2 id="sequential-flow">Sequential Flow<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#sequential-flow">#</a></h2>
|
||
<p>By default the code statements in Python are executed in Sequential order.</p>
|
||
<p>The below flow chart demonstrates how 3 statements are executed in a sequential order.</p>
|
||
<p><img src="images/0802a.png" alt="Sequential Flow"></p>
|
||
<p>For example,</p>
|
||
<pre><code class="hljs language-python">a = <span class="hljs-number">2</span>
|
||
b = <span class="hljs-number">3</span>
|
||
c = a*b
|
||
<span class="hljs-built_in">print</span>(c)
|
||
</code></pre>
|
||
<p>The above code will be executed in the following sequential order:</p>
|
||
<p><img src="images/0802b.png" alt="Sequential Flow of Code"></p>
|
||
<h2 id="selection-statements-if--else">Selection Statements: if .. else<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#selection-statements-if--else">#</a></h2>
|
||
<p>Selection statements, also known as Decision making statements, control the flow of a program based on
|
||
the outcome of one or many test expression(s). If the condition is satisfied (<code>True</code>) then
|
||
the code block is executed. There is also a provision to execute another code block if the condition is
|
||
not satisfied.</p>
|
||
<p>This process can be demonstrated using the below flowchart:</p>
|
||
<p><img src="images/0803a.png" alt="Selection Flow"></p>
|
||
<p>Python supports <code>if</code> compound statement which provides this control. The <code>if</code>
|
||
statement comprises:</p>
|
||
<ul>
|
||
<li><code>if</code> keyword followed by the test expression, a colon <code>:</code> and an indented
|
||
block of code which gets executed if the condition is satisfied</li>
|
||
<li>(optional) one or many <code>elif</code> clause followed by their test conditions and their
|
||
corresponding code blocks</li>
|
||
<li>(optional) <code>else</code> clause and the corresponding code block which gets executed if none of
|
||
the above conditions (<code>if</code>, <code>elif</code>) are satisfied</li>
|
||
</ul>
|
||
<p>An example <code>if</code> statement is provided below:</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-string">'''
|
||
age - age of loan applicant
|
||
emp - is employed (bool)
|
||
cscore - credit scrore of applicant
|
||
'''</span>
|
||
result = <span class="hljs-literal">None</span>
|
||
<span class="hljs-keyword">if</span> age < <span class="hljs-number">26</span> <span class="hljs-keyword">and</span> <span class="hljs-keyword">not</span> emp:
|
||
result = <span class="hljs-string">"Loan rejected"</span>
|
||
<span class="hljs-keyword">elif</span> age > <span class="hljs-number">35</span> <span class="hljs-keyword">and</span> cscore < <span class="hljs-number">600</span>:
|
||
result = <span class="hljs-string">"Loan rejected"</span>
|
||
<span class="hljs-keyword">else</span>:
|
||
result = <span class="hljs-string">"Loan approved"</span>
|
||
<span class="hljs-built_in">print</span>(result)
|
||
</code></pre>
|
||
<p>The control flow view of the above code is:</p>
|
||
<p><img src="images/0803b.png" alt="Selection in Flow of Code"></p>
|
||
<h3 id="examples">Examples<a aria-hidden class="header-link" tabindex="-1" href="#examples">#</a></h3>
|
||
<p>Let us go through some programming problems which utilize selection statements.</p>
|
||
<p><strong>1. Absolute Value</strong></p>
|
||
<p>Write a program to output the magnitude of difference between two numbers using conditional statement.
|
||
</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">n1 = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter 1st number: "</span>))
|
||
n2 = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter 2nd number: "</span>))
|
||
|
||
<span class="hljs-keyword">if</span> n1 > n2:
|
||
diff = n1 - n2
|
||
<span class="hljs-keyword">else</span>:
|
||
diff = n2 - n1
|
||
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"The difference of"</span>, n1, <span class="hljs-string">"and"</span>, n2, <span class="hljs-string">"is"</span>, diff)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Enter 1st number: 12
|
||
Enter 2nd number: 15
|
||
The difference of 12 and 15 is 3
|
||
</code></pre>
|
||
<p><strong>2. Sorting 3 Numbers</strong></p>
|
||
<p>Write a program to accept 3 numbers from the user and print them in ascending order of value.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">a = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter 1st number: "</span>))
|
||
b = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter 2nd number: "</span>))
|
||
c = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter 3rd number: "</span>))
|
||
|
||
<span class="hljs-keyword">if</span> b < a:
|
||
<span class="hljs-comment"># Swapping the values of a and b</span>
|
||
a, b = b, a
|
||
|
||
<span class="hljs-keyword">if</span> c < b:
|
||
b, c = c, b
|
||
<span class="hljs-keyword">if</span> b < a:
|
||
a, b = b, a
|
||
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"The numbers in sorted order:"</span>, a, <span class="hljs-string">","</span>, b, <span class="hljs-string">","</span>, c)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Enter 1st number: 9
|
||
Enter 2nd number: 2
|
||
Enter 3rd number: 6
|
||
The numbers in sorted order: 2 , 6 , 9
|
||
</code></pre>
|
||
<p><strong>3. Divisibility</strong></p>
|
||
<p>Write a program to accept two numbers and test if the first number is divisible by the second number.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">a = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter 1st number: "</span>))
|
||
b = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter 2nd number: "</span>))
|
||
|
||
<span class="hljs-keyword">if</span> a % b == <span class="hljs-number">0</span>:
|
||
<span class="hljs-built_in">print</span>(a, <span class="hljs-string">"is divisible by"</span>, b)
|
||
<span class="hljs-keyword">else</span>:
|
||
<span class="hljs-built_in">print</span>(a, <span class="hljs-string">"is not divisible by"</span>, b)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Enter 1st number: 9
|
||
Enter 2nd number: 2
|
||
9 is not divisible by 2
|
||
|
||
Enter 1st number: 9
|
||
Enter 2nd number: 3
|
||
9 is divisible by 3
|
||
</code></pre>
|
||
<h2 id="iteration-for">Iteration: for<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#iteration-for">#</a></h2>
|
||
<p>Iteration statements, also known as Looping statements, allow repeated execution of a code block.</p>
|
||
<p>Python provides <code>for</code> and <code>while</code> statements to perform iteration.</p>
|
||
<p>The <code>for</code> statement can be used to iterate over the items of a sequence (<code>list</code>,
|
||
<code>string</code>, <code>tuple</code>, <code>range</code>). It can also be used to iterate over
|
||
unordered sequences like <code>set</code> and <code>dict</code>.
|
||
</p>
|
||
<p>This process can be demonstrated using the below flowchart:</p>
|
||
<p><img src="images/0804a.png" alt="Iteration in Flow of Code Python"></p>
|
||
<p>Let us go through some code examples to demonstrate how <code>for</code> statement can be used to iterate
|
||
over sequences.</p>
|
||
<h3 id="list-iteration">List Iteration<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#list-iteration">#</a></h3>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">cars = [<span class="hljs-string">"Hyundai"</span>, <span class="hljs-string">"Honda"</span>,
|
||
<span class="hljs-string">"Ford"</span>, <span class="hljs-string">"Toyota"</span>,
|
||
<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Volkswagen"</span>]
|
||
<span class="hljs-keyword">for</span> make <span class="hljs-keyword">in</span> cars:
|
||
<span class="hljs-built_in">print</span>(make)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Hyundai
|
||
Honda
|
||
Ford
|
||
Toyota
|
||
BMW
|
||
Volkswagen
|
||
</code></pre>
|
||
<h3 id="tuple-iteration">Tuple Iteration<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#tuple-iteration">#</a></h3>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">cars = (<span class="hljs-string">"Hyundai"</span>, <span class="hljs-string">"Honda"</span>,
|
||
<span class="hljs-string">"Ford"</span>, <span class="hljs-string">"Toyota"</span>,
|
||
<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Volkswagen"</span>)
|
||
<span class="hljs-keyword">for</span> make <span class="hljs-keyword">in</span> cars:
|
||
<span class="hljs-built_in">print</span>(make)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Hyundai
|
||
Honda
|
||
Ford
|
||
Toyota
|
||
BMW
|
||
Volkswagen
|
||
</code></pre>
|
||
<h3 id="string-iteration">String Iteration<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#string-iteration">#</a></h3>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">name = <span class="hljs-string">"python"</span>
|
||
<span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> name:
|
||
<span class="hljs-built_in">print</span>(char)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>p
|
||
y
|
||
t
|
||
h
|
||
o
|
||
n
|
||
</code></pre>
|
||
<h3 id="range-iteration">Range Iteration<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#range-iteration">#</a></h3>
|
||
<p>The <code>range</code> type represents an immutable sequence of numbers that is usually used in for loops
|
||
for looping a certain number of times. <code>range</code> object always take the same (small) amount of
|
||
memory, no matter the size of the range it represents, which is an advantage over a regular
|
||
<code>list</code> or <code>tuple</code>.
|
||
</p>
|
||
<p><strong>Syntax</strong>: <code>range(stop)</code> or<br><code>range(start, stop[, step])</code></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">range</span>(<span class="hljs-number">10</span>)
|
||
<span class="hljs-built_in">range</span>(<span class="hljs-number">0</span>, <span class="hljs-number">10</span>)
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">list</span>(<span class="hljs-built_in">range</span>(<span class="hljs-number">10</span>))
|
||
[<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">7</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>]
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">list</span>(<span class="hljs-built_in">range</span>(<span class="hljs-number">1</span>, <span class="hljs-number">10</span>, <span class="hljs-number">2</span>))
|
||
[<span class="hljs-number">1</span>, <span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">7</span>, <span class="hljs-number">9</span>]
|
||
</code></pre>
|
||
<p><code>range()</code> function is widely used in a <code>for</code> statement to control the number of
|
||
iterations and provide the index value (<code>i</code>) of each iteration.</p>
|
||
<p><strong>Example #1</strong></p>
|
||
<p>Print multiples of 5 starting from 0 to 20.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">5</span>):
|
||
<span class="hljs-built_in">print</span>(i*<span class="hljs-number">5</span>)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>0
|
||
5
|
||
10
|
||
15
|
||
20
|
||
</code></pre>
|
||
<p><strong>Example #2</strong></p>
|
||
<p>Print all integers from 2 to 5 including the boundary values.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">2</span>, <span class="hljs-number">6</span>):
|
||
<span class="hljs-built_in">print</span>(i)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>2
|
||
3
|
||
4
|
||
5
|
||
</code></pre>
|
||
<p><strong>Example #3</strong></p>
|
||
<p>Print all odd numbers between 2 and 10.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">3</span>, <span class="hljs-number">10</span>, <span class="hljs-number">2</span>):
|
||
<span class="hljs-built_in">print</span>(i)
|
||
</code></pre>
|
||
<p>or</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">2</span>, <span class="hljs-number">10</span>):
|
||
<span class="hljs-keyword">if</span> i % <span class="hljs-number">2</span> != <span class="hljs-number">0</span>:
|
||
<span class="hljs-built_in">print</span>(i)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>3
|
||
5
|
||
7
|
||
9
|
||
</code></pre>
|
||
<p><strong>Example #4</strong></p>
|
||
<p>Print the index of all occurrences of <code>o</code> in <code>python programming</code>.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">s = <span class="hljs-string">"python programming"</span>
|
||
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-built_in">len</span>(s)):
|
||
<span class="hljs-keyword">if</span> s[i] == <span class="hljs-string">"o"</span>:
|
||
<span class="hljs-built_in">print</span>(i)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>4
|
||
9
|
||
</code></pre>
|
||
<h3 id="exercises-1">Exercises<a aria-hidden class="header-link" tabindex="-1" href="#exercises-1">#</a>
|
||
</h3>
|
||
<p>Let us go through some programming problems which utilize the <code>for</code> iteration statement.</p>
|
||
<p><strong>1. Compound Interest</strong></p>
|
||
<p>Write a program to calculate the total compound interest payable for given principal, interest rate
|
||
(compounded annually) and total time (in years).</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">prin = <span class="hljs-built_in">float</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter the principal amount: "</span>))
|
||
rate = <span class="hljs-built_in">float</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter the annual interest rate: "</span>))
|
||
time = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter the loan duration (in years): "</span>))
|
||
|
||
amt = prin
|
||
<span class="hljs-keyword">for</span> n <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(time):
|
||
amt += rate*amt/<span class="hljs-number">100</span>
|
||
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Total interest payable:"</span>, amt - prin)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Enter the principal amount: 500000
|
||
Enter the annual interest rate: 5
|
||
Enter the loan duration (in years): 3
|
||
Total interest payable: 78812.5
|
||
</code></pre>
|
||
<p><strong>2. Factorial</strong></p>
|
||
<p>The factorial of a positive integer <code>n</code>, denoted by <code>n!</code>, is the product of all
|
||
positive integers less than or equal to
|
||
<code>n</code>.<br><code>n! = n×(n-1)×(n-2)...3×2×1</code><br>Write a program to calculate
|
||
<code>n!</code> for a given <code>n</code> (assume <code>n</code> is greater than <code>0</code>).
|
||
</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">n = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter n: "</span>))
|
||
|
||
factorial = <span class="hljs-number">1</span>
|
||
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">1</span>, n+<span class="hljs-number">1</span>):
|
||
factorial *= i
|
||
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"n! :"</span>, factorial)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Enter n: 6
|
||
n! : 720
|
||
</code></pre>
|
||
<h2 id="iteration-while">Iteration: while<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#iteration-while">#</a></h2>
|
||
<p><code>while</code> statement repeatedly executes a code block as long as the test condition is satisfied.
|
||
</p>
|
||
<p>Usually there is a statement at the end of the code block which updates the value of the variable being
|
||
used in the test expression, so the the loop does not execute infinitely.</p>
|
||
<p>A flowchart of the process is provided below:</p>
|
||
<p><img src="images/0805a.png" alt="while loop Iteration in Flow of Code"></p>
|
||
<p>For example, let us traverse a list and print the position(index) and value of each element until we
|
||
reach the end of the list.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">cars = [<span class="hljs-string">"Hyundai"</span>, <span class="hljs-string">"Honda"</span>,
|
||
<span class="hljs-string">"Ford"</span>, <span class="hljs-string">"Toyota"</span>,
|
||
<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Volkswagen"</span>]
|
||
i = <span class="hljs-number">0</span>
|
||
<span class="hljs-keyword">while</span> i<<span class="hljs-built_in">len</span>(cars):
|
||
<span class="hljs-built_in">print</span>(i, cars[i])
|
||
i+=<span class="hljs-number">1</span>
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>0 Hyundai
|
||
1 Honda
|
||
2 Ford
|
||
3 Toyota
|
||
4 BMW
|
||
5 Volkswagen
|
||
</code></pre>
|
||
<p>In the above example, the test condition is <code>i<len(cars)</code> and the update statement is
|
||
<code>i+=1</code>.
|
||
</p>
|
||
<h3 id="exercises-2">Exercises<a aria-hidden class="header-link" tabindex="-1" href="#exercises-2">#</a>
|
||
</h3>
|
||
<p>Let us go through some programming problems which utilize the <code>while</code> iteration statement.</p>
|
||
<p><strong>1. Compound Interest</strong></p>
|
||
<p>Write a program to calculate the total compound interest payable for given principal, interest rate
|
||
(compounded annually) and total time (in years).</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">prin = <span class="hljs-built_in">float</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter the principal amount: "</span>))
|
||
rate = <span class="hljs-built_in">float</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter the annual interest rate: "</span>))
|
||
time = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter the loan duration (in years): "</span>))
|
||
|
||
amt = prin
|
||
<span class="hljs-keyword">while</span> time > <span class="hljs-number">0</span>:
|
||
amt += rate*amt/<span class="hljs-number">100</span>
|
||
time = time - <span class="hljs-number">1</span>
|
||
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Total interest payable:"</span>, amt - prin)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Enter the principal amount: 500000
|
||
Enter the annual interest rate: 5
|
||
Enter the loan duration (in years): 3
|
||
Total interest payable: 78812.5
|
||
</code></pre>
|
||
<p><strong>2. Factorial</strong></p>
|
||
<p>The factorial of a positive integer <code>n</code>, denoted by <code>n!</code>, is the product of all
|
||
positive integers less than or equal to
|
||
<code>n</code>.<br><code>n! = n×(n-1)×(n-2)...3×2×1</code><br>Write a program to calculate
|
||
<code>n!</code> for a given <code>n</code> (assume <code>n</code> is greater than <code>0</code>).
|
||
</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">n = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter n: "</span>))
|
||
|
||
factorial = <span class="hljs-number">1</span>
|
||
<span class="hljs-keyword">while</span> n > <span class="hljs-number">0</span>:
|
||
factorial *= n
|
||
n = n - <span class="hljs-number">1</span>
|
||
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"n! :"</span>, factorial)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Enter n: 6
|
||
n! : 720
|
||
</code></pre>
|
||
<h2 id="jump-statements">Jump Statements<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#jump-statements">#</a></h2>
|
||
<p>Jump statements are used to (abruptly) alter the flow of execution.</p>
|
||
<p>Some of the jump statements available in Python are:</p>
|
||
<h3 id="pass">pass<a aria-hidden class="header-link" tabindex="-1" href="#pass">#</a></h3>
|
||
<p>A <code>pass</code> statement acts as a placeholder and performs null (no) operation.</p>
|
||
<p>Various reasons for using the keyword <code>pass</code> are provided below:</p>
|
||
<p><strong>1. Syntactical Requirement</strong></p>
|
||
<p>Using <code>pass</code> becomes a syntactical requirement for cases where the Python interpreter can
|
||
raise a <code>SyntaxError</code> due to missing statements.</p>
|
||
<p>The below code will execute successfully without any operation in the loop</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">6</span>):
|
||
<span class="hljs-keyword">pass</span>
|
||
</code></pre>
|
||
<p>whereas without <code>pass</code></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">6</span>):
|
||
</code></pre>
|
||
<p>will throw the following <code>SyntaxError</code></p>
|
||
<pre><code>File "<ipython-input-18-f2ba5099d499>", line 1
|
||
for i in range(6):
|
||
^
|
||
SyntaxError: unexpected EOF while parsing
|
||
</code></pre>
|
||
<p>Similarly, inside an <code>if</code></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">if</span> <span class="hljs-number">2</span> < <span class="hljs-number">3</span>:
|
||
<span class="hljs-keyword">pass</span>
|
||
</code></pre>
|
||
<p>whereas without <code>pass</code></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">if</span> <span class="hljs-number">2</span> < <span class="hljs-number">3</span>:
|
||
</code></pre>
|
||
<p>will throw the following <code>SyntaxError</code></p>
|
||
<pre><code>File "<ipython-input-20-068861cce0a8>", line 1
|
||
if 2 < 3:
|
||
^
|
||
SyntaxError: unexpected EOF while parsing
|
||
</code></pre>
|
||
<p><strong>2. Skipping Code Execution</strong></p>
|
||
<p><code>pass</code> can be used to skip code execution for certain cases.</p>
|
||
<p>For example,</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">l = [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>]
|
||
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> l:
|
||
<span class="hljs-keyword">if</span> i%<span class="hljs-number">3</span> == <span class="hljs-number">0</span>:
|
||
<span class="hljs-keyword">pass</span>
|
||
<span class="hljs-keyword">else</span>:
|
||
<span class="hljs-built_in">print</span>(i, <span class="hljs-string">"is not divisible by 3"</span>)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>2 is not divisible by 3
|
||
4 is not divisible by 3
|
||
5 is not divisible by 3
|
||
</code></pre>
|
||
<p><strong>3. Placeholders</strong></p>
|
||
<p><code>pass</code> can be used to create valid empty functions and classes as placeholders which can be
|
||
modified in the future versions of code.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">emptyFunction</span>():
|
||
<span class="hljs-keyword">pass</span>
|
||
|
||
<span class="hljs-keyword">class</span> <span class="hljs-title class_">EmptyClass</span>:
|
||
<span class="hljs-keyword">pass</span>
|
||
</code></pre>
|
||
<h3 id="break">break<a aria-hidden class="header-link" tabindex="-1" href="#break">#</a></h3>
|
||
<p>The <code>break</code> statement is used to terminate the execution of immediately enclosing
|
||
<code>for</code> or <code>while</code> statement.
|
||
</p>
|
||
<p>The below code will terminate the <code>for</code> loop when <code>i</code> is equal to <code>4</code>
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">10</span>):
|
||
<span class="hljs-built_in">print</span>(i)
|
||
<span class="hljs-keyword">if</span> i == <span class="hljs-number">4</span>:
|
||
<span class="hljs-keyword">break</span>
|
||
</code></pre>
|
||
<pre><code>0
|
||
1
|
||
2
|
||
3
|
||
4
|
||
</code></pre>
|
||
<p>In a while statement,</p>
|
||
<pre><code class="hljs language-python">i =<span class="hljs-number">0</span>
|
||
<span class="hljs-keyword">while</span> i <<span class="hljs-number">10</span>:
|
||
<span class="hljs-built_in">print</span>(i)
|
||
<span class="hljs-keyword">if</span> i == <span class="hljs-number">4</span>:
|
||
<span class="hljs-keyword">break</span>
|
||
i+=<span class="hljs-number">1</span>
|
||
</code></pre>
|
||
<p><code>break</code> will terminate the <code>while</code> loop when <code>i</code> is equal to
|
||
<code>4</code>
|
||
</p>
|
||
<pre><code>0
|
||
1
|
||
2
|
||
3
|
||
4
|
||
</code></pre>
|
||
<h3 id="continue">continue<a aria-hidden class="header-link" tabindex="-1" href="#continue">#</a></h3>
|
||
<p><code>continue</code> statement is used to skip the execution of successive statements and start the next
|
||
iteration.</p>
|
||
<p>The below code will skip all candidates for an interview who have less than 4 years of work experience.
|
||
</p>
|
||
<pre><code class="hljs language-python">people = [{<span class="hljs-string">"name"</span>: <span class="hljs-string">"ABC"</span>, <span class="hljs-string">"experience"</span>: <span class="hljs-number">6</span>},
|
||
{<span class="hljs-string">"name"</span>: <span class="hljs-string">"EFG"</span>, <span class="hljs-string">"experience"</span>: <span class="hljs-number">2</span>},
|
||
{<span class="hljs-string">"name"</span>: <span class="hljs-string">"JKL"</span>, <span class="hljs-string">"experience"</span>: <span class="hljs-number">5</span>},
|
||
{<span class="hljs-string">"name"</span>: <span class="hljs-string">"XYZ"</span>, <span class="hljs-string">"experience"</span>: <span class="hljs-number">3</span>},]
|
||
<span class="hljs-keyword">for</span> candidate <span class="hljs-keyword">in</span> people:
|
||
<span class="hljs-keyword">if</span> candidate[<span class="hljs-string">"experience"</span>]<<span class="hljs-number">4</span>:
|
||
<span class="hljs-keyword">continue</span>
|
||
<span class="hljs-built_in">print</span>(candidate[<span class="hljs-string">"name"</span>], <span class="hljs-string">"is selected for interview"</span>)
|
||
</code></pre>
|
||
<p>Output:</p>
|
||
<pre><code>ABC is selected for interview
|
||
JKL is selected for interview
|
||
</code></pre>
|
||
<h2 id="nested-loops">Nested Loops<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#nested-loops">#</a></h2>
|
||
<p>When a loop is present inside another loop, it is known as a nested loop.</p>
|
||
<p>For each iteration of the outer loop, the inner loop undergoes complete iteration. Thus, if the outer
|
||
loop has to undergo <code>n</code> iterations and the inner loop has to undergo <code>m</code>
|
||
iterations, the code block inside the inner loop executes <code>n x m</code> times.</p>
|
||
<p>Let us go through a nested loop example:</p>
|
||
<h3 id="factorial">Factorial<a aria-hidden class="header-link" tabindex="-1" href="#factorial">#</a></h3>
|
||
<p>Write a program to print the factorial of all numbers in the range <code>1</code> to <code>10</code>
|
||
(inclusive).</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">for</span> n <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">1</span>, <span class="hljs-number">11</span>):
|
||
factorial = <span class="hljs-number">1</span>
|
||
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">1</span>, n+<span class="hljs-number">1</span>):
|
||
factorial *= i
|
||
<span class="hljs-built_in">print</span>(n,<span class="hljs-string">"! ="</span>, factorial)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>1 ! = 1
|
||
2 ! = 2
|
||
3 ! = 6
|
||
4 ! = 24
|
||
5 ! = 120
|
||
6 ! = 720
|
||
7 ! = 5040
|
||
8 ! = 40320
|
||
9 ! = 362880
|
||
10 ! = 3628800
|
||
</code></pre>
|
||
<h3 id="nested-loop---break">Nested Loop - break<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#nested-loop---break">#</a></h3>
|
||
<p>A <code>break</code> statement inside the inner loop terminates only the inner loop whereas the outer
|
||
loop is not affected.</p>
|
||
<p>To develop a better understanding, let us write a program to find all prime numbers between 2 and 40.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">for</span> n <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-number">2</span>, <span class="hljs-number">40</span>):
|
||
i = <span class="hljs-number">2</span>
|
||
<span class="hljs-keyword">while</span> i < n/<span class="hljs-number">2</span>:
|
||
<span class="hljs-keyword">if</span> n%i == <span class="hljs-number">0</span>:
|
||
<span class="hljs-keyword">break</span>
|
||
i+=<span class="hljs-number">1</span>
|
||
<span class="hljs-keyword">if</span> i>n/<span class="hljs-number">2</span>:
|
||
<span class="hljs-built_in">print</span>(n,<span class="hljs-string">"is prime"</span>)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>2 is prime
|
||
3 is prime
|
||
5 is prime
|
||
7 is prime
|
||
11 is prime
|
||
13 is prime
|
||
17 is prime
|
||
19 is prime
|
||
23 is prime
|
||
29 is prime
|
||
31 is prime
|
||
37 is prime
|
||
</code></pre>
|
||
<h1 id="strings">Strings<a aria-hidden class="header-link" tabindex="-1" href="#strings">#</a></h1>
|
||
<h2 id="strings-introduction--creation">Strings: Introduction & Creation<a aria-hidden
|
||
class="header-link" tabindex="-1" href="#strings-introduction--creation">#</a></h2>
|
||
<p>A String (<code>str</code>) is an <strong>immutable</strong> sequence of Unicode characters which is used
|
||
to handle textual data in Python.</p>
|
||
<p>They can be specified by enclosing within:</p>
|
||
<ul>
|
||
<li>Single quotes: <code>'embedded "double" quotes are allowed'</code></li>
|
||
<li>Double quotes: <code>"embedded 'single' quotes are allowed"</code></li>
|
||
<li>Triple quotes: <code>'''Three single quotes'''</code>, <code>"""Three double quotes"""</code>.</li>
|
||
</ul>
|
||
<p>Triple quoted strings can also span multiple lines.</p>
|
||
<p>Some examples are provided below:</p>
|
||
<pre><code class="hljs language-python">s = <span class="hljs-string">"I am a String"</span>
|
||
|
||
s1 = <span class="hljs-string">"""A
|
||
multiline
|
||
String"""</span>
|
||
|
||
s2 = <span class="hljs-string">'''Also a
|
||
multiline
|
||
String'''</span>
|
||
</code></pre>
|
||
<h3 id="escape-characters">Escape Characters<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#escape-characters">#</a></h3>
|
||
<p>The backslash (<code>\</code>) character can be used in a string to escape characters that otherwise have
|
||
a special meaning, such as newline, linefeed, or the quote character.</p>
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th>Escape Sequence</th>
|
||
<th>Meaning</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr>
|
||
<td><code>\\</code></td>
|
||
<td>Backslash (<code>\</code>)</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>\'</code></td>
|
||
<td>Single quote (<code>'</code>)</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>\"</code></td>
|
||
<td>Double quote (<code>"</code>)</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>\a</code></td>
|
||
<td>ASCII Bell (BEL)</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>\b</code></td>
|
||
<td>ASCII Backspace (BS)</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>\f</code></td>
|
||
<td>ASCII Formfeed (FF)</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>\n</code></td>
|
||
<td>ASCII Linefeed (LF)</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>\r</code></td>
|
||
<td>ASCII Carriage Return (CR)</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>\t</code></td>
|
||
<td>ASCII Horizontal Tab (TAB)</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>\v</code></td>
|
||
<td>ASCII Vertical Tab (VT)</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
<p>Although <code>\'</code> and <code>\"</code> can be used to specify quote characters, Python allows
|
||
embedding double quotes inside a single-quoted string (<code>'My name is "Python".'</code>) and single
|
||
quotes inside a double-quoted string (<code>"Python's World"</code>).</p>
|
||
<h3 id="unicode-support">Unicode Support<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#unicode-support">#</a></h3>
|
||
<p>Python string objects support Unicode characters.</p>
|
||
<p>A unicode character can be specified as <code>\u</code> followed by the 4 letter unicode
|
||
(<code>\uXXXX</code>).</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span>(<span class="hljs-string">"E = mc\u00B2"</span>)
|
||
E = mc²
|
||
</code></pre>
|
||
<p>In the above example, <code>\u00B2</code> is the unicode character which represents the 'SUPERSCRIPT
|
||
TWO'.</p>
|
||
<h3 id="other-types-to-string">Other Types to String<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#other-types-to-string">#</a></h3>
|
||
<p>In case you want to create a string object from other data types, just use the built-in
|
||
<code>str()</code> function as follows:
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">str</span>(<span class="hljs-number">9</span>)
|
||
<span class="hljs-string">'9'</span>
|
||
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">str</span>(<span class="hljs-number">10.0</span>)
|
||
<span class="hljs-string">'10.0'</span>
|
||
</code></pre>
|
||
<h2 id="accessing-characters-of-a-string">Accessing Characters of a String<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#accessing-characters-of-a-string">#</a></h2>
|
||
<p>Python strings are "immutable", i.e., the state (value) of the objects cannot be modified after they are
|
||
created.</p>
|
||
<p>Using the standard <code>[ ]</code> syntax and zero-based indexing, characters can be accessed in a
|
||
string.</p>
|
||
<p>If <code>s = "hello"</code>,</p>
|
||
<ul>
|
||
<li><code>s[0]</code> will result in <code>h</code></li>
|
||
<li><code>s[2]</code> will result in <code>l</code></li>
|
||
<li><code>s[5]</code> will result in <code>IndexError: string index out of range</code> as the length of
|
||
string is <code>5</code> (index <code>0</code> to <code>4</code>)</li>
|
||
<li><code>s[2] = 'p'</code> will result in
|
||
<code>TypeError: 'str' object does not support item assignment</code> as <code>s</code> is immutable
|
||
</li>
|
||
</ul>
|
||
<p>Python also supports negative indexing, i.e., you can access the values of a string from right to left.
|
||
</p>
|
||
<p>Index of <code>-1</code> denotes the last character of the string, <code>-2</code> is the second last
|
||
character and so forth.</p>
|
||
<p>If <code>s = "hello"</code>,</p>
|
||
<ul>
|
||
<li><code>s[-1]</code> will result in <code>o</code></li>
|
||
<li><code>s[-4]</code> will result in <code>e</code></li>
|
||
<li><code>s[-6]</code> will result in <code>IndexError: string index out of range</code> as the length
|
||
of string is <code>5</code> (negative index <code>-1</code> to <code>-5</code>)</li>
|
||
</ul>
|
||
<h3 id="length-of-string">Length of String<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#length-of-string">#</a></h3>
|
||
<p>The built-in function <code>len()</code> returns the length of a string which is useful during string
|
||
traversal or other string operations.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">len</span>(<span class="hljs-string">"hello"</span>)
|
||
<span class="hljs-number">5</span>
|
||
|
||
<span class="hljs-meta">>>> </span>s = <span class="hljs-string">"sample text"</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">len</span>(s)
|
||
<span class="hljs-number">11</span>
|
||
|
||
<span class="hljs-meta">>>> </span>p = <span class="hljs-string">"python"</span>
|
||
<span class="hljs-meta">>>> </span>l = <span class="hljs-built_in">len</span>(p)
|
||
<span class="hljs-meta">>>> </span>p[l-<span class="hljs-number">1</span>]
|
||
<span class="hljs-string">'n'</span>
|
||
</code></pre>
|
||
<h2 id="string-operations">String Operations<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#string-operations">#</a></h2>
|
||
<p>We can perform various operations on a string (sequence of characters) such as slicing, membership,
|
||
concatenation and repetition.</p>
|
||
<h3 id="slicing">Slicing<a aria-hidden class="header-link" tabindex="-1" href="#slicing">#</a></h3>
|
||
<p>In Python, a character in a string can be easily accessed using its index.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>s = <span class="hljs-string">"Hello"</span>
|
||
<span class="hljs-meta">>>> </span>s[<span class="hljs-number">1</span>]
|
||
<span class="hljs-string">'e'</span>
|
||
</code></pre>
|
||
<p>Python also provides a way to access a substring from a string. This substring is known as a
|
||
<strong>slice</strong> and it can be obtained using the slice operator <code>[n:m]</code> which returns
|
||
the part of the string from the start index (<code>n</code>) to the end index (<code>m</code>),
|
||
including the first but excluding the last.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>s = <span class="hljs-string">"Hello"</span>
|
||
<span class="hljs-meta">>>> </span>s[<span class="hljs-number">1</span>:<span class="hljs-number">3</span>]
|
||
<span class="hljs-string">'el'</span>
|
||
</code></pre>
|
||
<p>If the start index (<code>n</code>) is omitted, the default value of <code>n</code> is set as
|
||
<code>0</code> which denotes the beginning of the string. If the end index (<code>m</code>) is omitted,
|
||
the substring ends at the last character of the string.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>s = <span class="hljs-string">"Hello"</span>
|
||
<span class="hljs-meta">>>> </span>s[:<span class="hljs-number">3</span>]
|
||
<span class="hljs-string">'Hel'</span>
|
||
<span class="hljs-meta">>>> </span>s[<span class="hljs-number">3</span>:]
|
||
<span class="hljs-string">'lo'</span>
|
||
<span class="hljs-meta">>>> </span>s[:]
|
||
<span class="hljs-string">'Hello'</span>
|
||
</code></pre>
|
||
<p>Negative indexing is also supported in the slice operator.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>s = <span class="hljs-string">"Hello"</span>
|
||
<span class="hljs-meta">>>> </span>s[-<span class="hljs-number">4</span>:-<span class="hljs-number">2</span>]
|
||
<span class="hljs-string">'el'</span>
|
||
</code></pre>
|
||
<p>In the above example, <code>-4</code> is equivalent to <code>len(s) - 4 = 5 - 4 = 1</code> and
|
||
<code>-2</code> is equivalent to <code>5 - 2 = 3</code>. Thus, <code>s[-4:-2]</code> is same as
|
||
<code>s[1:3]</code>.
|
||
</p>
|
||
<p>The slice operator also allows the usage of a third index which is known as step as it allows a user to
|
||
step over (skip) characters.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>s = <span class="hljs-string">"Hello"</span>
|
||
<span class="hljs-meta">>>> </span>s[<span class="hljs-number">0</span>:<span class="hljs-number">5</span>:<span class="hljs-number">2</span>]
|
||
<span class="hljs-string">'Hlo'</span>
|
||
</code></pre>
|
||
<p>In the above example, the substring begins at the start of the string, takes a step size of
|
||
<code>2</code> skipping <code>e</code> and ends at the last character again skipping the 4th character
|
||
<code>l</code>.
|
||
</p>
|
||
<h3 id="membership">Membership<a aria-hidden class="header-link" tabindex="-1" href="#membership">#</a></h3>
|
||
<p><code>in</code> and <code>not in</code> operators can be used to determine whether a substring is
|
||
present/not present in a string.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>s = <span class="hljs-string">"Hello"</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"lo"</span> <span class="hljs-keyword">in</span> s
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"lp"</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> s
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<h3 id="concatenation">Concatenation<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#concatenation">#</a></h3>
|
||
<p>The <code>+</code> operator can be used to join two strings.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>s1 = <span class="hljs-string">"Hello"</span>
|
||
<span class="hljs-meta">>>> </span>s2 = <span class="hljs-string">"Python"</span>
|
||
<span class="hljs-meta">>>> </span>s1 + s2
|
||
<span class="hljs-string">'HelloPython'</span>
|
||
<span class="hljs-meta">>>> </span>s1 + <span class="hljs-string">"World"</span>
|
||
<span class="hljs-string">'HelloWorld'</span>
|
||
</code></pre>
|
||
<h3 id="repetition">Repetition<a aria-hidden class="header-link" tabindex="-1" href="#repetition">#</a></h3>
|
||
<p>The <code>*</code> operator repeats a string the number of times as specified by the integer operand.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>s = <span class="hljs-string">"Hello"</span>
|
||
<span class="hljs-meta">>>> </span>s*<span class="hljs-number">3</span>
|
||
<span class="hljs-string">'HelloHelloHello'</span>
|
||
</code></pre>
|
||
<h2 id="introduction-to-string-methods">Introduction to String Methods<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#introduction-to-string-methods">#</a></h2>
|
||
<p>Apart from the built-in function <code>len()</code> which returns the length of the string, String
|
||
objects have access to several specialized functions (methods) that can:</p>
|
||
<ol>
|
||
<li>Convert Case of Strings</li>
|
||
<li>Check Characters of a String</li>
|
||
<li>Split a String</li>
|
||
<li>Strip Characters from a String</li>
|
||
<li>Checking for Prefix or Suffix in a String</li>
|
||
<li>Find & Replace Characters in a String</li>
|
||
</ol>
|
||
<p>Let us discuss these methods in detail in the coming sections.</p>
|
||
<h2 id="convert-case-of-strings">Convert Case of Strings<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#convert-case-of-strings">#</a></h2>
|
||
<p>The following methods are useful in converting the case of the characters in a string:</p>
|
||
<h3 id="lower">lower()<a aria-hidden class="header-link" tabindex="-1" href="#lower">#</a></h3>
|
||
<p>All cased characters are converted into lowercase.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"PYthon"</span>.lower()
|
||
<span class="hljs-string">'python'</span>
|
||
</code></pre>
|
||
<h3 id="upper">upper()<a aria-hidden class="header-link" tabindex="-1" href="#upper">#</a></h3>
|
||
<p>All cased characters are converted into uppercase.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"PYthon"</span>.upper()
|
||
<span class="hljs-string">'PYTHON'</span>
|
||
</code></pre>
|
||
<h3 id="swapcase">swapcase()<a aria-hidden class="header-link" tabindex="-1" href="#swapcase">#</a></h3>
|
||
<p>Uppercase characters are converted into lowercase and lowercase characters are converted into uppercase.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"PYthon"</span>.swapcase()
|
||
<span class="hljs-string">'pyTHON'</span>
|
||
</code></pre>
|
||
<h3 id="capitalize">capitalize()<a aria-hidden class="header-link" tabindex="-1" href="#capitalize">#</a>
|
||
</h3>
|
||
<p>First character is capitalized and rest all characters are lowercased.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"hello py"</span>.capitalize()
|
||
<span class="hljs-string">'Hello py'</span>
|
||
</code></pre>
|
||
<h3 id="title">title()<a aria-hidden class="header-link" tabindex="-1" href="#title">#</a></h3>
|
||
<p>For each word present in the string, the first character is uppercased and the remaining characters are
|
||
lowercased.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"hello python"</span>.title()
|
||
<span class="hljs-string">'Hello Python'</span>
|
||
</code></pre>
|
||
<h2 id="check-characters-of-a-string">Check Characters of a String<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#check-characters-of-a-string">#</a></h2>
|
||
<p>The following methods are used to check the type of characters in a string.</p>
|
||
<h3 id="isalpha">isalpha()<a aria-hidden class="header-link" tabindex="-1" href="#isalpha">#</a></h3>
|
||
<p>Returns <code>True</code> if all characters in the string are letters (<code>A-Z a-z</code>).</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"HelloPython"</span>.isalpha()
|
||
<span class="hljs-literal">True</span>
|
||
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"Hello Python"</span>.isalpha()
|
||
<span class="hljs-literal">False</span> <span class="hljs-comment"># contains whitespace</span>
|
||
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"HelloPython2"</span>.isalpha()
|
||
<span class="hljs-literal">False</span> <span class="hljs-comment"># contains digit</span>
|
||
</code></pre>
|
||
<h3 id="isdigit">isdigit()<a aria-hidden class="header-link" tabindex="-1" href="#isdigit">#</a></h3>
|
||
<p>Returns <code>True</code> if all characters in the string are digits.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"Hello24"</span>.isdigit()
|
||
<span class="hljs-literal">False</span> <span class="hljs-comment"># contains alphabets</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"24"</span>.isdigit()
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<h3 id="isalnum">isalnum()<a aria-hidden class="header-link" tabindex="-1" href="#isalnum">#</a></h3>
|
||
<p>Returns <code>True</code> if all characters in the string are alphanumeric (Alphabets or Numeric).</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"02"</span>.isalnum()
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"HelloPython"</span>.isalnum()
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"Hello Python v2"</span>.isalnum()
|
||
<span class="hljs-literal">False</span> <span class="hljs-comment"># contains whitespace</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"HelloPythonv2"</span>.isalnum()
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<h3 id="isascii">isascii()<a aria-hidden class="header-link" tabindex="-1" href="#isascii">#</a></h3>
|
||
<p>Returns <code>True</code> if the string is empty or all characters in the string are ASCII.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">""</span>.isascii()
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"HelloPython"</span>.isascii()
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"Hello Py \u00B2"</span>.isascii()
|
||
<span class="hljs-literal">False</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"पा से python"</span>.isascii()
|
||
<span class="hljs-literal">False</span>
|
||
</code></pre>
|
||
<h3 id="islower">islower()<a aria-hidden class="header-link" tabindex="-1" href="#islower">#</a></h3>
|
||
<p>Returns <code>True</code> if all characters are lowercase.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"hello"</span>.islower()
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"Hello"</span>.islower()
|
||
<span class="hljs-literal">False</span>
|
||
</code></pre>
|
||
<h3 id="isupper">isupper()<a aria-hidden class="header-link" tabindex="-1" href="#isupper">#</a></h3>
|
||
<p>Returns <code>True</code> if all characters are uppercase.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"HELLO"</span>.isupper()
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"Hello"</span>.isupper()
|
||
<span class="hljs-literal">False</span>
|
||
</code></pre>
|
||
<h3 id="isspace">isspace()<a aria-hidden class="header-link" tabindex="-1" href="#isspace">#</a></h3>
|
||
<p>Returns <code>True</code> if there are only whitespace characters in the string. Some popular whitespace
|
||
characters are <code></code> (space), <code>\t</code> (tab), <code>\n</code> (newline), <code>\r</code>
|
||
(carriage return), <code>\f</code> (form feed) and <code>\v</code> (vertical tab).</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">" "</span>.isspace()
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<h3 id="istitle">istitle()<a aria-hidden class="header-link" tabindex="-1" href="#istitle">#</a></h3>
|
||
<p>Returns <code>True</code> if the string is title-cased, i.e., the first character of every word in the
|
||
string is uppercased and the remaining characters are lowercased.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"Hello World"</span>.istitle()
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"Hello world"</span>.istitle()
|
||
<span class="hljs-literal">False</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"hello world"</span>.istitle()
|
||
<span class="hljs-literal">False</span>
|
||
</code></pre>
|
||
<h2 id="split-a-string">Split a String<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#split-a-string">#</a></h2>
|
||
<p>Split methods help in splitting/partitioning a string.</p>
|
||
<h3 id="partition">partition()<a aria-hidden class="header-link" tabindex="-1" href="#partition">#</a></h3>
|
||
<p><code>partition(sep)</code> method splits the string when the separator (<code>sep</code>) is encountered
|
||
for the first time, and returns a tuple with three items
|
||
<code>(string before separator, separator, string after separator)</code>.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"Hi|Ed|Punk"</span>.partition(<span class="hljs-string">'|'</span>)
|
||
(<span class="hljs-string">'Hi'</span>, <span class="hljs-string">'|'</span>, <span class="hljs-string">'Ed|Punk'</span>)
|
||
</code></pre>
|
||
<h3 id="split">split()<a aria-hidden class="header-link" tabindex="-1" href="#split">#</a></h3>
|
||
<p><code>split(sep=None, maxsplit=-1)</code> method splits a string into a list based on a string separator
|
||
(<code>sep</code>).</p>
|
||
<p>If <code>sep</code> is not specified, it defaults to <code>None</code>, where whitespace is regarded as
|
||
separator, and the string is stripped of all leading and trailing whitespaces after which it is split
|
||
into words contained in the string.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"Hi|Ed|Punk"</span>.split(<span class="hljs-string">'|'</span>)
|
||
[<span class="hljs-string">'Hi'</span>, <span class="hljs-string">'Ed'</span>, <span class="hljs-string">'Punk'</span>]
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"Hi Ed Punk"</span>.split()
|
||
[<span class="hljs-string">'Hi'</span>, <span class="hljs-string">'Ed'</span>, <span class="hljs-string">'Punk'</span>]
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">" Hi Ed Punk "</span>.split()
|
||
[<span class="hljs-string">'Hi'</span>, <span class="hljs-string">'Ed'</span>, <span class="hljs-string">'Punk'</span>]
|
||
</code></pre>
|
||
<p>If <code>maxsplit</code> is provided, at most <code>maxsplit</code> number of splits are performed and
|
||
the list will contain a maximum of <code>maxsplit+1</code> elements.</p>
|
||
<p><code>maxsplit</code> when not specified defaults to <code>-1</code>, which implies that there is no
|
||
limit on the number of splits.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"Hi|Ed|Punk|v2"</span>.split(<span class="hljs-string">'|'</span>, <span class="hljs-number">2</span>)
|
||
[<span class="hljs-string">'Hi'</span>, <span class="hljs-string">'Ed'</span>, <span class="hljs-string">'Punk|v2'</span>]
|
||
</code></pre>
|
||
<h2 id="strip-characters-from-a-string">Strip Characters from a String<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#strip-characters-from-a-string">#</a></h2>
|
||
<p>Strip methods are useful in removing leading and/or trailing characters in a string.</p>
|
||
<p>They accept an optional argument <code>chars</code> which specifies the set of characters which have to
|
||
be removed.</p>
|
||
<p>If no arguments are provided then <code>chars</code> defaults to ASCII whitespace and the method removes
|
||
all leading and/or trailing spaces from the string.</p>
|
||
<h3 id="lstrip">lstrip()<a aria-hidden class="header-link" tabindex="-1" href="#lstrip">#</a></h3>
|
||
<p>All leading (on the left) characters are removed from the string.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">" Hello|World "</span>.lstrip()
|
||
<span class="hljs-string">'Hello|World '</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"www.edpunk.cc"</span>.lstrip(<span class="hljs-string">'w.'</span>)
|
||
<span class="hljs-string">'edpunk.cc'</span>
|
||
</code></pre>
|
||
<h3 id="rstrip">rstrip()<a aria-hidden class="header-link" tabindex="-1" href="#rstrip">#</a></h3>
|
||
<p>All trailing (on the right) characters are removed from the string.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">" Hello|World "</span>.rstrip()
|
||
<span class="hljs-string">' Hello|World'</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"www.edpunk.cc"</span>.rstrip(<span class="hljs-string">'.c'</span>)
|
||
<span class="hljs-string">'www.edpunk'</span>
|
||
</code></pre>
|
||
<h3 id="strip">strip()<a aria-hidden class="header-link" tabindex="-1" href="#strip">#</a></h3>
|
||
<p>All leading and trailing characters are removed from the string.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">" Hello|World "</span>.strip()
|
||
<span class="hljs-string">'Hello|World'</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"www.edpunk.cc"</span>.strip(<span class="hljs-string">'cw.'</span>)
|
||
<span class="hljs-string">'edpunk'</span>
|
||
</code></pre>
|
||
<h2 id="check-prefix-or-suffix-in-a-string">Check Prefix or Suffix in a String<a aria-hidden
|
||
class="header-link" tabindex="-1" href="#check-prefix-or-suffix-in-a-string">#</a></h2>
|
||
<p><code>startswith()</code> and <code>endswith()</code> methods are used check whether a string starts or
|
||
ends with the provided substring (or a tuple of substrings).</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"Hello Py"</span>.startswith(<span class="hljs-string">"He"</span>)
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"Hello Py"</span>.startswith((<span class="hljs-string">"He"</span>,<span class="hljs-string">"P"</span>))
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"Py Hello"</span>.startswith((<span class="hljs-string">"He"</span>,<span class="hljs-string">"P"</span>))
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"Hello Py"</span>.endswith(<span class="hljs-string">"y"</span>)
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"Hello Py"</span>.endswith((<span class="hljs-string">"p"</span>,<span class="hljs-string">"y"</span>))
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"Py Hello"</span>.endswith((<span class="hljs-string">"o"</span>,<span class="hljs-string">"n"</span>))
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<h2 id="find--replace-characters-in-a-string">Find & Replace Characters in a String<a aria-hidden
|
||
class="header-link" tabindex="-1" href="#find--replace-characters-in-a-string">#</a></h2>
|
||
<p>The following string methods are useful for locating substring in a string.</p>
|
||
<h3 id="count">count()<a aria-hidden class="header-link" tabindex="-1" href="#count">#</a></h3>
|
||
<p><code>count(sub[, start[, end]])</code> returns the number of non-overlapping occurrences of a substring
|
||
<code>sub</code> in the range <code>[start, end]</code>.
|
||
</p>
|
||
<p><code>start</code> and <code>end</code> are optional parameters and they default to <code>0</code> and
|
||
<code>len(string)</code> respectively.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>s = <span class="hljs-string">"she sells sea shells"</span>
|
||
<span class="hljs-meta">>>> </span>s.count(<span class="hljs-string">"she"</span>)
|
||
<span class="hljs-number">2</span>
|
||
<span class="hljs-meta">>>> </span>s.count(<span class="hljs-string">"she"</span>, <span class="hljs-number">5</span>)
|
||
<span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span>s.count(<span class="hljs-string">"she"</span>, <span class="hljs-number">5</span>, <span class="hljs-number">10</span>)
|
||
<span class="hljs-number">0</span>
|
||
<span class="hljs-meta">>>> </span>s.count(<span class="hljs-string">"she"</span>, <span class="hljs-number">5</span>, <span class="hljs-number">17</span>)
|
||
<span class="hljs-number">1</span>
|
||
</code></pre>
|
||
<p>It has to be noted that the method counts non-overlapping occurrences, so it does not start a new
|
||
matching process until the current substring matching is complete.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>s = <span class="hljs-string">"valhala alala"</span>
|
||
<span class="hljs-meta">>>> </span>s.count(<span class="hljs-string">"al"</span>)
|
||
<span class="hljs-number">4</span>
|
||
<span class="hljs-meta">>>> </span>s.count(<span class="hljs-string">"ala"</span>)
|
||
<span class="hljs-number">2</span>
|
||
</code></pre>
|
||
<p>In the above example, <code>ala</code> is counted twice as the first occurence is in
|
||
<code>valh"ala"</code> and the next occurance is in <code>"ala"la</code>. Although <code>ala</code> can
|
||
be located again in <code>al"ala"</code>, it overlaps with the occurance <code>"ala"la</code>, hence it
|
||
is not counted.
|
||
</p>
|
||
<h3 id="find">find()<a aria-hidden class="header-link" tabindex="-1" href="#find">#</a></h3>
|
||
<p><code>find(sub[, start[, end]])</code> returns the lowest index in the string where substring
|
||
<code>sub</code> is located in the range <code>[start, end]</code>.
|
||
</p>
|
||
<p><code>start</code> and <code>end</code> are optional parameters and they default to <code>0</code> and
|
||
<code>len(string)</code> respectively.
|
||
</p>
|
||
<p>The method returns <code>-1</code> in case the substring is not present.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>s = <span class="hljs-string">"she sells sea shells"</span>
|
||
<span class="hljs-meta">>>> </span>s.find(<span class="hljs-string">"she"</span>)
|
||
<span class="hljs-number">0</span>
|
||
<span class="hljs-meta">>>> </span>s.find(<span class="hljs-string">"she"</span>, <span class="hljs-number">5</span>)
|
||
<span class="hljs-number">14</span>
|
||
<span class="hljs-meta">>>> </span>s.find(<span class="hljs-string">"see"</span>)
|
||
-<span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span>s.find(<span class="hljs-string">"she"</span>, <span class="hljs-number">5</span>, <span class="hljs-number">10</span>)
|
||
-<span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span>s.find(<span class="hljs-string">"she"</span>, <span class="hljs-number">5</span>, <span class="hljs-number">17</span>)
|
||
<span class="hljs-number">14</span>
|
||
</code></pre>
|
||
<h3 id="rfind">rfind()<a aria-hidden class="header-link" tabindex="-1" href="#rfind">#</a></h3>
|
||
<p><code>rfind(sub[, start[, end]])</code> returns the highest index in the string where substring
|
||
<code>sub</code> is located in the range <code>[start, end]</code>.
|
||
</p>
|
||
<p><code>start</code> and <code>end</code> are optional parameters and they default to <code>0</code> and
|
||
<code>len(string)</code> respectively.
|
||
</p>
|
||
<p>The method returns <code>-1</code> in case the substring is not present.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>s = <span class="hljs-string">"she sells sea shells"</span>
|
||
<span class="hljs-meta">>>> </span>s.rfind(<span class="hljs-string">"she"</span>)
|
||
<span class="hljs-number">14</span>
|
||
<span class="hljs-meta">>>> </span>s.rfind(<span class="hljs-string">"she"</span>, <span class="hljs-number">0</span>, <span class="hljs-number">12</span>)
|
||
<span class="hljs-number">0</span>
|
||
<span class="hljs-meta">>>> </span>s.rfind(<span class="hljs-string">"see"</span>)
|
||
-<span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span>s.rfind(<span class="hljs-string">"she"</span>, <span class="hljs-number">5</span>)
|
||
<span class="hljs-number">14</span>
|
||
</code></pre>
|
||
<h3 id="index">index()<a aria-hidden class="header-link" tabindex="-1" href="#index">#</a></h3>
|
||
<p><code>index(sub[, start[, end]])</code> is similar to <code>find(sub[, start[, end]])</code>, but instead
|
||
of returning <code>-1</code> it raises <code>ValueError</code> when the substring is not found.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>s = <span class="hljs-string">"she sells sea shells"</span>
|
||
<span class="hljs-meta">>>> </span>s.index(<span class="hljs-string">"she"</span>)
|
||
<span class="hljs-number">0</span>
|
||
<span class="hljs-meta">>>> </span>s.index(<span class="hljs-string">"she"</span>, <span class="hljs-number">5</span>)
|
||
<span class="hljs-number">14</span>
|
||
<span class="hljs-meta">>>> </span>s.index(<span class="hljs-string">"see"</span>)
|
||
Traceback (most recent call last):
|
||
File <span class="hljs-string">"<stdin>"</span>, line <span class="hljs-number">1</span>,
|
||
<span class="hljs-keyword">in</span> <module>
|
||
ValueError: substring <span class="hljs-keyword">not</span> found
|
||
<span class="hljs-meta">>>> </span>s.index(<span class="hljs-string">"she"</span>, <span class="hljs-number">5</span>, <span class="hljs-number">10</span>)
|
||
Traceback (most recent call last):
|
||
File <span class="hljs-string">"<stdin>"</span>, line <span class="hljs-number">1</span>,
|
||
<span class="hljs-keyword">in</span> <module>
|
||
ValueError: substring <span class="hljs-keyword">not</span> found
|
||
<span class="hljs-meta">>>> </span>s.index(<span class="hljs-string">"she"</span>, <span class="hljs-number">5</span>, <span class="hljs-number">17</span>)
|
||
<span class="hljs-number">14</span>
|
||
</code></pre>
|
||
<h3 id="rindex">rindex()<a aria-hidden class="header-link" tabindex="-1" href="#rindex">#</a></h3>
|
||
<p><code>s.rindex(sub[, start[, end]])</code> is similar to <code>rfind(sub[, start[, end]])</code>, but
|
||
instead of returning <code>-1</code> it raises <code>ValueError</code> when the substring is not found.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>s = <span class="hljs-string">"she sells sea shells"</span>
|
||
<span class="hljs-meta">>>> </span>s.rindex(<span class="hljs-string">"she"</span>)
|
||
<span class="hljs-number">14</span>
|
||
<span class="hljs-meta">>>> </span>s.rindex(<span class="hljs-string">"she"</span>, <span class="hljs-number">0</span>, <span class="hljs-number">12</span>)
|
||
<span class="hljs-number">0</span>
|
||
<span class="hljs-meta">>>> </span>s.rindex(<span class="hljs-string">"see"</span>)
|
||
Traceback (most recent call last):
|
||
File <span class="hljs-string">"<stdin>"</span>, line <span class="hljs-number">1</span>,
|
||
<span class="hljs-keyword">in</span> <module>
|
||
ValueError: substring <span class="hljs-keyword">not</span> found
|
||
<span class="hljs-meta">>>> </span>s.rindex(<span class="hljs-string">"she"</span>, <span class="hljs-number">5</span>)
|
||
<span class="hljs-number">14</span>
|
||
</code></pre>
|
||
<h3 id="replace">replace()<a aria-hidden class="header-link" tabindex="-1" href="#replace">#</a></h3>
|
||
<p><code>replace(oldsub, newsub[, count])</code> returns a copy of the string with all occurrences of
|
||
<code>oldsub</code> substring replaced by <code>newsub</code>.
|
||
</p>
|
||
<p><code>count</code> is an optional parameter which when provided, only replaces the first
|
||
<code>count</code> occurrences from the string.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>s = <span class="hljs-string">"Oh Python! Oh"</span>
|
||
<span class="hljs-meta">>>> </span>s.replace(<span class="hljs-string">"Oh"</span>, <span class="hljs-string">"Hi"</span>)
|
||
<span class="hljs-string">'Hi Python! Hi'</span>
|
||
<span class="hljs-meta">>>> </span>s.replace(<span class="hljs-string">"Oh"</span>, <span class="hljs-string">"Hi"</span>, <span class="hljs-number">1</span>)
|
||
<span class="hljs-string">'Hi Python! Oh'</span>
|
||
</code></pre>
|
||
<h2 id="traversing-a-string">Traversing a String<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#traversing-a-string">#</a></h2>
|
||
<p><code>for</code> and <code>while</code> statements are useful for traversing a string.</p>
|
||
<h3 id="using-for">Using <code>for</code><a aria-hidden class="header-link" tabindex="-1"
|
||
href="#using-for">#</a></h3>
|
||
<p>As a string is a sequence of characters, the <code>for</code> statement can be used to iterate over a
|
||
string as shown below.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">name = <span class="hljs-string">"python"</span>
|
||
<span class="hljs-keyword">for</span> char <span class="hljs-keyword">in</span> name:
|
||
<span class="hljs-built_in">print</span>(char)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>p
|
||
y
|
||
t
|
||
h
|
||
o
|
||
n
|
||
</code></pre>
|
||
<h3 id="using-while">Using <code>while</code><a aria-hidden class="header-link" tabindex="-1"
|
||
href="#using-while">#</a></h3>
|
||
<p>A <code>while</code> statement can be used to traverse a string by iterating on the value of index till
|
||
the last character index.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">name = <span class="hljs-string">"python"</span>
|
||
i = <span class="hljs-number">0</span>
|
||
<span class="hljs-keyword">while</span> i < <span class="hljs-built_in">len</span>(name):
|
||
<span class="hljs-built_in">print</span>(name[i])
|
||
i += <span class="hljs-number">1</span>
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>p
|
||
y
|
||
t
|
||
h
|
||
o
|
||
n
|
||
</code></pre>
|
||
<h1 id="list">List<a aria-hidden class="header-link" tabindex="-1" href="#list">#</a></h1>
|
||
<h2 id="what-is-a-python-list-how-to-create-a-list">What is a Python List? How to Create a List?<a
|
||
aria-hidden class="header-link" tabindex="-1"
|
||
href="#what-is-a-python-list-how-to-create-a-list">#</a></h2>
|
||
<p>The most common and widely used collections in Python are <strong>lists</strong> which store an ordered
|
||
group of objects (of any datatype) which might have some logical relation. This marks a considerable
|
||
difference from arrays (in traditional languages) and makes Python an ideal language for handling
|
||
real-life data which is not type-bound.</p>
|
||
<p>Let us create a list of attributes of a particular vehicle available for sale in a car dealership:</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>]
|
||
</code></pre>
|
||
<p>In this list:</p>
|
||
<ul>
|
||
<li><code>"BMW"</code> is the make of the vehicle,</li>
|
||
<li><code>"Z4"</code> is the model of the vehicle,</li>
|
||
<li><code>2019</code> is the year when the vehicle was manufactured,</li>
|
||
<li><code>4</code> represents the number of wheels,</li>
|
||
<li><code>"Red"</code> is the color of the vehicle, and</li>
|
||
<li><code>True</code> tells us that the vehicle up for sale is brand new.</li>
|
||
</ul>
|
||
<p>This method of creating a list from a collection of literals is known as <strong>list display</strong>.
|
||
</p>
|
||
<p>Notice, how this list contains items of multiple data types - <code>str</code>, <code>int</code> and
|
||
<code>bool</code>.
|
||
</p>
|
||
<p>Apart from the list display shown above, the built-in <code>list()</code> function can also be used to
|
||
create new lists.</p>
|
||
<p>If no arguments are provided to the <code>list()</code> function, an empty list is created.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = <span class="hljs-built_in">list</span>()
|
||
<span class="hljs-meta">>>> </span>l
|
||
[]
|
||
</code></pre>
|
||
<p>If a string, tuple or set is passed as an argument, <code>list()</code> functions converts them into a
|
||
list.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = <span class="hljs-built_in">list</span>(<span class="hljs-string">"abcd"</span>)
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>, <span class="hljs-string">'d'</span>]
|
||
<span class="hljs-meta">>>> </span>l = <span class="hljs-built_in">list</span>({<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>})
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
|
||
<span class="hljs-meta">>>> </span>l = <span class="hljs-built_in">list</span>((<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>))
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
|
||
</code></pre>
|
||
<h2 id="accessing-items-of-a-list">Accessing Items of a List<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#accessing-items-of-a-list">#</a></h2>
|
||
<p>Lists use zero-based indexing, where 0 is the index of the first element and <code>len(list) - 1</code>
|
||
is the index of the last element.</p>
|
||
<p>For example,</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>]
|
||
<span class="hljs-meta">>>> </span>l[<span class="hljs-number">0</span>]
|
||
<span class="hljs-string">'BMW'</span>
|
||
<span class="hljs-meta">>>> </span>l[<span class="hljs-number">2</span>]
|
||
<span class="hljs-number">2019</span>
|
||
</code></pre>
|
||
<h3 id="length-of-list">Length of List<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#length-of-list">#</a></h3>
|
||
<p>The built-in <code>len()</code> function can be used to return the length of the list.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>]
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">len</span>(l)
|
||
<span class="hljs-number">6</span>
|
||
</code></pre>
|
||
<h3 id="negative-indexing">Negative Indexing<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#negative-indexing">#</a></h3>
|
||
<p>Just like <code>str</code>, sequence types like <code>list</code> support negative indexing, i.e., you
|
||
can access the values of list from the end.</p>
|
||
<p>Index of <code>-1</code> denotes the last item in the list, <code>-2</code> the second last item and so
|
||
forth.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>]
|
||
<span class="hljs-meta">>>> </span>l[-<span class="hljs-number">1</span>]
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span>l[-<span class="hljs-number">3</span>]
|
||
<span class="hljs-number">4</span>
|
||
</code></pre>
|
||
<h2 id="modifying-a-list">Modifying a List<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#modifying-a-list">#</a></h2>
|
||
<p>As lists are mutable, the assignment operator can be used to modify or replace a single item in the list
|
||
at a given index.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-string">"Red"</span>]
|
||
<span class="hljs-meta">>>> </span>l[<span class="hljs-number">2</span>] = <span class="hljs-string">"Black"</span>
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-string">'BMW'</span>, <span class="hljs-string">'Z4'</span>, <span class="hljs-string">'Black'</span>]
|
||
</code></pre>
|
||
<h2 id="removing-item-from-a-list">Removing Item from a List<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#removing-item-from-a-list">#</a></h2>
|
||
<p><code>del</code> statement can be used to delete an item at a given index of a list.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-string">"Red"</span>]
|
||
<span class="hljs-meta">>>> </span><span class="hljs-keyword">del</span> l[<span class="hljs-number">1</span>]
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-string">'BMW'</span>, <span class="hljs-string">'Red'</span>]
|
||
</code></pre>
|
||
<h2 id="list-operations">List Operations<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#list-operations">#</a></h2>
|
||
<p>We can perform various operations on a list (collection of items) such as membership, concatenation,
|
||
repetition and slicing.</p>
|
||
<h3 id="membership-1">Membership<a aria-hidden class="header-link" tabindex="-1" href="#membership-1">#</a>
|
||
</h3>
|
||
<p><code>in</code> and <code>not in</code> can be used to detect the membership of an item in a list.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-string">"Red"</span>]
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"Red"</span> <span class="hljs-keyword">in</span> l
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"Gold"</span> <span class="hljs-keyword">in</span> l
|
||
<span class="hljs-literal">False</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"Gold"</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> l
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<h3 id="concatenation-1">Concatenation<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#concatenation-1">#</a></h3>
|
||
<p><code>+</code> operator can be used to join two lists to create a new list.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>]
|
||
<span class="hljs-meta">>>> </span>k = [<span class="hljs-number">2019</span>, <span class="hljs-string">"Red"</span>]
|
||
<span class="hljs-meta">>>> </span>l + k
|
||
[<span class="hljs-string">'BMW'</span>, <span class="hljs-string">'Z4'</span>, <span class="hljs-number">2019</span>, <span class="hljs-string">'Red'</span>]
|
||
</code></pre>
|
||
<p><code>+=</code> operator joins two lists and assigns it to the target list.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>]
|
||
<span class="hljs-meta">>>> </span>l += [<span class="hljs-number">2019</span>, <span class="hljs-string">"Red"</span>]
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-string">'BMW'</span>, <span class="hljs-string">'Z4'</span>, <span class="hljs-number">2019</span>, <span class="hljs-string">'Red'</span>]
|
||
</code></pre>
|
||
<h3 id="repetition-1">Repetition<a aria-hidden class="header-link" tabindex="-1" href="#repetition-1">#</a>
|
||
</h3>
|
||
<p>The <code>*</code> operator repeats the items of a list the number of times as specified by the integer
|
||
operand.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
|
||
<span class="hljs-meta">>>> </span>l*<span class="hljs-number">3</span>
|
||
[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
|
||
</code></pre>
|
||
<h3 id="slicing-1">Slicing<a aria-hidden class="header-link" tabindex="-1" href="#slicing-1">#</a></h3>
|
||
<p>A subset of list <code>l</code> can be obtained using the list slice notation given as
|
||
<code>l[i:j]</code>, where the item at start index <code>i</code> is included, but the item at end index
|
||
<code>j</code> is excluded.
|
||
</p>
|
||
<p>For example, the slice notation <code>[1:4]</code> refers to items from index <code>1</code> to index
|
||
<code>3</code> (i.e. <code>4-1</code>).
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>]
|
||
<span class="hljs-meta">>>> </span>l[<span class="hljs-number">1</span>:<span class="hljs-number">4</span>]
|
||
[<span class="hljs-string">'Z4'</span>, <span class="hljs-number">2019</span>, <span class="hljs-number">4</span>]
|
||
</code></pre>
|
||
<p>The slice notation <code>l[i:j:k]</code> can also include a third number known as the stepper. Here, a
|
||
list is sliced from start index <code>i</code> to end index (<code>j</code>) - 1 with a step of
|
||
<code>k</code> items.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>]
|
||
<span class="hljs-meta">>>> </span>l[<span class="hljs-number">1</span>:<span class="hljs-number">4</span>:<span class="hljs-number">2</span>]
|
||
[<span class="hljs-string">'Z4'</span>, <span class="hljs-number">4</span>]
|
||
</code></pre>
|
||
<p>Slice notations also have some useful defaults. 0 is the default for the first number and size of the
|
||
list is the default for the second number.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>]
|
||
<span class="hljs-meta">>>> </span>l[<span class="hljs-number">2</span>:]
|
||
[<span class="hljs-number">2019</span>, <span class="hljs-number">4</span>, <span class="hljs-string">'Red'</span>, <span class="hljs-literal">True</span>]
|
||
<span class="hljs-meta">>>> </span>l[:<span class="hljs-number">4</span>]
|
||
[<span class="hljs-string">'BMW'</span>, <span class="hljs-string">'Z4'</span>, <span class="hljs-number">2019</span>, <span class="hljs-number">4</span>]
|
||
</code></pre>
|
||
<p>Slice notation also supports negative indexing.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>]
|
||
<span class="hljs-meta">>>> </span>l[-<span class="hljs-number">4</span>:]
|
||
[<span class="hljs-number">2019</span>, <span class="hljs-number">4</span>, <span class="hljs-string">'Red'</span>, <span class="hljs-literal">True</span>]
|
||
<span class="hljs-meta">>>> </span>l[:-<span class="hljs-number">2</span>]
|
||
[<span class="hljs-string">'BMW'</span>, <span class="hljs-string">'Z4'</span>, <span class="hljs-number">2019</span>, <span class="hljs-number">4</span>]
|
||
<span class="hljs-meta">>>> </span>l[-<span class="hljs-number">4</span>:-<span class="hljs-number">1</span>]
|
||
[<span class="hljs-number">2019</span>, <span class="hljs-number">4</span>, <span class="hljs-string">'Red'</span>]
|
||
</code></pre>
|
||
<p>Slice notation can be used to replace multiple items in a list.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>]
|
||
<span class="hljs-meta">>>> </span>l[:<span class="hljs-number">2</span>] = [<span class="hljs-string">"Kia"</span>, <span class="hljs-string">"Sonet"</span>]
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-string">'Kia'</span>, <span class="hljs-string">'Sonet'</span>, <span class="hljs-number">2019</span>, <span class="hljs-number">4</span>, <span class="hljs-string">'Red'</span>, <span class="hljs-literal">True</span>]
|
||
|
||
<span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>]
|
||
<span class="hljs-meta">>>> </span>l[<span class="hljs-number">1</span>:<span class="hljs-number">5</span>:<span class="hljs-number">2</span>] = [<span class="hljs-string">"Sonet"</span>, <span class="hljs-number">2</span>]
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-string">'BMW'</span>, <span class="hljs-string">'Sonet'</span>, <span class="hljs-number">2019</span>, <span class="hljs-number">2</span>, <span class="hljs-string">'Red'</span>, <span class="hljs-literal">True</span>]
|
||
</code></pre>
|
||
<p>Slice notation can also be used to delete multiple items in a list.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>]
|
||
<span class="hljs-meta">>>> </span><span class="hljs-keyword">del</span> l[:<span class="hljs-number">2</span>]
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-number">2019</span>, <span class="hljs-number">4</span>, <span class="hljs-string">'Red'</span>, <span class="hljs-literal">True</span>]
|
||
|
||
<span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>]
|
||
<span class="hljs-meta">>>> </span><span class="hljs-keyword">del</span> l[:<span class="hljs-number">5</span>:<span class="hljs-number">2</span>]
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-string">'Z4'</span>, <span class="hljs-number">4</span>, <span class="hljs-literal">True</span>]
|
||
</code></pre>
|
||
<h2 id="traversing-a-list">Traversing a List<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#traversing-a-list">#</a></h2>
|
||
<p>List Traversal is the process of visiting every item in a list, usually from the first item to the last
|
||
item, and executing some instruction on the accessed item.</p>
|
||
<p>Python provides 2 ways to traverse a list:</p>
|
||
<h3 id="direct-traversal">Direct Traversal<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#direct-traversal">#</a></h3>
|
||
<p>As a list is an ordered collection of items, the <code>for</code> statement can be used to directly and
|
||
sequentially access each item.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">l = [<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>]
|
||
<span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> l:
|
||
<span class="hljs-built_in">print</span>(item)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>BMW
|
||
Z4
|
||
2019
|
||
4
|
||
Red
|
||
True
|
||
</code></pre>
|
||
<h3 id="location-or-index-based-traversal">Location or Index Based Traversal<a aria-hidden
|
||
class="header-link" tabindex="-1" href="#location-or-index-based-traversal">#</a></h3>
|
||
<p>In location based or index based traversal the value of index starts at <code>0</code> and increments as
|
||
long as it is lesser than the length of the list.</p>
|
||
<p>This index value can be used to access the item at that index in a list using the index operator
|
||
<code>[]</code>.
|
||
</p>
|
||
<p><code>for</code> statement can be used to iterate over the index of the list using the
|
||
<code>range()</code> and <code>len()</code> functions.
|
||
</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">l = [<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>]
|
||
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-built_in">len</span>(l)):
|
||
<span class="hljs-built_in">print</span>(i, l[i])
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>0 BMW
|
||
1 Z4
|
||
2 2019
|
||
3 4
|
||
4 Red
|
||
5 True
|
||
</code></pre>
|
||
<p>This method is also useful when you need to modify the items of a list (without altering the length of
|
||
list) during traversal.</p>
|
||
<p>For example, let us convert each item of the list into a string.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">l = [<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>]
|
||
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-built_in">len</span>(l)):
|
||
<span class="hljs-comment"># modifying item value</span>
|
||
l[i] = <span class="hljs-built_in">str</span>(l[i])
|
||
<span class="hljs-built_in">print</span>(l)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>['BMW', 'Z4', '2019', '4', 'Red', 'True']
|
||
</code></pre>
|
||
<p>A <code>while</code> statement can be used to traverse a list by iterating on the value of index till the
|
||
last item index.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">l = [<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>]
|
||
i = <span class="hljs-number">0</span>
|
||
<span class="hljs-keyword">while</span> i < <span class="hljs-built_in">len</span>(l):
|
||
<span class="hljs-built_in">print</span>(l[i])
|
||
i += <span class="hljs-number">1</span>
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>BMW
|
||
Z4
|
||
2019
|
||
4
|
||
Red
|
||
True
|
||
</code></pre>
|
||
<h2 id="built-in-functions-that-can-be-used-for-a-list">Built-in Functions that can be used for a List<a
|
||
aria-hidden class="header-link" tabindex="-1"
|
||
href="#built-in-functions-that-can-be-used-for-a-list">#</a></h2>
|
||
<p>Built-in functions <code>max()</code>, <code>min()</code> and <code>sum()</code> are used to calculate
|
||
the maximum, minimum and sum of items in a list, respectively.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-number">4</span>, <span class="hljs-number">8</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>]
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">min</span>(l)
|
||
<span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">max</span>(l)
|
||
<span class="hljs-number">8</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">sum</span>(l)
|
||
<span class="hljs-number">18</span>
|
||
</code></pre>
|
||
<h2 id="introduction-to-list-methods">Introduction to List Methods<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#introduction-to-list-methods">#</a></h2>
|
||
<p>List objects have access to several specialized functions (methods) that can be used to:</p>
|
||
<ol>
|
||
<li>Add Items to a List</li>
|
||
<li>Remove Items from a List</li>
|
||
<li>Count or Locate Items in a List</li>
|
||
<li>Sort a List</li>
|
||
<li>Reverse a List</li>
|
||
<li>Copy the Contents of a List</li>
|
||
</ol>
|
||
<p>Let us discuss these methods in detail in the coming sections.</p>
|
||
<h2 id="adding-items-to-a-list">Adding Items to a List<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#adding-items-to-a-list">#</a></h2>
|
||
<p><code>append()</code> method adds an item (passed as an argument) to the end of a list.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"T"</span>, <span class="hljs-string">"C"</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>]
|
||
<span class="hljs-meta">>>> </span>l.append(<span class="hljs-number">2.5</span>)
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-string">'T'</span>, <span class="hljs-string">'C'</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">2.5</span>]
|
||
</code></pre>
|
||
<p>If the item has to be added at a particular index, <code>insert()</code> method can be used.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"T"</span>, <span class="hljs-string">"C"</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>]
|
||
<span class="hljs-meta">>>> </span>l.insert(<span class="hljs-number">3</span>, <span class="hljs-number">2.5</span>)
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-string">'T'</span>, <span class="hljs-string">'C'</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2.5</span>, <span class="hljs-number">4</span>]
|
||
</code></pre>
|
||
<p><code>extend()</code> method appends each item of the argument list at the end of the target list.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"T"</span>, <span class="hljs-string">"C"</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>]
|
||
<span class="hljs-meta">>>> </span>l.extend([<span class="hljs-number">2.5</span>, <span class="hljs-string">"SE"</span>])
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-string">'T'</span>, <span class="hljs-string">'C'</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">2.5</span>, <span class="hljs-string">'SE'</span>]
|
||
</code></pre>
|
||
<h2 id="removing-items-from-a-list">Removing Items from a List<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#removing-items-from-a-list">#</a></h2>
|
||
<p><code>clear()</code> method removes all items from the list.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"T"</span>, <span class="hljs-string">"C"</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"S"</span>]
|
||
<span class="hljs-meta">>>> </span>l.clear()
|
||
<span class="hljs-meta">>>> </span>l
|
||
[]
|
||
</code></pre>
|
||
<p><code>remove()</code> method removes the first occurrence of an item from the list.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"Hi"</span>, <span class="hljs-string">"Ed"</span>, <span class="hljs-string">"Py"</span>, <span class="hljs-string">"Hi"</span>]
|
||
<span class="hljs-meta">>>> </span>l.remove(<span class="hljs-string">"Hi"</span>)
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-string">'Ed'</span>, <span class="hljs-string">'Py'</span>, <span class="hljs-string">'Hi'</span>]
|
||
</code></pre>
|
||
<p>If an index is provided, <code>pop()</code> method removes the item at that index, else the last item is
|
||
removed from the list.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"T"</span>, <span class="hljs-string">"C"</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"S"</span>]
|
||
<span class="hljs-meta">>>> </span>item = l.pop()
|
||
<span class="hljs-meta">>>> </span>item
|
||
<span class="hljs-string">'S'</span>
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-string">'T'</span>, <span class="hljs-string">'C'</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>]
|
||
|
||
<span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"T"</span>, <span class="hljs-string">"C"</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"S"</span>]
|
||
<span class="hljs-meta">>>> </span>item = l.pop(<span class="hljs-number">2</span>)
|
||
<span class="hljs-meta">>>> </span>item
|
||
<span class="hljs-number">2</span>
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-string">'T'</span>, <span class="hljs-string">'C'</span>, <span class="hljs-number">4</span>, <span class="hljs-string">'S'</span>]
|
||
</code></pre>
|
||
<h2 id="counting-or-locating-items-in-a-list">Counting or Locating Items in a List<a aria-hidden
|
||
class="header-link" tabindex="-1" href="#counting-or-locating-items-in-a-list">#</a></h2>
|
||
<p>An item <code>x</code> can be located in a list using the <code>index(x[, i[, j]])</code> method which
|
||
returns the first occurrence of the item at or after index <code>i</code> and before index
|
||
<code>j</code>.
|
||
</p>
|
||
<p>In case <code>i</code> and <code>j</code> are not specified they default to <code>i=0</code> and
|
||
<code>j=len(l)</code>.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-number">34</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">23</span>, <span class="hljs-number">4</span>]
|
||
<span class="hljs-meta">>>> </span>l.index(<span class="hljs-number">4</span>)
|
||
<span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span>l.index(<span class="hljs-number">4</span>, <span class="hljs-number">3</span>)
|
||
<span class="hljs-number">4</span>
|
||
<span class="hljs-meta">>>> </span>l.index(<span class="hljs-number">6</span>, <span class="hljs-number">1</span>, <span class="hljs-number">4</span>)
|
||
<span class="hljs-number">2</span>
|
||
</code></pre>
|
||
<p><code>count()</code> method can be used to count the occurrence(s) of an item in a list.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-number">34</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">23</span>]
|
||
<span class="hljs-meta">>>> </span>l.count(<span class="hljs-number">4</span>)
|
||
<span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"it"</span>, <span class="hljs-string">"is"</span>, <span class="hljs-string">"it"</span>, <span class="hljs-string">"I"</span>]
|
||
<span class="hljs-meta">>>> </span>l.count(<span class="hljs-string">"it"</span>)
|
||
<span class="hljs-number">2</span>
|
||
</code></pre>
|
||
<h2 id="reversing-items">Reversing Items<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#reversing-items">#</a></h2>
|
||
<p><code>reverse()</code> method can be used to reverse a list in-place.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"T"</span>, <span class="hljs-string">"C"</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"S"</span>]
|
||
<span class="hljs-meta">>>> </span>l.reverse()
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-string">'S'</span>, <span class="hljs-number">4</span>, <span class="hljs-number">2</span>, <span class="hljs-string">'C'</span>, <span class="hljs-string">'T'</span>]
|
||
</code></pre>
|
||
<p>If you do not wish to modify the existing list and create a new list with items in reverse order, use the
|
||
built-in function <code>reversed()</code> nested in the built-in <code>list()</code>.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"T"</span>, <span class="hljs-string">"C"</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"S"</span>]
|
||
<span class="hljs-meta">>>> </span>new_l = <span class="hljs-built_in">list</span>(<span class="hljs-built_in">reversed</span>(l))
|
||
<span class="hljs-meta">>>> </span>new_l
|
||
[<span class="hljs-string">'S'</span>, <span class="hljs-number">4</span>, <span class="hljs-number">2</span>, <span class="hljs-string">'C'</span>, <span class="hljs-string">'T'</span>]
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-string">'T'</span>, <span class="hljs-string">'C'</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-string">'S'</span>]
|
||
</code></pre>
|
||
<h2 id="sorting-a-list">Sorting a List<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#sorting-a-list">#</a></h2>
|
||
<p>Python lists have a built-in <code>sort()</code> method which sorts the items in-place using
|
||
<code><</code> comparisons between items.
|
||
</p>
|
||
<p>The method also accepts 2 keyworded arguments:</p>
|
||
<ul>
|
||
<li><code>key</code> is used to specify a function which is called on each list element prior to making
|
||
the comparisons.</li>
|
||
<li><code>reverse</code> is a boolean which specifies whether the list is to be sorted in descending
|
||
order.</li>
|
||
</ul>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-number">34</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">23</span>]
|
||
<span class="hljs-meta">>>> </span>l.sort()
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">23</span>, <span class="hljs-number">34</span>]
|
||
|
||
<span class="hljs-meta">>>> </span>l = [<span class="hljs-number">34</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">23</span>]
|
||
<span class="hljs-meta">>>> </span>l.sort(reverse=<span class="hljs-literal">True</span>)
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-number">34</span>, <span class="hljs-number">23</span>, <span class="hljs-number">6</span>, <span class="hljs-number">4</span>]
|
||
|
||
<span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"Oh"</span>, <span class="hljs-string">"Hi"</span>, <span class="hljs-string">"Py"</span>, <span class="hljs-string">"ed"</span>]
|
||
<span class="hljs-meta">>>> </span>l.sort()
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-string">'Hi'</span>, <span class="hljs-string">'Oh'</span>, <span class="hljs-string">'Py'</span>, <span class="hljs-string">'ed'</span>]
|
||
|
||
<span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"Oh"</span>, <span class="hljs-string">"Hi"</span>, <span class="hljs-string">"Py"</span>, <span class="hljs-string">"ed"</span>]
|
||
<span class="hljs-comment"># lowercase the words before sorting</span>
|
||
<span class="hljs-meta">>>> </span>l.sort(key=<span class="hljs-built_in">str</span>.lower)
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-string">'ed'</span>, <span class="hljs-string">'Hi'</span>, <span class="hljs-string">'Oh'</span>, <span class="hljs-string">'Py'</span>]
|
||
</code></pre>
|
||
<p>If you do not wish to modify the existing list and create a new list with sorted items in, use the
|
||
built-in <code>sorted()</code> function which returns a new sorted list.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-number">34</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">23</span>]
|
||
<span class="hljs-meta">>>> </span>new_l = <span class="hljs-built_in">sorted</span>(l)
|
||
<span class="hljs-meta">>>> </span>new_l
|
||
[<span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">23</span>, <span class="hljs-number">34</span>]
|
||
</code></pre>
|
||
<h2 id="copying-a-list">Copying a List<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#copying-a-list">#</a></h2>
|
||
<p>In Python, we can create an object (data) and bind its reference to a variable using the assignment
|
||
operator (<code>=</code>).</p>
|
||
<p>As multiple collections or items in collections can point to the same mutable object, a copy is required
|
||
so one can change one copy without changing the other.</p>
|
||
<p>Let us take an example:</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>old_l = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
|
||
|
||
<span class="hljs-comment"># Copying old list into a new list</span>
|
||
<span class="hljs-meta">>>> </span>new_l = old_l
|
||
|
||
<span class="hljs-comment"># Checking if both lists are </span>
|
||
<span class="hljs-comment"># pointing to the same object</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">id</span>(new_l)==<span class="hljs-built_in">id</span>(old_l)
|
||
<span class="hljs-literal">True</span>
|
||
|
||
<span class="hljs-comment"># Adding element to new list</span>
|
||
<span class="hljs-meta">>>> </span>new_l.append(<span class="hljs-number">4</span>)
|
||
<span class="hljs-meta">>>> </span>new_l
|
||
[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
|
||
<span class="hljs-meta">>>> </span>old_l
|
||
[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
|
||
</code></pre>
|
||
<p>It can be seen how the assignment operator <strong>does not create a new copy</strong> of the list.</p>
|
||
<p>The <code>copy()</code> method can be used to create a new <code>list</code> containing the items of the
|
||
original list.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>old_l = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
|
||
|
||
<span class="hljs-comment"># Copying old list into a new list</span>
|
||
<span class="hljs-meta">>>> </span>new_l = old_l.copy()
|
||
|
||
<span class="hljs-comment"># Checking if both lists are </span>
|
||
<span class="hljs-comment"># pointing to the same object</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">id</span>(new_l)==<span class="hljs-built_in">id</span>(old_l)
|
||
<span class="hljs-literal">False</span>
|
||
|
||
<span class="hljs-comment"># Adding element to new list</span>
|
||
<span class="hljs-meta">>>> </span>new_l.append(<span class="hljs-number">4</span>)
|
||
<span class="hljs-meta">>>> </span>new_l
|
||
[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
|
||
<span class="hljs-meta">>>> </span>old_l
|
||
[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
|
||
</code></pre>
|
||
<p>Assigning a slice of the entire list (<code>[:]</code>) is also equivalent to creating a new copy.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>old_l = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
|
||
|
||
<span class="hljs-comment"># Copying old list into a new list</span>
|
||
<span class="hljs-comment"># using slice notation</span>
|
||
<span class="hljs-meta">>>> </span>new_l = old_l[:]
|
||
|
||
<span class="hljs-comment"># Checking if both lists are </span>
|
||
<span class="hljs-comment"># pointing to the same object</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">id</span>(new_l)==<span class="hljs-built_in">id</span>(old_l)
|
||
<span class="hljs-literal">False</span>
|
||
|
||
<span class="hljs-comment"># Adding element to new list</span>
|
||
<span class="hljs-meta">>>> </span>new_l.append(<span class="hljs-number">4</span>)
|
||
<span class="hljs-meta">>>> </span>new_l
|
||
[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
|
||
<span class="hljs-meta">>>> </span>old_l
|
||
[<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
|
||
</code></pre>
|
||
<h2 id="nested-list">Nested List<a aria-hidden class="header-link" tabindex="-1" href="#nested-list">#</a>
|
||
</h2>
|
||
<p>A list of lists is also known as a nested list.</p>
|
||
<p>Previously, we learnt how to create a list of attributes of a particular vehicle available for sale in a
|
||
dealership.</p>
|
||
<p>Let us now create a nested list containing some details of vehicles available for sale.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-comment"># Make Model Year No_of_wheels</span>
|
||
l = [[<span class="hljs-string">"Kia"</span>, <span class="hljs-string">"Sonnet"</span>, <span class="hljs-number">2019</span>, <span class="hljs-number">4</span>],
|
||
[<span class="hljs-string">"Toyota"</span>, <span class="hljs-string">"Camry"</span>, <span class="hljs-number">2018</span>, <span class="hljs-number">4</span>],
|
||
[<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2015</span>, <span class="hljs-number">4</span>],
|
||
[<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"S1000"</span>, <span class="hljs-number">2016</span>, <span class="hljs-number">2</span>],
|
||
[<span class="hljs-string">"KTM"</span>, <span class="hljs-string">"390"</span>, <span class="hljs-number">2019</span>, <span class="hljs-number">2</span>],
|
||
]
|
||
</code></pre>
|
||
<p>Thus, nested list is useful in representing a dataset where each item is a list (datum) containing the
|
||
attributes of an observation.</p>
|
||
<p><code>l[i][j]</code> is the syntax to fetch the <code>j+1th</code> item of the list at index
|
||
<code>i</code> of the nested list <code>l</code>.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l[<span class="hljs-number">2</span>][<span class="hljs-number">1</span>]
|
||
<span class="hljs-string">'Z4'</span>
|
||
</code></pre>
|
||
<h2 id="list-comprehension">List Comprehension<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#list-comprehension">#</a></h2>
|
||
<p>A short and succinct way of creating a new list by transforming an existing list is via list
|
||
comprehension.</p>
|
||
<p>Also, due to the optimizations present in the Python interpreter, there are performance benefits of using
|
||
list comprehension.</p>
|
||
<h3 id="member-wise-operation">Member-wise Operation<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#member-wise-operation">#</a></h3>
|
||
<p>List comprehension can be used to make a new list where each element is the result of some operations
|
||
applied to each member of another sequence or iterable.</p>
|
||
<p>For example, to create a new list where each item is squared.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>]
|
||
<span class="hljs-meta">>>> </span>l2 = [i**<span class="hljs-number">2</span> <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> l]
|
||
<span class="hljs-meta">>>> </span>l2
|
||
[<span class="hljs-number">4</span>, <span class="hljs-number">9</span>, <span class="hljs-number">16</span>, <span class="hljs-number">25</span>, <span class="hljs-number">36</span>, <span class="hljs-number">64</span>]
|
||
</code></pre>
|
||
<h3 id="filtering-or-subsequence">Filtering or Subsequence<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#filtering-or-subsequence">#</a></h3>
|
||
<p>List comprehension can also be used to create a subsequence of those elements that satisfy a certain
|
||
condition.</p>
|
||
<p>For example, to create a new list where each item is divisible by 2.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>]
|
||
<span class="hljs-meta">>>> </span>l2 = [i <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> l <span class="hljs-keyword">if</span> i%<span class="hljs-number">2</span>==<span class="hljs-number">0</span>]
|
||
<span class="hljs-meta">>>> </span>l2
|
||
[<span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>]
|
||
</code></pre>
|
||
<h2 id="sample-programs">Sample Programs<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#sample-programs">#</a></h2>
|
||
<h3 id="1-min-max-and-mean">1. Min, Max and Mean<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#1-min-max-and-mean">#</a></h3>
|
||
<p>Write a program to find the minimum, maximum and mean of values stored in a list input by user.</p>
|
||
<p><strong>a) Without Using Built-in Functions</strong></p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-comment">#create an empty list</span>
|
||
l = []
|
||
|
||
n = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter length of list: "</span>))
|
||
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(n):
|
||
val = <span class="hljs-built_in">float</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter item: "</span>))
|
||
<span class="hljs-comment">#append marks in the list </span>
|
||
l.append(val)
|
||
|
||
<span class="hljs-comment"># Set first item as the default min value</span>
|
||
minval = l[<span class="hljs-number">0</span>]
|
||
<span class="hljs-comment"># Set first item as the default max value</span>
|
||
maxval = l[<span class="hljs-number">0</span>]
|
||
<span class="hljs-comment"># Store sum of items</span>
|
||
s = <span class="hljs-number">0</span>
|
||
<span class="hljs-keyword">for</span> val <span class="hljs-keyword">in</span> l:
|
||
<span class="hljs-comment"># check if item value is smaller than current min val</span>
|
||
<span class="hljs-keyword">if</span> val < minval:
|
||
minval = val
|
||
<span class="hljs-comment"># check if item value is greater than current max val</span>
|
||
<span class="hljs-keyword">if</span> val > maxval:
|
||
maxval = val
|
||
s += val
|
||
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Minimum :"</span>, minval)
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Maximum :"</span>, maxval)
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Mean :"</span>, s/n)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Enter length of list: 5
|
||
Enter item: 3
|
||
Enter item: 2
|
||
Enter item: 6
|
||
Enter item: 9
|
||
Enter item: 1
|
||
Minimum : 1.0
|
||
Maximum : 9.0
|
||
Mean : 4.2
|
||
</code></pre>
|
||
<p><strong>b) Using Built-in Functions</strong></p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-comment">#create an empty list</span>
|
||
l = []
|
||
|
||
n = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter length of list: "</span>))
|
||
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(n):
|
||
val = <span class="hljs-built_in">float</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter item: "</span>))
|
||
<span class="hljs-comment">#append marks in the list </span>
|
||
l.append(val)
|
||
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Minimum :"</span>, <span class="hljs-built_in">min</span>(l))
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Maximum :"</span>, <span class="hljs-built_in">max</span>(l))
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Mean :"</span>, <span class="hljs-built_in">sum</span>(l)/n)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Enter length of list: 5
|
||
Enter item: 3
|
||
Enter item: 2
|
||
Enter item: 6
|
||
Enter item: 9
|
||
Enter item: 1
|
||
Minimum : 1.0
|
||
Maximum : 9.0
|
||
Mean : 4.2
|
||
</code></pre>
|
||
<h3 id="2-linear-search">2. Linear Search<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#2-linear-search">#</a></h3>
|
||
<p>Write a program to enter a list and then check if the number entered by a user is present in that list.
|
||
</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-comment">#create an empty list</span>
|
||
l = []
|
||
|
||
n = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter length of list: "</span>))
|
||
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(n):
|
||
val = <span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter item: "</span>)
|
||
<span class="hljs-comment">#append marks in the list </span>
|
||
l.append(val)
|
||
|
||
search = <span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter search value: "</span>)
|
||
|
||
found = <span class="hljs-literal">False</span>
|
||
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(n):
|
||
<span class="hljs-keyword">if</span> l[i] == search:
|
||
found = <span class="hljs-literal">True</span>
|
||
<span class="hljs-keyword">break</span>
|
||
<span class="hljs-keyword">if</span> found:
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Search value located at index"</span>, i)
|
||
<span class="hljs-keyword">else</span>:
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Search value not found"</span>)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Enter length of list: 4
|
||
Enter item: 2
|
||
Enter item: 6
|
||
Enter item: 3
|
||
Enter item: 7
|
||
Enter search value: 3
|
||
Search value located at index 2
|
||
|
||
Enter length of list: 4
|
||
Enter item: 2
|
||
Enter item: 6
|
||
Enter item: 3
|
||
Enter item: 7
|
||
Enter search value: 1
|
||
Search value not found
|
||
</code></pre>
|
||
<h3 id="3-frequency-of-elements">3. Frequency of Elements<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#3-frequency-of-elements">#</a></h3>
|
||
<p>Write a program to enter a list and then print the frequency of elements present in that list.</p>
|
||
<p><strong>a) Without Using Built-in Functions</strong></p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-comment">#create an empty list</span>
|
||
l = []
|
||
|
||
n = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter length of list: "</span>))
|
||
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(n):
|
||
val = <span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter item: "</span>)
|
||
<span class="hljs-comment">#append marks in the list </span>
|
||
l.append(val)
|
||
|
||
<span class="hljs-comment"># Let us create two lists </span>
|
||
<span class="hljs-comment"># 1. to store unique items </span>
|
||
items = []
|
||
<span class="hljs-comment"># 2. to store the count of unique items</span>
|
||
counts = []
|
||
|
||
<span class="hljs-keyword">for</span> val <span class="hljs-keyword">in</span> l:
|
||
<span class="hljs-keyword">if</span> val <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> items:
|
||
items.append(val)
|
||
counts.append(<span class="hljs-number">1</span>)
|
||
<span class="hljs-keyword">else</span>:
|
||
<span class="hljs-keyword">for</span> idx <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-built_in">len</span>(items)):
|
||
<span class="hljs-keyword">if</span> items[idx] == val:
|
||
counts[idx] += <span class="hljs-number">1</span>
|
||
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Frequency of Elements"</span>)
|
||
<span class="hljs-keyword">for</span> idx <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-built_in">len</span>(items)):
|
||
<span class="hljs-built_in">print</span>(items[idx], <span class="hljs-string">"-"</span>, counts[idx])
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Enter length of list: 8
|
||
Enter item: 2
|
||
Enter item: 3
|
||
Enter item: 3
|
||
Enter item: 4
|
||
Enter item: 2
|
||
Enter item: 5
|
||
Enter item: 6
|
||
Enter item: 6
|
||
Frequency of Elements
|
||
2 - 2
|
||
3 - 2
|
||
4 - 1
|
||
5 - 1
|
||
6 - 2
|
||
</code></pre>
|
||
<p><strong>b) Using Built-in Functions</strong></p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">l = []
|
||
|
||
n = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter length of list: "</span>))
|
||
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(n):
|
||
val = <span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter item: "</span>)
|
||
<span class="hljs-comment">#append marks in the list </span>
|
||
l.append(val)
|
||
|
||
<span class="hljs-comment"># List to store unique items </span>
|
||
items = []
|
||
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Frequency of Elements"</span>)
|
||
<span class="hljs-keyword">for</span> val <span class="hljs-keyword">in</span> l:
|
||
<span class="hljs-keyword">if</span> val <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> items:
|
||
items.append(val)
|
||
<span class="hljs-built_in">print</span>(val, <span class="hljs-string">"-"</span>, l.count(val))
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Enter length of list: 8
|
||
Enter item: 2
|
||
Enter item: 3
|
||
Enter item: 3
|
||
Enter item: 4
|
||
Enter item: 2
|
||
Enter item: 5
|
||
Enter item: 6
|
||
Enter item: 6
|
||
Frequency of Elements
|
||
2 - 2
|
||
3 - 2
|
||
4 - 1
|
||
5 - 1
|
||
6 - 2
|
||
</code></pre>
|
||
<h1 id="tuple">Tuple<a aria-hidden class="header-link" tabindex="-1" href="#tuple">#</a></h1>
|
||
<h2 id="list-vs-tuple">List vs Tuple<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#list-vs-tuple">#</a></h2>
|
||
<p>Tuples are like lists, with a difference - they are immutable. This means that once initialized a user
|
||
cannot modify its value, which makes it a useful feature to ensure the sanctity of data and guarantee
|
||
that it is not being modified by the program.</p>
|
||
<h2 id="how-to-create-tuple">How to Create Tuple?<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#how-to-create-tuple">#</a></h2>
|
||
<p>Tuples are declared using parentheses <code>( )</code>, with successive items separated by a comma
|
||
<code>,</code>.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = (<span class="hljs-string">"Hi"</span>, <span class="hljs-string">"Ed"</span>, <span class="hljs-string">"Punk"</span>)
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">type</span>(l)
|
||
<<span class="hljs-keyword">class</span> <span class="hljs-string">'tuple'</span>>
|
||
</code></pre>
|
||
<h3 id="tuple-1">tuple()<a aria-hidden class="header-link" tabindex="-1" href="#tuple-1">#</a></h3>
|
||
<p>Apart from the method shown above, the built-in <code>tuple()</code> function can also be used to create
|
||
new tuples.</p>
|
||
<p>If no arguments are provided to the <code>tuple()</code> function, an empty tuple is created.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>t = <span class="hljs-built_in">tuple</span>()
|
||
<span class="hljs-meta">>>> </span>t
|
||
()
|
||
</code></pre>
|
||
<p>If a string, tuple or set is passed as an argument, <code>tuple()</code> functions converts them into a
|
||
tuple.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>t = <span class="hljs-built_in">tuple</span>(<span class="hljs-string">"abcd"</span>)
|
||
<span class="hljs-meta">>>> </span>t
|
||
(<span class="hljs-string">'a'</span>, <span class="hljs-string">'b'</span>, <span class="hljs-string">'c'</span>, <span class="hljs-string">'d'</span>)
|
||
<span class="hljs-meta">>>> </span>t = <span class="hljs-built_in">tuple</span>({<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>})
|
||
<span class="hljs-meta">>>> </span>t
|
||
(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)
|
||
<span class="hljs-meta">>>> </span>t = <span class="hljs-built_in">tuple</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>])
|
||
<span class="hljs-meta">>>> </span>t
|
||
(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>)
|
||
</code></pre>
|
||
<h2 id="what-is-a-singleton">What is a Singleton?<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#what-is-a-singleton">#</a></h2>
|
||
<p>In case a tuple has only 1 item, it is known as a singleton.</p>
|
||
<p>It is a good practice to include a trailing comma to avoid the Python interpreter from treating it as a
|
||
value inside regular parentheses as shown in the examples below.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>regular_string = (<span class="hljs-string">"Hi"</span>)
|
||
<span class="hljs-meta">>>> </span>regular_string
|
||
<span class="hljs-string">'Hi'</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">type</span>(regular_string)
|
||
<<span class="hljs-keyword">class</span> <span class="hljs-string">'str'</span>>
|
||
|
||
<span class="hljs-meta">>>> </span>regular_int = (<span class="hljs-number">1</span>)
|
||
<span class="hljs-meta">>>> </span>regular_int
|
||
<span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">type</span>(regular_int)
|
||
<<span class="hljs-keyword">class</span> <span class="hljs-string">'int'</span>>
|
||
|
||
<span class="hljs-meta">>>> </span>str_tuple = (<span class="hljs-string">"Hi"</span>, )
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">type</span>(str_tuple)
|
||
<<span class="hljs-keyword">class</span> <span class="hljs-string">'tuple'</span>>
|
||
|
||
<span class="hljs-meta">>>> </span>int_tuple = (<span class="hljs-number">1</span>, )
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">type</span>(int_tuple)
|
||
<<span class="hljs-keyword">class</span> <span class="hljs-string">'tuple'</span>>
|
||
</code></pre>
|
||
<h2 id="accessing-items-of-a-tuple">Accessing Items of a Tuple<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#accessing-items-of-a-tuple">#</a></h2>
|
||
<p>Tuples use zero-based indexing, where 0 is the index of the first element and <code>len(tuple) - 1</code>
|
||
is the index of the last element.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>t = (<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>)
|
||
<span class="hljs-meta">>>> </span>t[<span class="hljs-number">0</span>]
|
||
<span class="hljs-string">'BMW'</span>
|
||
<span class="hljs-meta">>>> </span>t[<span class="hljs-number">2</span>]
|
||
<span class="hljs-number">2019</span>
|
||
</code></pre>
|
||
<h3 id="length-of-tuple">Length of Tuple<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#length-of-tuple">#</a></h3>
|
||
<p>The built-in <code>len()</code> function can be used to return the length of the tuple.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>t = (<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>)
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">len</span>(t)
|
||
<span class="hljs-number">6</span>
|
||
</code></pre>
|
||
<h3 id="negative-indexing-1">Negative Indexing<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#negative-indexing-1">#</a></h3>
|
||
<p>Just like <code>list</code>, <code>tuple</code> supports negative indexing, i.e., you can access the
|
||
values of tuple from the end. Index of -1 denotes the last item in the tuple, -2 is the second last item
|
||
and so forth.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>t = (<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>)
|
||
<span class="hljs-meta">>>> </span>t[-<span class="hljs-number">1</span>]
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span>t[-<span class="hljs-number">3</span>]
|
||
<span class="hljs-number">4</span>
|
||
</code></pre>
|
||
<h2 id="tuples-are-immutable">Tuples are Immutable<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#tuples-are-immutable">#</a></h2>
|
||
<p>Tuples are immutable, i.e., no modifications are permitted once it is created and any attempt to do so
|
||
raises an error.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>t = (<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>)
|
||
<span class="hljs-meta">>>> </span>t[<span class="hljs-number">1</span>] = <span class="hljs-string">"Charger"</span>
|
||
Traceback (most recent call last):
|
||
File <span class="hljs-string">"<stdin>"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> <module>
|
||
TypeError: <span class="hljs-string">'tuple'</span> <span class="hljs-built_in">object</span> does <span class="hljs-keyword">not</span> support item assignment
|
||
</code></pre>
|
||
<h2 id="tuple-operations">Tuple Operations<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#tuple-operations">#</a></h2>
|
||
<p>We can perform various operations on a tuple such as membership, concatenation, repetition and slicing.
|
||
</p>
|
||
<h3 id="membership-2">Membership<a aria-hidden class="header-link" tabindex="-1" href="#membership-2">#</a>
|
||
</h3>
|
||
<p><code>in</code> and <code>not in</code> can be used to detect the membership of an item in a tuple.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>t = (<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>)
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"Red"</span> <span class="hljs-keyword">in</span> t
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"Gold"</span> <span class="hljs-keyword">in</span> t
|
||
<span class="hljs-literal">False</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"Gold"</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> t
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<h3 id="concatenation-2">Concatenation<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#concatenation-2">#</a></h3>
|
||
<p><code>+</code> operator can be used to join two tuples to create a new tuple.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>t = (<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>)
|
||
<span class="hljs-meta">>>> </span>u = (<span class="hljs-number">2019</span>, <span class="hljs-string">"Red"</span>)
|
||
<span class="hljs-meta">>>> </span>t+u
|
||
(<span class="hljs-string">'BMW'</span>, <span class="hljs-string">'Z4'</span>, <span class="hljs-number">2019</span>, <span class="hljs-string">'Red'</span>)
|
||
</code></pre>
|
||
<h3 id="repetition-2">Repetition<a aria-hidden class="header-link" tabindex="-1" href="#repetition-2">#</a>
|
||
</h3>
|
||
<p>The <code>*</code> operator creates a new tuple with items of a tuple repeated the number of times as
|
||
specified by the integer operand.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>t = (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)
|
||
<span class="hljs-meta">>>> </span>t*<span class="hljs-number">3</span>
|
||
(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>)
|
||
</code></pre>
|
||
<h3 id="tuple-slicing">Tuple Slicing<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#tuple-slicing">#</a></h3>
|
||
<p>A subset of tuple <code>t</code> can be obtained using the tuple slice notation given as
|
||
<code>t[i:j]</code>, where the item at index <code>i</code> is included, but the item at index
|
||
<code>j</code> is excluded.
|
||
</p>
|
||
<p>For example, the slice notation <code>[1:4]</code> refers to items from index <code>1</code> to index
|
||
<code>3</code> (i.e. <code>4-1</code>).
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>t = (<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>)
|
||
<span class="hljs-meta">>>> </span>t[<span class="hljs-number">1</span>:<span class="hljs-number">4</span>]
|
||
(<span class="hljs-string">'Z4'</span>, <span class="hljs-number">2019</span>, <span class="hljs-number">4</span>)
|
||
</code></pre>
|
||
<p>The slice notation <code>t[i:j:k]</code> can also include a third number known as the step. Here, a tuple
|
||
is sliced from start index <code>i</code> to end index (<code>j</code>) - 1 with a step of
|
||
<code>k</code> items.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>t = (<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>)
|
||
<span class="hljs-meta">>>> </span>t[<span class="hljs-number">1</span>:<span class="hljs-number">4</span>:<span class="hljs-number">2</span>]
|
||
(<span class="hljs-string">'Z4'</span>, <span class="hljs-number">4</span>)
|
||
</code></pre>
|
||
<p>Slice notations also have some useful defaults.</p>
|
||
<p><code>0</code> is the default for the first number and size of the tuple is the default for the second
|
||
number.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>t = (<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>)
|
||
<span class="hljs-meta">>>> </span>t[<span class="hljs-number">2</span>:]
|
||
(<span class="hljs-number">2019</span>, <span class="hljs-number">4</span>, <span class="hljs-string">'Red'</span>, <span class="hljs-literal">True</span>)
|
||
<span class="hljs-meta">>>> </span>t[:<span class="hljs-number">4</span>]
|
||
(<span class="hljs-string">'BMW'</span>, <span class="hljs-string">'Z4'</span>, <span class="hljs-number">2019</span>, <span class="hljs-number">4</span>)
|
||
</code></pre>
|
||
<p>Slice notation also supports negative indexing.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>t = (<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>)
|
||
<span class="hljs-meta">>>> </span>t[-<span class="hljs-number">4</span>:]
|
||
(<span class="hljs-number">2019</span>, <span class="hljs-number">4</span>, <span class="hljs-string">'Red'</span>, <span class="hljs-literal">True</span>)
|
||
<span class="hljs-meta">>>> </span>t[:-<span class="hljs-number">2</span>]
|
||
(<span class="hljs-string">'BMW'</span>, <span class="hljs-string">'Z4'</span>, <span class="hljs-number">2019</span>, <span class="hljs-number">4</span>)
|
||
<span class="hljs-meta">>>> </span>t[-<span class="hljs-number">4</span>:-<span class="hljs-number">1</span>]
|
||
(<span class="hljs-number">2019</span>, <span class="hljs-number">4</span>, <span class="hljs-string">'Red'</span>)
|
||
</code></pre>
|
||
<h2 id="traversing-a-tuple">Traversing a Tuple<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#traversing-a-tuple">#</a></h2>
|
||
<p>Tuple Traversal is the process of visiting every item in a tuple, usually from the first item to the last
|
||
item, and executing some instruction on the accessed item.</p>
|
||
<p>Python provides 2 ways to traverse a tuple:</p>
|
||
<h3 id="direct-traversal-1">Direct Traversal<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#direct-traversal-1">#</a></h3>
|
||
<p>As a tuple is an ordered collection of items, the <code>for</code> statement can be used to directly and
|
||
sequentially access each item.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">t = (<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>)
|
||
<span class="hljs-keyword">for</span> item <span class="hljs-keyword">in</span> t:
|
||
<span class="hljs-built_in">print</span>(item)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>BMW
|
||
Z4
|
||
2019
|
||
4
|
||
Red
|
||
True
|
||
</code></pre>
|
||
<h3 id="location-or-index-based-traversal-1">Location or Index Based Traversal<a aria-hidden
|
||
class="header-link" tabindex="-1" href="#location-or-index-based-traversal-1">#</a></h3>
|
||
<p>In location based or index based traversal the value of index starts at <code>0</code> and increments as
|
||
long as it is lesser than the length of the tuple.</p>
|
||
<p>This index value can be used to access the item at that index in a tuple using the index operator
|
||
<code>[]</code>.
|
||
</p>
|
||
<p><code>for</code> statement can be used to iterate over the index of the tuple using the
|
||
<code>range()</code> and <code>len()</code> functions.
|
||
</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">t = (<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>)
|
||
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-built_in">len</span>(t)):
|
||
<span class="hljs-built_in">print</span>(t[i])
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>BMW
|
||
Z4
|
||
2019
|
||
4
|
||
Red
|
||
True
|
||
</code></pre>
|
||
<p>A <code>while</code> statement can be used to traverse a tuple by iterating on the value of index.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">t = (<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2019</span>,
|
||
<span class="hljs-number">4</span>, <span class="hljs-string">"Red"</span>, <span class="hljs-literal">True</span>)
|
||
index = <span class="hljs-number">0</span>
|
||
<span class="hljs-keyword">while</span> index < <span class="hljs-built_in">len</span>(t):
|
||
<span class="hljs-built_in">print</span>(t[index])
|
||
index += <span class="hljs-number">1</span>
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>BMW
|
||
Z4
|
||
2019
|
||
4
|
||
Red
|
||
True
|
||
</code></pre>
|
||
<h2 id="built-in-functions-that-can-be-used-for-a-tuple">Built-in Functions that can be used for a Tuple<a
|
||
aria-hidden class="header-link" tabindex="-1"
|
||
href="#built-in-functions-that-can-be-used-for-a-tuple">#</a></h2>
|
||
<p>Built-in functions <code>max()</code>, <code>min()</code> and <code>sum()</code> can be used to calculate
|
||
the maximum, minimum and sum of items in a tuple, respectively.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>t = (<span class="hljs-number">4</span>, <span class="hljs-number">8</span>, <span class="hljs-number">2</span>, <span class="hljs-number">1</span>, <span class="hljs-number">3</span>)
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">min</span>(t)
|
||
<span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">max</span>(t)
|
||
<span class="hljs-number">8</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">sum</span>(t)
|
||
<span class="hljs-number">18</span>
|
||
</code></pre>
|
||
<h2 id="locating-items-in-a-tuple">Locating Items in a Tuple<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#locating-items-in-a-tuple">#</a></h2>
|
||
<p>As compared to a <code>list</code>, <code>tuple</code> supports only methods that do not try to modify
|
||
it.</p>
|
||
<p>An item <code>x</code> can be located in a tuple using the <code>index(x[, i[, j]])</code> method which
|
||
returns the first occurrence of the item at or after index <code>i</code> and before index
|
||
<code>j</code>. In case <code>i</code> and <code>j</code> are not specified they default to
|
||
<code>i=0</code> and <code>j=len(t)</code>.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>t = (<span class="hljs-number">34</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">23</span>, <span class="hljs-number">4</span>)
|
||
<span class="hljs-meta">>>> </span>t.index(<span class="hljs-number">4</span>)
|
||
<span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span>t.index(<span class="hljs-number">4</span>, <span class="hljs-number">3</span>)
|
||
<span class="hljs-number">4</span>
|
||
<span class="hljs-meta">>>> </span>t.index(<span class="hljs-number">6</span>, <span class="hljs-number">1</span>, <span class="hljs-number">4</span>)
|
||
<span class="hljs-number">2</span>
|
||
</code></pre>
|
||
<h2 id="counting-the-occurrence-of-an-item">Counting the Occurrence of an Item<a aria-hidden
|
||
class="header-link" tabindex="-1" href="#counting-the-occurrence-of-an-item">#</a></h2>
|
||
<p><code>count()</code> method can be used to count the occurrence(s) of an item in a tuple.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>t = (<span class="hljs-number">34</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">23</span>, <span class="hljs-number">4</span>)
|
||
<span class="hljs-meta">>>> </span>t.count(<span class="hljs-number">4</span>)
|
||
<span class="hljs-number">2</span>
|
||
<span class="hljs-meta">>>> </span>t = (<span class="hljs-string">"it"</span>, <span class="hljs-string">"is"</span>, <span class="hljs-string">"it"</span>, <span class="hljs-string">"I"</span>)
|
||
<span class="hljs-meta">>>> </span>t.count(<span class="hljs-string">"it"</span>)
|
||
<span class="hljs-number">2</span>
|
||
</code></pre>
|
||
<h2 id="new-tuple-with-reversed-items">New Tuple with Reversed Items<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#new-tuple-with-reversed-items">#</a></h2>
|
||
<p>To create a new tuple with items in reverse order, use the built-in function <code>reversed()</code>
|
||
nested in the built-in <code>tuple()</code>.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>t = (<span class="hljs-string">"T"</span>, <span class="hljs-string">"C"</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-string">"S"</span>)
|
||
<span class="hljs-meta">>>> </span>new_t = <span class="hljs-built_in">tuple</span>(<span class="hljs-built_in">reversed</span>(t))
|
||
<span class="hljs-meta">>>> </span>new_t
|
||
(<span class="hljs-string">'S'</span>, <span class="hljs-number">4</span>, <span class="hljs-number">2</span>, <span class="hljs-string">'C'</span>, <span class="hljs-string">'T'</span>)
|
||
<span class="hljs-meta">>>> </span>t
|
||
(<span class="hljs-string">'T'</span>, <span class="hljs-string">'C'</span>, <span class="hljs-number">2</span>, <span class="hljs-number">4</span>, <span class="hljs-string">'S'</span>)
|
||
</code></pre>
|
||
<h2 id="new-tuple-with-sorted-items">New Tuple with Sorted Items<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#new-tuple-with-sorted-items">#</a></h2>
|
||
<p>To create a new tuple with sorted items, use the built-in <code>sorted(x,[key, reverse])</code> function
|
||
which returns a new sorted tuple.</p>
|
||
<p>The method optionally accepts 2 keyword (named) arguments:</p>
|
||
<ul>
|
||
<li><code>key</code> which is used to specify a function which is called on each tuple element prior to
|
||
making the comparisons, and</li>
|
||
<li><code>reverse</code> is a boolean which specifies whether the tuple is to be sorted in descending
|
||
order.</li>
|
||
</ul>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>t = (<span class="hljs-number">34</span>, <span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">23</span>, <span class="hljs-number">9</span>)
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">tuple</span>(<span class="hljs-built_in">sorted</span>(t))
|
||
(<span class="hljs-number">4</span>, <span class="hljs-number">6</span>, <span class="hljs-number">9</span>, <span class="hljs-number">23</span>, <span class="hljs-number">34</span>)
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">tuple</span>(<span class="hljs-built_in">sorted</span>(t, reverse=<span class="hljs-literal">True</span>))
|
||
(<span class="hljs-number">34</span>, <span class="hljs-number">23</span>, <span class="hljs-number">9</span>, <span class="hljs-number">6</span>, <span class="hljs-number">4</span>)
|
||
|
||
<span class="hljs-meta">>>> </span>t = (<span class="hljs-string">"Oh"</span>, <span class="hljs-string">"Hi"</span>, <span class="hljs-string">"Py"</span>, <span class="hljs-string">"it"</span>)
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">tuple</span>(<span class="hljs-built_in">sorted</span>(t))
|
||
(<span class="hljs-string">'Hi'</span>, <span class="hljs-string">'Oh'</span>, <span class="hljs-string">'Py'</span>, <span class="hljs-string">'it'</span>)
|
||
<span class="hljs-comment"># lowercase the words before sorting</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">tuple</span>(<span class="hljs-built_in">sorted</span>(t, key=<span class="hljs-built_in">str</span>.lower))
|
||
(<span class="hljs-string">'Hi'</span>, <span class="hljs-string">'it'</span>, <span class="hljs-string">'Oh'</span>, <span class="hljs-string">'Py'</span>)
|
||
</code></pre>
|
||
<h2 id="nested-tuple">Nested Tuple<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#nested-tuple">#</a></h2>
|
||
<p>A tuple of tuples is also known as a nested tuple.</p>
|
||
<p>Let us create a nested tuple containing the details of all vehicles available for sale.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-comment"># Make Model Year No_of_wheels</span>
|
||
t = (
|
||
(<span class="hljs-string">"Kia"</span>, <span class="hljs-string">"Sonnet"</span>, <span class="hljs-number">2019</span>, <span class="hljs-number">4</span>),
|
||
(<span class="hljs-string">"Toyota"</span>, <span class="hljs-string">"Camry"</span>, <span class="hljs-number">2018</span>, <span class="hljs-number">4</span>),
|
||
(<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"Z4"</span>, <span class="hljs-number">2015</span>, <span class="hljs-number">4</span>),
|
||
(<span class="hljs-string">"BMW"</span>, <span class="hljs-string">"S1000"</span>, <span class="hljs-number">2016</span>, <span class="hljs-number">2</span>),
|
||
(<span class="hljs-string">"KTM"</span>, <span class="hljs-string">"390"</span>, <span class="hljs-number">2019</span>, <span class="hljs-number">2</span>),
|
||
)
|
||
</code></pre>
|
||
<p><code>t[i][j]</code> is the syntax to fetch the <code>j+1 th</code> item of the tuple at index
|
||
<code>i</code> of the nested tuple <code>t</code>.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>t[<span class="hljs-number">2</span>][<span class="hljs-number">1</span>]
|
||
<span class="hljs-string">'Z4'</span>
|
||
</code></pre>
|
||
<p>As compared to a nested list, a nested tuple is useful in representing a dataset (such as a table fetched
|
||
from a database) where it is important to ensure the sanctity of data as the code cannot modify it
|
||
because tuples are immutable.</p>
|
||
<h2 id="understanding-the-immutable-nature-of-tuples">Understanding the Immutable Nature of Tuples<a
|
||
aria-hidden class="header-link" tabindex="-1"
|
||
href="#understanding-the-immutable-nature-of-tuples">#</a></h2>
|
||
<p>Just like lists, the <code>+=</code> operation works for a tuple and adds new item(s) to it.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>t = (<span class="hljs-string">"Hi"</span>, <span class="hljs-string">"Ed"</span>, <span class="hljs-string">"Punk"</span>)
|
||
<span class="hljs-meta">>>> </span>t += (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)
|
||
<span class="hljs-meta">>>> </span>t
|
||
(<span class="hljs-string">'Hi'</span>, <span class="hljs-string">'Ed'</span>, <span class="hljs-string">'Punk'</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>)
|
||
</code></pre>
|
||
<p>But tuples are immutable right?<br>Then how are we able to modify it.</p>
|
||
<p>To understand it better, let us revisit what happens when we apply <code>+=</code> operator on a list.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"Hi"</span>, <span class="hljs-string">"Ed"</span>, <span class="hljs-string">"Punk"</span>]
|
||
<span class="hljs-meta">>>> </span>id_l = <span class="hljs-built_in">id</span>(l)
|
||
<span class="hljs-meta">>>> </span>l += [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-string">'Hi'</span>, <span class="hljs-string">'Ed'</span>, <span class="hljs-string">'Punk'</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">id</span>(l) == id_l
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<p>In case of a list, the modified list <code>l</code> still points at the same object.</p>
|
||
<p>Now, let us add items to a tuple.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>t = (<span class="hljs-string">"Hi"</span>, <span class="hljs-string">"Ed"</span>, <span class="hljs-string">"Punk"</span>)
|
||
<span class="hljs-meta">>>> </span>id_t = <span class="hljs-built_in">id</span>(t)
|
||
<span class="hljs-meta">>>> </span>t += (<span class="hljs-number">1</span>, <span class="hljs-number">2</span>)
|
||
<span class="hljs-meta">>>> </span>t
|
||
(<span class="hljs-string">'Hi'</span>, <span class="hljs-string">'Ed'</span>, <span class="hljs-string">'Punk'</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>)
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">id</span>(t) == id_t
|
||
<span class="hljs-literal">False</span>
|
||
</code></pre>
|
||
<p>In case of a tuple, the modified tuple is actually a completely new tuple with contents of the original
|
||
tuple and the extension.</p>
|
||
<p>The original tuple is not modified as it is immutable. But, as <code>t</code> is no longer pointing to
|
||
the original tuple, it is freed from memory.</p>
|
||
<p>Thus, it is recommended that instead of <code>+=</code>, <code>append()</code> and <code>extend()</code>
|
||
methods should be employed to add new items programatically as it will raise an error in case the code
|
||
is trying to modify a tuple.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"Hi"</span>, <span class="hljs-string">"Ed"</span>, <span class="hljs-string">"Punk"</span>]
|
||
<span class="hljs-meta">>>> </span>l.extend([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>])
|
||
<span class="hljs-meta">>>> </span>l
|
||
[<span class="hljs-string">'Hi'</span>, <span class="hljs-string">'Ed'</span>, <span class="hljs-string">'Punk'</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>]
|
||
|
||
<span class="hljs-meta">>>> </span>t = (<span class="hljs-string">"Hi"</span>, <span class="hljs-string">"Ed"</span>, <span class="hljs-string">"Punk"</span>)
|
||
<span class="hljs-meta">>>> </span>t.extend((<span class="hljs-number">1</span>, <span class="hljs-number">2</span>))
|
||
Traceback (most recent call last):
|
||
File <span class="hljs-string">"<stdin>"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> <module>
|
||
AttributeError: <span class="hljs-string">'tuple'</span> <span class="hljs-built_in">object</span> has no attribute <span class="hljs-string">'extend'</span>
|
||
</code></pre>
|
||
<h1 id="dictionary">Dictionary<a aria-hidden class="header-link" tabindex="-1" href="#dictionary">#</a></h1>
|
||
<h2 id="what-is-a-dictionary">What is a Dictionary?<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#what-is-a-dictionary">#</a></h2>
|
||
<p>Python provides a mapping type collection which contains keys, and values corresponding to those keys.
|
||
</p>
|
||
<p>This collection is known as a <code>dictionary</code> (type <code>dict</code>) , where each key is unique
|
||
and can be used to easily store or retrieve values (any data-type including <code>string</code>,
|
||
<code>int</code>, <code>float</code>, <code>list</code>).
|
||
</p>
|
||
<p>Dictionaries are indexed by keys (any immutable type - numbers, string, tuple) as compared to lists which
|
||
are indexed by a range of numbers.</p>
|
||
<h2 id="how-to-create-a-dictionary">How to Create a Dictionary<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#how-to-create-a-dictionary">#</a></h2>
|
||
<p>An empty dictionary can be created using a pair of braces - <code>{}</code> or using the built-in
|
||
function <code>dict()</code> which is also a constructor.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>d = {}
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">type</span>(d)
|
||
<<span class="hljs-keyword">class</span> <span class="hljs-string">'dict'</span>>
|
||
|
||
<span class="hljs-meta">>>> </span>d = <span class="hljs-built_in">dict</span>()
|
||
<span class="hljs-meta">>>> </span>d
|
||
{}
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">type</span>(d)
|
||
<<span class="hljs-keyword">class</span> <span class="hljs-string">'dict'</span>>
|
||
</code></pre>
|
||
<p>To create a new dictionary with some initial values, one can use:</p>
|
||
<h3 id="key-value-pairs">Key: Value Pairs<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#key-value-pairs">#</a></h3>
|
||
<p>A sequence of <code>key: value</code> pairs separated by commas in braces - <code>{}</code>.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ed"</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-meta">>>> </span>d
|
||
{<span class="hljs-string">'yr'</span>: <span class="hljs-number">20</span>, <span class="hljs-string">'name'</span>: <span class="hljs-string">'Ed'</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
</code></pre>
|
||
<h3 id="sequence-of-key-value-tuples">Sequence of (key, value) Tuples<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#sequence-of-key-value-tuples">#</a></h3>
|
||
<p>A sequence of (key, value) tuples can be passed as an argument to the <code>dict()</code> function.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [(<span class="hljs-string">"yr"</span>,<span class="hljs-number">20</span>), (<span class="hljs-string">"name"</span>,<span class="hljs-string">"Ed"</span>),
|
||
<span class="hljs-meta">... </span> (<span class="hljs-number">18</span>,<span class="hljs-literal">True</span>)]
|
||
<span class="hljs-meta">>>> </span>d = <span class="hljs-built_in">dict</span>(l)
|
||
<span class="hljs-meta">>>> </span>d
|
||
{<span class="hljs-string">'yr'</span>: <span class="hljs-number">20</span>, <span class="hljs-string">'name'</span>: <span class="hljs-string">'Ed'</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
</code></pre>
|
||
<h3 id="keywordnamed-arguments">Keyword/Named Arguments<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#keywordnamed-arguments">#</a></h3>
|
||
<p>Keys and values can be passed as keyword arguments to the <code>dict()</code> function.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>d = <span class="hljs-built_in">dict</span>(yr=<span class="hljs-number">20</span>, name=<span class="hljs-string">"Ed"</span>,
|
||
<span class="hljs-meta">... </span> is18=<span class="hljs-literal">True</span>)
|
||
<span class="hljs-meta">>>> </span>d
|
||
{<span class="hljs-string">'yr'</span>: <span class="hljs-number">20</span>, <span class="hljs-string">'name'</span>: <span class="hljs-string">'Ed'</span>, <span class="hljs-string">'is18'</span>: <span class="hljs-literal">True</span>}
|
||
</code></pre>
|
||
<p>One of the limitations of this method is that the keys of the dictionary are only of type string and
|
||
their names must be within the namespace of an identifier.</p>
|
||
<h3 id="key-and-value-lists">Key and Value Lists<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#key-and-value-lists">#</a></h3>
|
||
<p>There might cases when there is a need to combine two lists where keys are in one list and the
|
||
corresponding values are available in another list.</p>
|
||
<p>The built-in <code>zip()</code> function is useful for combining two lists into tuple pairs.</p>
|
||
<p>The zipped iterator can be passed as an argument to the <code>dict()</code> to create a new mapping
|
||
collection.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>m = [<span class="hljs-string">"yr"</span>, <span class="hljs-string">"name"</span>, <span class="hljs-number">18</span>]
|
||
<span class="hljs-meta">>>> </span>n = [<span class="hljs-number">20</span>, <span class="hljs-string">"Ed"</span>, <span class="hljs-literal">True</span>]
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">list</span>(<span class="hljs-built_in">zip</span>(m, n))
|
||
[(<span class="hljs-string">'yr'</span>, <span class="hljs-number">20</span>), (<span class="hljs-string">'name'</span>, <span class="hljs-string">'Ed'</span>), (<span class="hljs-number">18</span>, <span class="hljs-literal">True</span>)]
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">dict</span>(<span class="hljs-built_in">zip</span>(m, n))
|
||
{<span class="hljs-string">'yr'</span>: <span class="hljs-number">20</span>, <span class="hljs-string">'name'</span>: <span class="hljs-string">'Ed'</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
</code></pre>
|
||
<h3 id="keys-with-default-value">Keys with Default Value<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#keys-with-default-value">#</a></h3>
|
||
<p><code>dict.fromkeys(iterable[, value])</code> can be used to create new dictionary with items of an
|
||
<code>iterable</code> as keys with an optional value (default - <code>None</code>) corresponding to the
|
||
keys.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>l = [<span class="hljs-string">"yr"</span>, <span class="hljs-string">"name"</span>, <span class="hljs-number">18</span>]
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">dict</span>.fromkeys(l)
|
||
{<span class="hljs-string">'yr'</span>: <span class="hljs-literal">None</span>, <span class="hljs-string">'name'</span>: <span class="hljs-literal">None</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">None</span>}
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">dict</span>.fromkeys(l, <span class="hljs-number">0</span>)
|
||
{<span class="hljs-string">'yr'</span>: <span class="hljs-number">0</span>, <span class="hljs-string">'name'</span>: <span class="hljs-number">0</span>, <span class="hljs-number">18</span>: <span class="hljs-number">0</span>}
|
||
</code></pre>
|
||
<h2 id="accessing-items-keyvalue-of-a-dictionary">Accessing Items (Key:Value) of a Dictionary<a aria-hidden
|
||
class="header-link" tabindex="-1" href="#accessing-items-keyvalue-of-a-dictionary">#</a></h2>
|
||
<h3 id="index-operator-">Index Operator []<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#index-operator-">#</a></h3>
|
||
<p><code>d[x]</code> can be used to access the value corresponding to a key <code>x</code> in a dictionary
|
||
<code>d</code>.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ed"</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-meta">>>> </span>d[<span class="hljs-string">"yr"</span>]
|
||
<span class="hljs-number">20</span>
|
||
</code></pre>
|
||
<h3 id="get">get()<a aria-hidden class="header-link" tabindex="-1" href="#get">#</a></h3>
|
||
<p><code>get(key[, default])</code> method can also be used to fetch the value for a key if key is in the
|
||
dictionary, else a <code>default</code> value is returned.</p>
|
||
<p>If <code>default</code> is not provided, <code>None</code> is the default value returned.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ed"</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-meta">>>> </span>d.get(<span class="hljs-string">"name"</span>)
|
||
<span class="hljs-string">'Ed'</span>
|
||
<span class="hljs-meta">>>> </span>d.get(<span class="hljs-string">"version"</span>) <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>
|
||
<span class="hljs-literal">True</span>
|
||
<span class="hljs-meta">>>> </span>d.get(<span class="hljs-string">"version"</span>, <span class="hljs-string">"1.0"</span>)
|
||
<span class="hljs-string">'1.0'</span>
|
||
</code></pre>
|
||
<p>This is an elegant method of fetching a value from a dictionary and it should be used in real life
|
||
software codes as it never raises a <code>KeyError</code>.</p>
|
||
<h2 id="updating-a-dictionary">Updating a Dictionary<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#updating-a-dictionary">#</a></h2>
|
||
<h3 id="index-operator--1">Index Operator []<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#index-operator--1">#</a></h3>
|
||
<p><code>d[x] = y</code> can be used to add the value <code>y</code> corresponding to a key <code>x</code>
|
||
in a dictionary <code>d</code>.</p>
|
||
<p>In case key <code>x</code> already exists, assignment updates or overwrites the value corresponding to
|
||
it.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-meta">>>> </span>d[<span class="hljs-string">"name"</span>] = <span class="hljs-string">'Ed'</span>
|
||
<span class="hljs-meta">>>> </span>d
|
||
{<span class="hljs-string">'yr'</span>: <span class="hljs-number">20</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>, <span class="hljs-string">'name'</span>: <span class="hljs-string">'Ed'</span>}
|
||
|
||
<span class="hljs-meta">>>> </span>d[<span class="hljs-string">"name"</span>] = <span class="hljs-string">'Py'</span>
|
||
<span class="hljs-meta">>>> </span>d
|
||
{<span class="hljs-string">'yr'</span>: <span class="hljs-number">20</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>, <span class="hljs-string">'name'</span>: <span class="hljs-string">'Py'</span>}
|
||
</code></pre>
|
||
<h3 id="update">update()<a aria-hidden class="header-link" tabindex="-1" href="#update">#</a></h3>
|
||
<p><code>update()</code> method can be used to add new items or update existing items in a
|
||
<code>dict</code>.
|
||
</p>
|
||
<p>This method accepts the following:</p>
|
||
<p><strong>1. Dictionary</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-meta">>>> </span>d.update({<span class="hljs-string">"name"</span>: <span class="hljs-string">'Ed'</span>})
|
||
<span class="hljs-meta">>>> </span>d
|
||
{<span class="hljs-string">'yr'</span>: <span class="hljs-number">20</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>, <span class="hljs-string">'name'</span>: <span class="hljs-string">'Ed'</span>}
|
||
|
||
<span class="hljs-meta">>>> </span>d.update({<span class="hljs-string">"yr"</span>: <span class="hljs-number">15</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">False</span>})
|
||
<span class="hljs-meta">>>> </span>d
|
||
{<span class="hljs-string">'yr'</span>: <span class="hljs-number">15</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">False</span>, <span class="hljs-string">'name'</span>: <span class="hljs-string">'Ed'</span>}
|
||
</code></pre>
|
||
<p><strong>2. Sequence of (key, value) pairs</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-meta">>>> </span>d.update([(<span class="hljs-string">"name"</span>, <span class="hljs-string">'Ed'</span>),
|
||
<span class="hljs-meta">... </span> (<span class="hljs-string">'yr'</span>, <span class="hljs-number">15</span>)])
|
||
<span class="hljs-meta">>>> </span>d
|
||
{<span class="hljs-string">'yr'</span>: <span class="hljs-number">15</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>, <span class="hljs-string">'name'</span>: <span class="hljs-string">'Ed'</span>}
|
||
</code></pre>
|
||
<p><strong>3. Keyworded arguments</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-meta">>>> </span>d.update(name=<span class="hljs-string">"Ed"</span>, yr=<span class="hljs-number">15</span>)
|
||
<span class="hljs-meta">>>> </span>d
|
||
{<span class="hljs-string">'yr'</span>: <span class="hljs-number">15</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>, <span class="hljs-string">'name'</span>: <span class="hljs-string">'Ed'</span>}
|
||
</code></pre>
|
||
<h3 id="setdefault">setdefault()<a aria-hidden class="header-link" tabindex="-1" href="#setdefault">#</a>
|
||
</h3>
|
||
<p><code>setdefault(key[, default])</code> method returns a value corresponding to a key.</p>
|
||
<p>If the key is not present in the dictionary, it is inserted with the provided <code>default</code> value.
|
||
</p>
|
||
<p>If no default value is provided, the value is set as <code>None</code>.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-meta">>>> </span>d.setdefault(<span class="hljs-string">"name"</span>)
|
||
<span class="hljs-meta">>>> </span>d
|
||
{<span class="hljs-string">'yr'</span>: <span class="hljs-number">20</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>, <span class="hljs-string">'name'</span>: <span class="hljs-literal">None</span>}
|
||
|
||
<span class="hljs-meta">>>> </span>d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-meta">>>> </span>d.setdefault(<span class="hljs-string">"name"</span>, <span class="hljs-string">"Ed"</span>)
|
||
<span class="hljs-string">'Ed'</span>
|
||
<span class="hljs-meta">>>> </span>d
|
||
{<span class="hljs-string">'yr'</span>: <span class="hljs-number">20</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>, <span class="hljs-string">'name'</span>: <span class="hljs-string">'Ed'</span>}
|
||
</code></pre>
|
||
<h2 id="removing-an-item-keyvalue-from-a-dictionary">Removing an Item (Key:Value) from a Dictionary<a
|
||
aria-hidden class="header-link" tabindex="-1"
|
||
href="#removing-an-item-keyvalue-from-a-dictionary">#</a></h2>
|
||
<h3 id="del">del<a aria-hidden class="header-link" tabindex="-1" href="#del">#</a></h3>
|
||
<p><code>del</code> keyword can be used to remove a <code>key: value</code> pair.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ed"</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-meta">>>> </span><span class="hljs-keyword">del</span> d[<span class="hljs-string">"name"</span>]
|
||
<span class="hljs-meta">>>> </span>d
|
||
{<span class="hljs-string">'yr'</span>: <span class="hljs-number">20</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
</code></pre>
|
||
<h3 id="clear">clear()<a aria-hidden class="header-link" tabindex="-1" href="#clear">#</a></h3>
|
||
<p><code>clear()</code> method can be used to clear all values of a dictionary.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ed"</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-meta">>>> </span>d.clear()
|
||
<span class="hljs-meta">>>> </span>d
|
||
{}
|
||
</code></pre>
|
||
<h3 id="pop">pop()<a aria-hidden class="header-link" tabindex="-1" href="#pop">#</a></h3>
|
||
<p><code>pop(key[, default])</code> method can be used to remove a <code>key: value</code> pair.</p>
|
||
<p>In case the key is not present in the dictionary, the method returns the value of argument
|
||
<code>default</code> provided by the user.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ed"</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-meta">>>> </span>d.pop(<span class="hljs-string">"name"</span>)
|
||
<span class="hljs-string">'Ed'</span>
|
||
<span class="hljs-meta">>>> </span>d
|
||
{<span class="hljs-string">'yr'</span>: <span class="hljs-number">20</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
|
||
<span class="hljs-meta">>>> </span>d.pop(<span class="hljs-string">"name"</span>)
|
||
Traceback (most recent call last):
|
||
File <span class="hljs-string">"<stdin>"</span>, line <span class="hljs-number">1</span>, <span class="hljs-keyword">in</span> <module>
|
||
KeyError: <span class="hljs-string">'name'</span>
|
||
|
||
<span class="hljs-meta">>>> </span>d.pop(<span class="hljs-string">"name"</span>, <span class="hljs-string">"Punk"</span>)
|
||
<span class="hljs-string">'Punk'</span>
|
||
</code></pre>
|
||
<h3 id="popitem">popitem()<a aria-hidden class="header-link" tabindex="-1" href="#popitem">#</a></h3>
|
||
<p><code>popitem()</code> can be used to destructively iterate over a dictionary removing and returning a
|
||
<code>(key, value)</code> pair in LIFO (Last Item First Out) order.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ed"</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-meta">>>> </span>d.popitem()
|
||
(<span class="hljs-number">18</span>, <span class="hljs-literal">True</span>)
|
||
<span class="hljs-meta">>>> </span>d.popitem()
|
||
(<span class="hljs-string">'name'</span>, <span class="hljs-string">'Ed'</span>)
|
||
<span class="hljs-meta">>>> </span>d.update({<span class="hljs-string">"name"</span>: <span class="hljs-string">"py"</span>})
|
||
<span class="hljs-meta">>>> </span>d
|
||
{<span class="hljs-string">'yr'</span>: <span class="hljs-number">20</span>, <span class="hljs-string">'name'</span>: <span class="hljs-string">'py'</span>}
|
||
<span class="hljs-meta">>>> </span>d.popitem()
|
||
(<span class="hljs-string">'name'</span>, <span class="hljs-string">'py'</span>)
|
||
<span class="hljs-meta">>>> </span>d.popitem()
|
||
(<span class="hljs-string">'yr'</span>, <span class="hljs-number">20</span>)
|
||
<span class="hljs-meta">>>> </span>d
|
||
{}
|
||
</code></pre>
|
||
<h2 id="dictionary-operations">Dictionary Operations<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#dictionary-operations">#</a></h2>
|
||
<h3 id="membership-3">Membership<a aria-hidden class="header-link" tabindex="-1" href="#membership-3">#</a>
|
||
</h3>
|
||
<p><code>in</code> keyword can be used to test the presence of a <code>key</code> in a dictionary.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-meta">>>> </span><span class="hljs-string">"yr"</span> <span class="hljs-keyword">in</span> d
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<p>Similarly, <code>not in</code> can be used to determine the absence of a <code>key</code>.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-string">"name"</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> d
|
||
<span class="hljs-literal">True</span>
|
||
</code></pre>
|
||
<h3 id="union">Union<a aria-hidden class="header-link" tabindex="-1" href="#union">#</a></h3>
|
||
<p>The <code>|</code> (union) operator can be used to merge two dictionaries.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-meta">>>> </span>n = {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Ed"</span>}
|
||
<span class="hljs-meta">>>> </span>d | n
|
||
{<span class="hljs-string">'yr'</span>: <span class="hljs-number">20</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>, <span class="hljs-string">'name'</span>: <span class="hljs-string">'Ed'</span>}
|
||
</code></pre>
|
||
<p>In case of common keys between the two operands (dictionaries), the values of the operand on the right
|
||
takes priority.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-meta">>>> </span>n = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">15</span>, <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ed"</span>}
|
||
<span class="hljs-meta">>>> </span>d | n
|
||
{<span class="hljs-string">'yr'</span>: <span class="hljs-number">15</span>, <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>, <span class="hljs-string">'name'</span>: <span class="hljs-string">'Ed'</span>}
|
||
</code></pre>
|
||
<p>In the above example, both <code>d</code> and <code>n</code> shared a common key <code>yr</code>. The
|
||
value corresponding to <code>yr</code> in <code>n</code> gets priority.</p>
|
||
<h2 id="traversing-a-dictionary">Traversing a Dictionary<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#traversing-a-dictionary">#</a></h2>
|
||
<p>Compared to position based indexing of <code>list</code> or <code>tuple</code>, dictionaries are indexed
|
||
based on the key.</p>
|
||
<h3 id="direct-traversal-2">Direct Traversal<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#direct-traversal-2">#</a></h3>
|
||
<p><code>for</code> loop can be used to directly iterate over the keys of a <code>dict</code>.</p>
|
||
<pre><code class="hljs language-python">d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ed"</span>,
|
||
<span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-keyword">for</span> key <span class="hljs-keyword">in</span> d:
|
||
<span class="hljs-built_in">print</span>(key,<span class="hljs-string">":"</span>, d[key])
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>yr : 20
|
||
name : Ed
|
||
18 : True
|
||
</code></pre>
|
||
<h3 id="traversing-using-dictionary-methods">Traversing Using Dictionary Methods<a aria-hidden
|
||
class="header-link" tabindex="-1" href="#traversing-using-dictionary-methods">#</a></h3>
|
||
<p>Dictionary methods <code>items()</code>, <code>keys()</code> and <code>values()</code> can be used to
|
||
fetch the items, keys and values in a dictionary, respectively.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ed"</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-meta">>>> </span>d.keys()
|
||
dict_keys([<span class="hljs-string">'yr'</span>, <span class="hljs-string">'name'</span>, <span class="hljs-number">18</span>])
|
||
<span class="hljs-meta">>>> </span>d.values()
|
||
dict_values([<span class="hljs-number">20</span>, <span class="hljs-string">'Ed'</span>, <span class="hljs-literal">True</span>])
|
||
<span class="hljs-meta">>>> </span>d.items()
|
||
dict_items([(<span class="hljs-string">'yr'</span>, <span class="hljs-number">20</span>), (<span class="hljs-string">'name'</span>, <span class="hljs-string">'Ed'</span>), (<span class="hljs-number">18</span>, <span class="hljs-literal">True</span>)])
|
||
</code></pre>
|
||
<p><code>dict_keys</code>, <code>dict_values</code> and <code>dict_items</code> are iterables that can be
|
||
used in a <code>for</code> statement to traverse the dictionary.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ed"</span>,
|
||
<span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-keyword">for</span> key <span class="hljs-keyword">in</span> d.keys():
|
||
<span class="hljs-built_in">print</span>(key)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>yr
|
||
name
|
||
18
|
||
</code></pre>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ed"</span>,
|
||
<span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-keyword">for</span> value <span class="hljs-keyword">in</span> d.values():
|
||
<span class="hljs-built_in">print</span>(value)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>20
|
||
Ed
|
||
True
|
||
</code></pre>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ed"</span>,
|
||
<span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-keyword">for</span> key, value <span class="hljs-keyword">in</span> d.items():
|
||
<span class="hljs-built_in">print</span>(key,<span class="hljs-string">":"</span>, value)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>yr : 20
|
||
name : Ed
|
||
18 : True
|
||
</code></pre>
|
||
<h2 id="built-in-functions-for-a-dictionary">Built-in Functions for a Dictionary<a aria-hidden
|
||
class="header-link" tabindex="-1" href="#built-in-functions-for-a-dictionary">#</a></h2>
|
||
<h3 id="number-of-items">Number of Items<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#number-of-items">#</a></h3>
|
||
<p><code>len()</code> can be used to fetch the number of items in the dictionary.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ed"</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-number">18</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">len</span>(d)
|
||
<span class="hljs-number">3</span>
|
||
</code></pre>
|
||
<h3 id="min-and-max">Min and Max<a aria-hidden class="header-link" tabindex="-1" href="#min-and-max">#</a>
|
||
</h3>
|
||
<p>The <code>min()</code> and <code>max()</code> built-in functions return the minimum and maximum value
|
||
among the keys of a dictionary.</p>
|
||
<p>In case of string keys, they return the first and last occurring strings alphabetically.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>d = {<span class="hljs-string">"yr"</span>: <span class="hljs-number">20</span>, <span class="hljs-string">"name"</span>: <span class="hljs-string">"Ed"</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-string">"is18"</span>: <span class="hljs-literal">True</span>}
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">min</span>(d)
|
||
<span class="hljs-string">'is18'</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">max</span>(d)
|
||
<span class="hljs-string">'yr'</span>
|
||
|
||
<span class="hljs-meta">>>> </span>d = {<span class="hljs-number">2</span>: <span class="hljs-string">"b"</span>, <span class="hljs-number">3</span>: <span class="hljs-string">"c"</span>, <span class="hljs-number">1</span>: <span class="hljs-string">"a"</span>}
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">min</span>(d)
|
||
<span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">max</span>(d)
|
||
<span class="hljs-number">3</span>
|
||
</code></pre>
|
||
<h2 id="creating-a-copy-of-a-dictionary">Creating a Copy of a Dictionary<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#creating-a-copy-of-a-dictionary">#</a></h2>
|
||
<p>A new copy of a dictionary can be made using <code>copy()</code> method:</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>old_d = {<span class="hljs-string">"a"</span>: <span class="hljs-number">1</span>, <span class="hljs-string">"b"</span>: <span class="hljs-number">2</span>}
|
||
<span class="hljs-meta">>>> </span>new_d = old_d.copy()
|
||
|
||
<span class="hljs-comment"># Checking if both dicts are </span>
|
||
<span class="hljs-comment"># pointing to the same object</span>
|
||
<span class="hljs-meta">>>> </span>new_d <span class="hljs-keyword">is</span> old_d
|
||
<span class="hljs-literal">False</span>
|
||
|
||
<span class="hljs-meta">>>> </span>new_d[<span class="hljs-string">"c"</span>] = <span class="hljs-number">3</span>
|
||
<span class="hljs-meta">>>> </span>new_d[<span class="hljs-string">"b"</span>] = <span class="hljs-number">4</span>
|
||
<span class="hljs-meta">>>> </span>new_d
|
||
{<span class="hljs-string">'a'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'b'</span>: <span class="hljs-number">4</span>, <span class="hljs-string">'c'</span>: <span class="hljs-number">3</span>}
|
||
<span class="hljs-meta">>>> </span>old_d
|
||
{<span class="hljs-string">'a'</span>: <span class="hljs-number">1</span>, <span class="hljs-string">'b'</span>: <span class="hljs-number">2</span>}
|
||
</code></pre>
|
||
<h2 id="nested-dictionary">Nested Dictionary<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#nested-dictionary">#</a></h2>
|
||
<p>When the value in a <code>key:value</code> pair of a dictionary is of type <code>dict</code>, it is known
|
||
as a nested dictionary.</p>
|
||
<p>In simple terms, it is a dictionary inside a dictionary.</p>
|
||
<p>Records of a table can be represented as a nested dict with primary key as the outer dict keys.</p>
|
||
<pre><code class="hljs language-python">d = { <span class="hljs-number">1</span>: {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Amar"</span>, <span class="hljs-string">"age"</span>: <span class="hljs-number">19</span>},
|
||
<span class="hljs-number">2</span>: {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Ria"</span>, <span class="hljs-string">"age"</span>: <span class="hljs-number">20</span>},
|
||
<span class="hljs-number">3</span>: {<span class="hljs-string">"name"</span>: <span class="hljs-string">"Rao"</span>, <span class="hljs-string">"age"</span>: <span class="hljs-number">18</span>}}
|
||
|
||
<span class="hljs-built_in">print</span>(d[<span class="hljs-number">1</span>])
|
||
<span class="hljs-built_in">print</span>(d[<span class="hljs-number">2</span>][<span class="hljs-string">"name"</span>])
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code class="hljs language-python">{<span class="hljs-string">'name'</span>: <span class="hljs-string">'Amar'</span>, <span class="hljs-string">'age'</span>: <span class="hljs-number">19</span>}
|
||
Ria
|
||
</code></pre>
|
||
<h2 id="sample-programs-1">Sample Programs<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#sample-programs-1">#</a></h2>
|
||
<h3 id="frequency-of-characters">Frequency of Characters<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#frequency-of-characters">#</a></h3>
|
||
<p>Write a program to count the number of times a character appears in a given string.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">d = {}
|
||
s = <span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter string: "</span>)
|
||
<span class="hljs-keyword">for</span> c <span class="hljs-keyword">in</span> s:
|
||
<span class="hljs-keyword">if</span> c <span class="hljs-keyword">in</span> d:
|
||
d[c] += <span class="hljs-number">1</span>
|
||
<span class="hljs-keyword">else</span>:
|
||
d[c] = <span class="hljs-number">1</span>
|
||
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Frequency of characters"</span>)
|
||
<span class="hljs-keyword">for</span> key <span class="hljs-keyword">in</span> d:
|
||
<span class="hljs-built_in">print</span>(key, <span class="hljs-string">"-"</span>, d[key])
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Enter string: pythondata
|
||
Frequency of characters
|
||
p - 1
|
||
y - 1
|
||
t - 2
|
||
h - 1
|
||
o - 1
|
||
n - 1
|
||
d - 1
|
||
a - 2
|
||
</code></pre>
|
||
<h3 id="salary-book">Salary Book<a aria-hidden class="header-link" tabindex="-1" href="#salary-book">#</a>
|
||
</h3>
|
||
<p>Write a program to enter employee names and their salaries as input and store them in a dictionary.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">n = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter number of employees: "</span>))
|
||
emp = <span class="hljs-built_in">dict</span>()
|
||
<span class="hljs-keyword">for</span> cnt <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(n):
|
||
name = <span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter employee name: "</span>)
|
||
salary = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter salary: "</span>))
|
||
emp[name] = salary
|
||
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Employee Name & Salary"</span>)
|
||
<span class="hljs-keyword">for</span> key <span class="hljs-keyword">in</span> emp:
|
||
<span class="hljs-built_in">print</span>(key, <span class="hljs-string">'-'</span>, emp[key])
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Enter number of employees: 3
|
||
Enter employee name: Anil Raj
|
||
Enter salary: 12000
|
||
Enter employee name: Dinesh Kumar
|
||
Enter salary: 15000
|
||
Enter employee name: Sam Singh
|
||
Enter salary: 10000
|
||
Employee Name & Salary
|
||
Anil Raj - 12000
|
||
Dinesh Kumar - 15000
|
||
Sam Singh - 10000
|
||
</code></pre>
|
||
<h1 id="python-standard-library">Python Standard Library<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#python-standard-library">#</a></h1>
|
||
<h2 id="built-in-functions">Built-in Functions<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#built-in-functions">#</a></h2>
|
||
<p>Python has a rich and extensive <strong>Standard Library</strong> which gives it an edge over traditional
|
||
programming languages.</p>
|
||
<p><strong>Python Standard Library</strong> contains 69 built-in functions that are commonly used by
|
||
programmers which saves a lot of time as they can be directly used in a program.</p>
|
||
<p>We have already used some functions in the previous sections like <code>input()</code>,
|
||
<code>output()</code>, <code>len()</code>, <code>sum()</code>, <code>min()</code>, <code>max()</code>,
|
||
<code>list()</code>, <code>dict()</code>, etc.
|
||
</p>
|
||
<p>Some of the widely used functions can be categorized as follows:</p>
|
||
<ul>
|
||
<li>Mathematical Functions</li>
|
||
<li>Type Functions</li>
|
||
<li>Input/Output Functions</li>
|
||
<li>Base/Unicode Functions</li>
|
||
</ul>
|
||
<h2 id="mathematical-functions">Mathematical Functions<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#mathematical-functions">#</a></h2>
|
||
<h3 id="abs">abs()<a aria-hidden class="header-link" tabindex="-1" href="#abs">#</a></h3>
|
||
<p><code>abs(x)</code> returns the absolute value or magnitude of <code>x</code> of type <code>int</code>,
|
||
<code>float</code> or <code>complex</code> number.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">abs</span>(-<span class="hljs-number">2.3</span>)
|
||
<span class="hljs-number">2.3</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">abs</span>(-<span class="hljs-number">10</span>)
|
||
<span class="hljs-number">10</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">abs</span>(<span class="hljs-number">2</span> + <span class="hljs-number">2j</span>)
|
||
<span class="hljs-number">2.8284271247461903</span>
|
||
</code></pre>
|
||
<h3 id="round">round()<a aria-hidden class="header-link" tabindex="-1" href="#round">#</a></h3>
|
||
<p><code>round(x [,ndigits])</code> rounds off <code>x</code> (<code>float</code>) to <code>ndigits</code>
|
||
precision after the decimal point.</p>
|
||
<p>In case <code>ndigits</code> is not provided, it rounds off to the nearest integer.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">round</span>(<span class="hljs-number">2.33462398</span>)
|
||
<span class="hljs-number">2</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">round</span>(<span class="hljs-number">2.33462398</span>, <span class="hljs-number">3</span>)
|
||
<span class="hljs-number">2.335</span>
|
||
</code></pre>
|
||
<h3 id="sum">sum()<a aria-hidden class="header-link" tabindex="-1" href="#sum">#</a></h3>
|
||
<p><code>sum(sequence [,start])</code> returns the sum of items in a <code>sequence</code> of type
|
||
<code>list</code>, <code>tuple</code>, <code>range</code> or <code>set</code>.
|
||
</p>
|
||
<p>If a second argument <code>start</code> is provided, it is added to the sum.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">sum</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, -<span class="hljs-number">1</span>])
|
||
<span class="hljs-number">2</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">sum</span>((<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, -<span class="hljs-number">1</span>))
|
||
<span class="hljs-number">2</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">sum</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, -<span class="hljs-number">1</span>], <span class="hljs-number">10</span>)
|
||
<span class="hljs-number">12</span>
|
||
</code></pre>
|
||
<h3 id="min">min()<a aria-hidden class="header-link" tabindex="-1" href="#min">#</a></h3>
|
||
<p><code>min(sequence)</code> returns the minimum value of items in a <code>sequence</code> of type
|
||
<code>list</code>, <code>tuple</code>, <code>range</code>, <code>str</code> or <code>set</code>.
|
||
</p>
|
||
<p>Apart from iterables, <code>min(arg1, arg2, ..)</code> also accepts multiple arguments <code>arg1</code>,
|
||
<code>arg2</code> .. of numeric type and returns the smallest among these arguments.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">min</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, -<span class="hljs-number">1</span>])
|
||
-<span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">min</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, -<span class="hljs-number">1</span>)
|
||
-<span class="hljs-number">1</span>
|
||
|
||
<span class="hljs-comment"># character with minimum</span>
|
||
<span class="hljs-comment"># ASCII value in a String</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">min</span>(<span class="hljs-string">"hello"</span>)
|
||
<span class="hljs-string">'e'</span>
|
||
</code></pre>
|
||
<h3 id="max">max()<a aria-hidden class="header-link" tabindex="-1" href="#max">#</a></h3>
|
||
<p><code>max(sequence)</code> returns the maximum value of items in a <code>sequence</code> of type
|
||
<code>list</code>, <code>tuple</code>, <code>range</code>, <code>str</code> or <code>set</code>.
|
||
</p>
|
||
<p>Apart from iterables, <code>max(arg1, arg2, ..)</code> also accepts multiple arguments <code>arg1</code>,
|
||
<code>arg2</code> .. of numeric type and returns the largest among these arguments.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">max</span>([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, -<span class="hljs-number">1</span>])
|
||
<span class="hljs-number">2</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">max</span>(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, -<span class="hljs-number">1</span>)
|
||
<span class="hljs-number">2</span>
|
||
|
||
<span class="hljs-comment"># character with maximum</span>
|
||
<span class="hljs-comment"># ASCII value in a String</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">max</span>(<span class="hljs-string">"hello"</span>)
|
||
<span class="hljs-string">'o'</span>
|
||
</code></pre>
|
||
<h3 id="pow">pow()<a aria-hidden class="header-link" tabindex="-1" href="#pow">#</a></h3>
|
||
<p><code>pow(base, exp [,mod])</code> raises a <code>base</code> (<code>int</code>, <code>float</code>) to
|
||
the power <code>exp</code> (<code>int</code>, <code>float</code>), i.e. <code>base**exp</code>.</p>
|
||
<p>If <code>mod</code> (<code>int</code>) is provided <code>(base**exp) % mod</code> is returned.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">pow</span>(<span class="hljs-number">3</span>, <span class="hljs-number">2</span>, <span class="hljs-number">7</span>)
|
||
<span class="hljs-number">2</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">pow</span>(<span class="hljs-number">1.4141</span>, <span class="hljs-number">2</span>)
|
||
<span class="hljs-number">1.9996788099999998</span>
|
||
</code></pre>
|
||
<h3 id="divmod">divmod()<a aria-hidden class="header-link" tabindex="-1" href="#divmod">#</a></h3>
|
||
<p><code>divmod(a, b)</code> returns a tuple <code>(a // b, a % b)</code> consisting of the quotient and
|
||
remainder when <code>a</code> (<code>int</code>, <code>float</code>) is divided by <code>b</code>
|
||
(<code>int</code>, <code>float</code>).</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">divmod</span>(<span class="hljs-number">23</span>, <span class="hljs-number">3.5</span>)
|
||
(<span class="hljs-number">6.0</span>, <span class="hljs-number">2.0</span>)
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">divmod</span>(-<span class="hljs-number">10</span>, <span class="hljs-number">7</span>)
|
||
(-<span class="hljs-number">2</span>, <span class="hljs-number">4</span>)
|
||
</code></pre>
|
||
<h2 id="type-functions">Type Functions<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#type-functions">#</a></h2>
|
||
<p>Python has built-in functions to handle various aspects of datatypes such as checking and conversion.</p>
|
||
<h3 id="type-checking-1">Type Checking<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#type-checking-1">#</a></h3>
|
||
<p><code>type()</code> and <code>isinstance()</code> builtin functions are used for checking the data type
|
||
of objects.</p>
|
||
<p>Check out the <strong>Type Checking</strong> section in the chapter <strong>Variable, Objects & Data
|
||
Types</strong> to learn more about it in detail.</p>
|
||
<h3 id="built-in-type-functions">Built-in Type Functions<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#built-in-type-functions">#</a></h3>
|
||
<p>We have previously discussed the various built-in data types available in Python.</p>
|
||
<p>The following functions are often used to assign a default value or create an empty collection when no
|
||
arguments are provided:</p>
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th>Function</th>
|
||
<th>Default Value</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr>
|
||
<td><code>bool()</code></td>
|
||
<td><code>False</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>int()</code></td>
|
||
<td><code>0</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>float()</code></td>
|
||
<td><code>0.0</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>complex()</code></td>
|
||
<td><code>0j</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>str()</code></td>
|
||
<td><code>''</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>list()</code></td>
|
||
<td><code>[]</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>tuple()</code></td>
|
||
<td><code>()</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>set()</code></td>
|
||
<td><code>set()</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>frozenset()</code></td>
|
||
<td><code>frozenset()</code></td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>dict()</code></td>
|
||
<td><code>{}</code></td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
<p>The <strong>Type Casting</strong> section of the chapter <strong>Variable, Objects & Data
|
||
Types</strong> covers these functions in detail in case any argument is passed.</p>
|
||
<h2 id="io-functions">I/O Functions<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#io-functions">#</a></h2>
|
||
<p>Python provides the following built-in functions to handle user input and result output:</p>
|
||
<h3 id="input">input()<a aria-hidden class="header-link" tabindex="-1" href="#input">#</a></h3>
|
||
<p><code>input()</code> function can be used to accept a user input and assign it to a variable.</p>
|
||
<p>When this function is encountered in the code, the python interpreter waits for the user to type a
|
||
response which is read as a string.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">name = <span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter name: "</span>)
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Hello,"</span>, name)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Enter name: Python
|
||
Hello, Python
|
||
</code></pre>
|
||
<h3 id="print">print()<a aria-hidden class="header-link" tabindex="-1" href="#print">#</a></h3>
|
||
<p>The built-in <code>print()</code> function can be used to display an output (value of variables,
|
||
expressions, etc.) on the standard output.</p>
|
||
<p>For example, the below code computes the area of a rectangle and displays it:</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">length = <span class="hljs-number">10</span>
|
||
breadth = <span class="hljs-number">5</span>
|
||
area = length * breadth
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"Area:"</span>, area)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Area: 50
|
||
</code></pre>
|
||
<p>Both, <code>input()</code> and <code>print()</code> functions are covered in detail in the chapter
|
||
<strong>Input & Output</strong>.
|
||
</p>
|
||
<h3 id="open">open()<a aria-hidden class="header-link" tabindex="-1" href="#open">#</a></h3>
|
||
<p><code>open()</code> function is used to open a file and return the corresponding file object.</p>
|
||
<p>This function supports various modes useful for reading from a file and writing to a file.</p>
|
||
<p>An example usage of <code>open()</code> function is shown below:</p>
|
||
<pre><code class="hljs language-python">f = <span class="hljs-built_in">open</span>(<span class="hljs-string">'data.txt'</span>, <span class="hljs-string">'r+'</span>)
|
||
<span class="hljs-comment"># f is the file object which </span>
|
||
<span class="hljs-comment"># can perform read and write</span>
|
||
<span class="hljs-comment"># operations on the file</span>
|
||
</code></pre>
|
||
<p>This function is covered in detail in the chapter <strong>File Handling</strong>.</p>
|
||
<h2 id="baseunicode-conversion-functions">Base/Unicode Conversion Functions<a aria-hidden
|
||
class="header-link" tabindex="-1" href="#baseunicode-conversion-functions">#</a></h2>
|
||
<h3 id="bin">bin()<a aria-hidden class="header-link" tabindex="-1" href="#bin">#</a></h3>
|
||
<p>Converts an <code>int</code> to a binary (base-2) string prefixed with <code>'0b'</code>.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">bin</span>(<span class="hljs-number">9</span>)
|
||
<span class="hljs-string">'0b1001'</span>
|
||
</code></pre>
|
||
<h3 id="oct">oct()<a aria-hidden class="header-link" tabindex="-1" href="#oct">#</a></h3>
|
||
<p>Converts an <code>int</code> to an octal (base-8) string prefixed with <code>'0o'</code>.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">oct</span>(<span class="hljs-number">9</span>)
|
||
<span class="hljs-string">'0o11'</span>
|
||
</code></pre>
|
||
<h3 id="hex">hex()<a aria-hidden class="header-link" tabindex="-1" href="#hex">#</a></h3>
|
||
<p>Converts an <code>int</code> to a lowercase hexadecimal (base-16) string prefixed with <code>"0x"</code>.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">hex</span>(<span class="hljs-number">29</span>)
|
||
<span class="hljs-string">'0x1d'</span>
|
||
</code></pre>
|
||
<h3 id="ord">ord()<a aria-hidden class="header-link" tabindex="-1" href="#ord">#</a></h3>
|
||
<p>Returns the integer Unicode code point for the given Unicode character <code>str</code>.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">ord</span>(<span class="hljs-string">"a"</span>)
|
||
<span class="hljs-number">97</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">ord</span>(<span class="hljs-string">"β"</span>)
|
||
<span class="hljs-number">946</span>
|
||
</code></pre>
|
||
<h3 id="chr">chr()<a aria-hidden class="header-link" tabindex="-1" href="#chr">#</a></h3>
|
||
<p>Converts the integer Unicode code point into the corresponding Unicode string.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-built_in">chr</span>(<span class="hljs-number">97</span>)
|
||
<span class="hljs-string">'a'</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">chr</span>(<span class="hljs-number">946</span>)
|
||
<span class="hljs-string">'β'</span>
|
||
</code></pre>
|
||
<h2 id="what-are-built-in-modules">What are Built-in Modules?<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#what-are-built-in-modules">#</a></h2>
|
||
<p>Apart from built-in functions, the <strong>Python Standard Library</strong> also contains a wide range of
|
||
built-in modules which are a group of functions organized based on functionality.</p>
|
||
<p>Some of the commonly used modules are mentioned below:</p>
|
||
<ul>
|
||
<li><code>math</code> - Mathematical functions</li>
|
||
<li><code>random</code> - Generate pseudo-random numbers</li>
|
||
<li><code>statistics</code> - Statistical functions</li>
|
||
</ul>
|
||
<p><strong>Accessing Modules</strong></p>
|
||
<p>A module can be accessed in a program using the <code>import</code> statement.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> math
|
||
</code></pre>
|
||
<p>The above <code>import</code> statement loads all the functions available in the <code>math</code>
|
||
module. To access any function in the module, simply type the module name followed by a period
|
||
(<code>.</code>), followed by the function name.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> math
|
||
<span class="hljs-meta">>>> </span>math.<span class="hljs-built_in">pow</span>(<span class="hljs-number">3</span>, <span class="hljs-number">2</span>)
|
||
<span class="hljs-number">9.0</span>
|
||
</code></pre>
|
||
<p>Instead of loading all the functions in a module, the <code>from</code> statement can be used to access
|
||
only specified functions.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> math <span class="hljs-keyword">import</span> <span class="hljs-built_in">pow</span>
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">pow</span>(<span class="hljs-number">3</span>, <span class="hljs-number">2</span>)
|
||
<span class="hljs-number">9.0</span>
|
||
</code></pre>
|
||
<h2 id="math-module">math Module<a aria-hidden class="header-link" tabindex="-1" href="#math-module">#</a>
|
||
</h2>
|
||
<p><code>math</code> module provides mathematical functions and constants as defined by the C standard.</p>
|
||
<h3 id="constants">Constants<a aria-hidden class="header-link" tabindex="-1" href="#constants">#</a></h3>
|
||
<p>The following frequently used mathematical constants are available in <code>math</code> module:</p>
|
||
<ul>
|
||
<li><code>pi</code> : <code>π = 3.141592…</code> (to available precision)</li>
|
||
<li><code>e</code> : <code>e = 2.718281…</code> (to available precision)</li>
|
||
<li><code>tau</code> : <code>τ = 2π = 6.283185…</code> (to available precision)</li>
|
||
</ul>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> math
|
||
<span class="hljs-meta">>>> </span>math.pi
|
||
<span class="hljs-number">3.141592653589793</span>
|
||
<span class="hljs-meta">>>> </span>math.e
|
||
<span class="hljs-number">2.718281828459045</span>
|
||
<span class="hljs-meta">>>> </span>math.tau
|
||
<span class="hljs-number">6.283185307179586</span>
|
||
</code></pre>
|
||
<h3 id="functions">Functions<a aria-hidden class="header-link" tabindex="-1" href="#functions">#</a></h3>
|
||
<p>Following useful mathematical functions are available in the <code>math</code> module:</p>
|
||
<p><strong>fabs()</strong></p>
|
||
<p><code>fabs(x)</code> returns the absolute value of <code>x</code>.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> math
|
||
<span class="hljs-meta">>>> </span>math.fabs(-<span class="hljs-number">3.24</span>)
|
||
<span class="hljs-number">3.24</span>
|
||
</code></pre>
|
||
<p><strong>gcd()</strong></p>
|
||
<p><code>gcd(a, b)</code> returns the greatest common divisor of integers <code>a</code> and <code>b</code>.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> math
|
||
<span class="hljs-meta">>>> </span>math.gcd(<span class="hljs-number">54</span>, <span class="hljs-number">24</span>)
|
||
<span class="hljs-number">6</span>
|
||
</code></pre>
|
||
<p><strong>ceil()</strong></p>
|
||
<p><code>ceil(x)</code> returns the smallest integer greater than or equal to <code>x</code>.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> math
|
||
<span class="hljs-meta">>>> </span>math.ceil(<span class="hljs-number">2.13</span>)
|
||
<span class="hljs-number">3</span>
|
||
</code></pre>
|
||
<p><strong>floor()</strong></p>
|
||
<p><code>floor(x)</code> returns the largest integer less than or equal to <code>x</code>.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> math
|
||
<span class="hljs-meta">>>> </span>math.floor(<span class="hljs-number">2.13</span>)
|
||
<span class="hljs-number">2</span>
|
||
</code></pre>
|
||
<p><strong>fmod()</strong></p>
|
||
<p><code>fmod(x, y)</code> returns the value of the expression <code>x - n*y</code> such that the result has
|
||
the same sign as <code>x</code> and magnitude less than <code>|y|</code> for some integer
|
||
<code>n</code>.
|
||
</p>
|
||
<p>This function should be preferred when working with floating point numbers as compared to
|
||
<code>x % y</code> that should be used when working with integers.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> math
|
||
<span class="hljs-meta">>>> </span>math.fmod(<span class="hljs-number">2.14</span>, <span class="hljs-number">0.5</span>)
|
||
<span class="hljs-number">0.14000000000000012</span>
|
||
<span class="hljs-meta">>>> </span>math.fmod(-<span class="hljs-number">2.14</span>, <span class="hljs-number">0.5</span>)
|
||
-<span class="hljs-number">0.14000000000000012</span>
|
||
</code></pre>
|
||
<p><strong>pow()</strong></p>
|
||
<p><code>pow(x, y)</code> raises <code>x</code> to the power of <code>y</code>.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> math
|
||
<span class="hljs-meta">>>> </span>math.<span class="hljs-built_in">pow</span>(<span class="hljs-number">5</span>, <span class="hljs-number">2</span>)
|
||
<span class="hljs-number">25.0</span>
|
||
</code></pre>
|
||
<p><strong>sqrt()</strong></p>
|
||
<p><code>sqrt(x)</code> returns the square root of <code>x</code>.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> math
|
||
<span class="hljs-meta">>>> </span>math.sqrt(<span class="hljs-number">25</span>)
|
||
<span class="hljs-number">5.0</span>
|
||
</code></pre>
|
||
<p><strong>sin(), cos() & tan()</strong></p>
|
||
<p><code>sin(x)</code>, <code>cos(x)</code> and <code>tan(x)</code> return the sine, cosine and tangent of
|
||
<code>x</code> (radians) respectively.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> math
|
||
<span class="hljs-meta">>>> </span>math.cos(math.pi/<span class="hljs-number">3</span>)
|
||
<span class="hljs-number">0.5000000000000001</span>
|
||
<span class="hljs-meta">>>> </span>math.sin(math.pi/<span class="hljs-number">2</span>)
|
||
<span class="hljs-number">1.0</span>
|
||
<span class="hljs-meta">>>> </span>math.tan(math.pi/<span class="hljs-number">4</span>)
|
||
<span class="hljs-number">0.9999999999999999</span>
|
||
</code></pre>
|
||
<p><strong>factorial()</strong></p>
|
||
<p><code>factorial(n)</code> computes the factorial of a positive integer <code>n</code> which is the
|
||
product of all positive integers less than or equal to
|
||
<code>n</code>.<br><code>n! = n×(n-1)×(n-2)...3×2×1</code>,<br>where <code>0! = 1</code>
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> math
|
||
<span class="hljs-meta">>>> </span>math.factorial(<span class="hljs-number">5</span>)
|
||
<span class="hljs-number">120</span>
|
||
</code></pre>
|
||
<h2 id="random-module">random Module<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#random-module">#</a></h2>
|
||
<p><code>random</code> module provides access to functions which can generate random numbers.</p>
|
||
<h3 id="random">random()<a aria-hidden class="header-link" tabindex="-1" href="#random">#</a></h3>
|
||
<p><code>random()</code> function draws a random float in the half open interval <code>[0.0, 1.0)</code>
|
||
with a uniform probability.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> random
|
||
<span class="hljs-meta">>>> </span>random.random()
|
||
<span class="hljs-number">0.6857133962949904</span>
|
||
</code></pre>
|
||
<h3 id="random-integer-from-range">Random Integer from Range<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#random-integer-from-range">#</a></h3>
|
||
<p><code>randrange(stop)</code> is used to randomly select an integer from a range <code>0</code> to
|
||
<code>stop</code> (excluding).
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> random
|
||
<span class="hljs-meta">>>> </span>random.randrange(<span class="hljs-number">10</span>)
|
||
<span class="hljs-number">5</span>
|
||
</code></pre>
|
||
<p><code>randrange(start, stop)</code> is used to randomly select an integer from a range <code>start</code>
|
||
to <code>stop</code> (excluding).</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> random
|
||
<span class="hljs-meta">>>> </span>random.randrange(<span class="hljs-number">5</span>, <span class="hljs-number">10</span>)
|
||
<span class="hljs-number">8</span>
|
||
</code></pre>
|
||
<p><code>randint(a, b)</code> is an alias for <code>randrange(a, b+1)</code>, provides an interface to
|
||
generate a random integer <code>N</code> such that <code>a <= N <= b</code> (includes
|
||
boundaries).</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> random
|
||
<span class="hljs-meta">>>> </span>random.randint(<span class="hljs-number">10</span>, <span class="hljs-number">20</span>)
|
||
<span class="hljs-number">12</span>
|
||
</code></pre>
|
||
<h2 id="statistics-module">statistics Module<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#statistics-module">#</a></h2>
|
||
<p><code>statistics</code> module provides functions that are useful for calculating mathematical statistics
|
||
of numeric (Real-valued) data.</p>
|
||
<h3 id="mean">Mean<a aria-hidden class="header-link" tabindex="-1" href="#mean">#</a></h3>
|
||
<p><code>mean(data)</code> returns the arithmetic mean or average value of <code>data</code>
|
||
(<code>list</code> or <code>tuple</code> of <code>int</code> or <code>float</code>).</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> statistics <span class="hljs-keyword">import</span> mean
|
||
<span class="hljs-meta">>>> </span>mean([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">6</span>])
|
||
<span class="hljs-number">3</span>
|
||
</code></pre>
|
||
<h3 id="median">Median<a aria-hidden class="header-link" tabindex="-1" href="#median">#</a></h3>
|
||
<p><code>median(data)</code> returns the median or middle value of <code>data</code> (<code>list</code> or
|
||
<code>tuple</code> of <code>int</code> or <code>float</code>) using the common "mean of middle two"
|
||
method.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> statistics <span class="hljs-keyword">import</span> median
|
||
<span class="hljs-meta">>>> </span>median([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">6</span>])
|
||
<span class="hljs-number">2.5</span>
|
||
</code></pre>
|
||
<h3 id="mode">Mode<a aria-hidden class="header-link" tabindex="-1" href="#mode">#</a></h3>
|
||
<p><code>mode(data)</code> returns the most commonly occurring value in the <code>data</code>
|
||
(<code>list</code> or <code>tuple</code> of <code>int</code>, <code>str</code> or <code>float</code>).
|
||
</p>
|
||
<p>If there are multiple modes with the same count, the first occurrence in the sequence is returned.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> statistics <span class="hljs-keyword">import</span> mode
|
||
<span class="hljs-meta">>>> </span>mode([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">6</span>])
|
||
<span class="hljs-number">1</span>
|
||
<span class="hljs-meta">>>> </span>mode([<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">6</span>])
|
||
<span class="hljs-number">2</span>
|
||
<span class="hljs-meta">>>> </span>mode([<span class="hljs-string">"a"</span>, <span class="hljs-string">"b"</span>, <span class="hljs-string">"a"</span>, <span class="hljs-string">"c"</span>])
|
||
<span class="hljs-string">'a'</span>
|
||
</code></pre>
|
||
<h1 id="file-handling">File Handling<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#file-handling">#</a></h1>
|
||
<h2 id="file-handling-in-python---introduction--overview">File Handling in Python - Introduction &
|
||
Overview<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#file-handling-in-python---introduction--overview">#</a></h2>
|
||
<p>So far we have written programs which accept input from the user via keyboard and display the generated
|
||
output on the standard output (console).</p>
|
||
<p>This activity has the following disadvantages:</p>
|
||
<ul>
|
||
<li>Feasible for small inputs, but cumbersome in case of large inputs.</li>
|
||
<li>The entire input has to be entered every time the program is executed.</li>
|
||
<li>The output generated is not saved for sharing or later use.</li>
|
||
</ul>
|
||
<p>Just like words can be written on a piece of paper, information can be stored on a computer disk as a
|
||
named location or a file.</p>
|
||
<p>Python comes with the in-built ability to interact with files. Through file handling, Python programs can
|
||
read a file to provide input data and output the results into a file for later use.</p>
|
||
<h2 id="text-files-vs-binary-files---use-case-file-formats-examples">Text Files vs Binary Files - Use Case,
|
||
File Formats, Examples<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#text-files-vs-binary-files---use-case-file-formats-examples">#</a></h2>
|
||
<p>Primarily, there are two types of files:</p>
|
||
<p><strong>Text File</strong></p>
|
||
<p>A text file is the simplest way to store information in a human readable text format (sequence of ASCII
|
||
or Unicode characters), which includes numeric values.</p>
|
||
<p>It is easy to view and modify the contents of a text file using any text editor like notepad or even
|
||
IDLE.</p>
|
||
<p>Even the python script is stored as a text file given by the extension <code>.py</code>.
|
||
<code>.txt</code> is the most popular extension used for a generic text file.
|
||
</p>
|
||
<p>Although text files do not have any structure, there are international standards defining some rules for
|
||
creating specialized text files like:</p>
|
||
<ul>
|
||
<li><code>.csv</code>, where each row is a set of comma separated values. This is the most popular data
|
||
exchange format.</li>
|
||
<li><code>.tsv</code>, similar to CSV but the values are separated by tabs instead of commas.</li>
|
||
<li><code>.xml</code> and <code>.json</code> are popular web data exchange formats.</li>
|
||
<li><code>.html</code> files are text files with contents written in the Hypertext Markup Language
|
||
designed to display contents in a web browser.</li>
|
||
</ul>
|
||
<p><strong>Binary File</strong></p>
|
||
<p>Although the contents of a text file is human readable, in reality this information is stored on the disk
|
||
in form of machine readable bytes (1s and 0s) one character at a time. This makes the format simple to
|
||
be operated by any application, but it is less efficient and consumes more memory (greater file size).
|
||
</p>
|
||
<p>In a binary file, the contents are also stored in form of bytes, but these bytes do not directly
|
||
translate into ASCII or Unicode characters.</p>
|
||
<p>Rather these bytes can represent anything like:</p>
|
||
<ul>
|
||
<li>Complex Data Structures</li>
|
||
<li>Image</li>
|
||
<li>Audio</li>
|
||
<li>Video</li>
|
||
</ul>
|
||
<p>and more.</p>
|
||
<p>As there is no simple rule to determine the basic unit of information, so opening a binary file in a text
|
||
editor will display garbage values and even a single bit of change can corrupt the entire file and make
|
||
it unreadable. Hence, specialized softwares are required to read and write binary files.</p>
|
||
<p>Python has a built-in <code>pickle</code> module which has implemented protocols to read and write binary
|
||
files having <code>.dat</code> or <code>.pickle</code> file extension. <code>pickle</code> is a Python
|
||
specific binary file format which can serialize any Python data structure (lists, dictionaries, etc) or
|
||
code object into a binary file. This byte-content of this file can then be de-serialized and used later
|
||
in any computer running Python.</p>
|
||
<h2 id="file-opening--closing">File Opening & Closing<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#file-opening--closing">#</a></h2>
|
||
<p>A text or binary file can be opened using the built-in <code>open(file_name, mode='r')</code> function.
|
||
</p>
|
||
<p>The parameters of the function are explained below:</p>
|
||
<p><strong><code>file_name</code></strong></p>
|
||
<p><code>file_name</code> is a required string parameter specifying the path of the file to be opened.</p>
|
||
<p>It can either be an absolute path or a relative path as shown below:</p>
|
||
<ul>
|
||
<li><code>'fname.txt'</code> is the relative path of a text file residing in the current working
|
||
directory from where the python script is being executed.</li>
|
||
<li><code>'../fname.txt'</code> is the relative path of a text file outside the current directory where
|
||
the python script is being executed.</li>
|
||
<li><code>'/Users/edpunk/Documents/fname.txt'</code> is the absolute path of a text file which can be
|
||
opened by the python script from any location as long as it is in the same system.</li>
|
||
</ul>
|
||
<p><strong><code>mode</code></strong></p>
|
||
<p><code>mode</code> is an optional string parameter which specifies the mode in which the file has to be
|
||
opened. It defaults to <code>'r'</code> which means open for reading in text mode.</p>
|
||
<p>The available modes are:</p>
|
||
<table>
|
||
<thead>
|
||
<tr>
|
||
<th><code>mode</code></th>
|
||
<th>purpose</th>
|
||
</tr>
|
||
</thead>
|
||
<tbody>
|
||
<tr>
|
||
<td><code>'r'</code></td>
|
||
<td>Opens the file for reading (default).</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>'t'</code></td>
|
||
<td>Opens the file in text mode (default).</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>'w'</code></td>
|
||
<td>Opens the file for writing, truncating (emptying) the file if it already exists.</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>'x'</code></td>
|
||
<td>Same as <code>'w'</code>, but it fails if the file already exists.</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>'a'</code></td>
|
||
<td>Opens the file for writing, where any new data is added at the end. It creates a new file if
|
||
the file does not exists.</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>'b'</code></td>
|
||
<td>Opens the file in binary mode.</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>'rb'</code></td>
|
||
<td>Opens the file in binary and read-only mode.</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>'wb'</code></td>
|
||
<td>Opens the file for writing in binary mode, truncating (emptying) the file if it already
|
||
exists.</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>'+'</code></td>
|
||
<td>Allows both read and write operations on a file.</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>'r+'</code></td>
|
||
<td>Opens the file in read and write mode. It throws an error in case the file does not exists.
|
||
If the file already exists, new data is overwritten on top of the existing data if the
|
||
position of stream is not moved to the end of the file.</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>'r+b'</code></td>
|
||
<td>Opens the file in binary read and write mode. It does not truncate the file if it already
|
||
exists.</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>'w+'</code></td>
|
||
<td>Opens the file in read and write mode. It creates a new file or truncates the contents of
|
||
the file if it already exists.</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>'w+b'</code></td>
|
||
<td>Opens the file in binary read and write mode. It creates a new file or truncates the
|
||
contents of the file if it already exists.</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>'a+'</code></td>
|
||
<td>Opens the file in read and append mode. It creates a new file if it does not exist. If the
|
||
file already exists, new data is automatically added at the end of the file after existing
|
||
data.</td>
|
||
</tr>
|
||
<tr>
|
||
<td><code>'a+b'</code></td>
|
||
<td>Opens the file in binary read and append mode.</td>
|
||
</tr>
|
||
</tbody>
|
||
</table>
|
||
<p>After opening a file and performing some file operations, it can be safely closed using the
|
||
<code>close()</code> method.
|
||
</p>
|
||
<p>For example, let us write a program to open a file <code>data.txt</code> in read and append mode and
|
||
close the file object in the successive statement.</p>
|
||
<pre><code class="hljs language-python">f = <span class="hljs-built_in">open</span>(<span class="hljs-string">'data.txt'</span>, <span class="hljs-string">'a+'</span>)
|
||
f.close()
|
||
</code></pre>
|
||
<h2 id="file-reading">File Reading<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#file-reading">#</a></h2>
|
||
<p>Opening a file using the <code>open()</code> function creates and returns a file object on which the
|
||
following activities can be performed:</p>
|
||
<h3 id="sequential-reading">Sequential Reading<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#sequential-reading">#</a></h3>
|
||
<p>The following three methods can be used on a file object to sequentially read the contents of a file:</p>
|
||
<h4 id="read">read()<a aria-hidden class="header-link" tabindex="-1" href="#read">#</a></h4>
|
||
<p><code>read(size = -1)</code> method is used to read <code>size</code> numbers of bytes of data from a
|
||
file at a time.</p>
|
||
<p>In case <code>size</code> is not specified, it reads and returns the entire content of the file.</p>
|
||
<p><strong>Example</strong></p>
|
||
<p>Let us consider a file named <code>info.txt</code> containing the below text:</p>
|
||
<pre><code>Hello World
|
||
Thank You
|
||
</code></pre>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>f = <span class="hljs-built_in">open</span>(<span class="hljs-string">'info.txt'</span>, <span class="hljs-string">'r'</span>)
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span>(f.read(<span class="hljs-number">3</span>))
|
||
Hel
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span>(f.read(<span class="hljs-number">4</span>))
|
||
lo W
|
||
<span class="hljs-meta">>>> </span>f.close()
|
||
|
||
<span class="hljs-meta">>>> </span>f = <span class="hljs-built_in">open</span>(<span class="hljs-string">'info.txt'</span>, <span class="hljs-string">'r'</span>)
|
||
<span class="hljs-meta">>>> </span><span class="hljs-built_in">print</span>(f.read())
|
||
Hello World
|
||
Thank You
|
||
<span class="hljs-meta">>>> </span>f.close()
|
||
</code></pre>
|
||
<h4 id="readline">readline()<a aria-hidden class="header-link" tabindex="-1" href="#readline">#</a></h4>
|
||
<p><code>readline(size = -1)</code> method without any arguments is used to read and return one line at a
|
||
time from the given file.</p>
|
||
<p>If <code>size</code> is specified, it returns at most <code>size</code> bytes of data or the data until
|
||
it encounters the newline character.</p>
|
||
<p><strong>Example</strong></p>
|
||
<p>Let us consider a file named <code>info.txt</code> containing the below text:</p>
|
||
<pre><code>Hello World
|
||
Thank You
|
||
</code></pre>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>f = <span class="hljs-built_in">open</span>(<span class="hljs-string">'info.txt'</span>, <span class="hljs-string">'r'</span>)
|
||
<span class="hljs-meta">>>> </span>f.readline(<span class="hljs-number">3</span>)
|
||
<span class="hljs-string">'Hel'</span>
|
||
|
||
<span class="hljs-comment"># Remaining data (byte size < 20) </span>
|
||
<span class="hljs-comment"># until it encounters newline</span>
|
||
<span class="hljs-meta">>>> </span>f.readline(<span class="hljs-number">20</span>)
|
||
<span class="hljs-string">'lo World\n'</span>
|
||
<span class="hljs-meta">>>> </span>f.close()
|
||
|
||
<span class="hljs-meta">>>> </span>f = <span class="hljs-built_in">open</span>(<span class="hljs-string">'info.txt'</span>, <span class="hljs-string">'r'</span>)
|
||
<span class="hljs-meta">>>> </span>f.readline()
|
||
<span class="hljs-string">'Hello World\n'</span>
|
||
<span class="hljs-meta">>>> </span>f.close()
|
||
</code></pre>
|
||
<p>Since <code>readline()</code> returns one row at a time, it can be used in a <code>while</code> statement
|
||
to iterate over the data row-wise. Once it reaches the end of file it returns an empty string.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">f = <span class="hljs-built_in">open</span>(<span class="hljs-string">'info.txt'</span>, <span class="hljs-string">'r'</span>)
|
||
line = f.readline()
|
||
<span class="hljs-keyword">while</span> line:
|
||
<span class="hljs-comment"># Removes newline</span>
|
||
<span class="hljs-comment"># character from the </span>
|
||
<span class="hljs-comment"># end of the line</span>
|
||
line = line.strip()
|
||
|
||
<span class="hljs-built_in">print</span>(line)
|
||
|
||
<span class="hljs-comment"># read the next line</span>
|
||
line = f.readline()
|
||
f.close()
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Hello World
|
||
Thank You
|
||
</code></pre>
|
||
<p><code>for</code> statement can also be used to traverse the file row-wise without any requirement of the
|
||
<code>readline()</code> method. Simply iterating over the file object returns the data one row at a
|
||
time.
|
||
</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">f = <span class="hljs-built_in">open</span>(<span class="hljs-string">'info.txt'</span>, <span class="hljs-string">'r'</span>)
|
||
<span class="hljs-keyword">for</span> line <span class="hljs-keyword">in</span> f:
|
||
<span class="hljs-comment"># Removes newline</span>
|
||
<span class="hljs-comment"># character from the </span>
|
||
<span class="hljs-comment"># end of the line</span>
|
||
line = line.strip()
|
||
<span class="hljs-built_in">print</span>(line)
|
||
f.close()
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>Hello World
|
||
Thank You
|
||
</code></pre>
|
||
<h4 id="readlines">readlines()<a aria-hidden class="header-link" tabindex="-1" href="#readlines">#</a></h4>
|
||
<p><code>readlines()</code> method returns a list of strings representing the lines (along with the newline
|
||
character) of text file content.</p>
|
||
<p><strong>Example</strong></p>
|
||
<p>Let us consider a file named <code>info.txt</code> containing the below text:</p>
|
||
<pre><code>Hello World
|
||
Thank You
|
||
</code></pre>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>f = <span class="hljs-built_in">open</span>(<span class="hljs-string">'info.txt'</span>, <span class="hljs-string">'r'</span>)
|
||
<span class="hljs-meta">>>> </span>f.readlines()
|
||
[<span class="hljs-string">'Hello World\n'</span>, <span class="hljs-string">'Thank You'</span>]
|
||
</code></pre>
|
||
<h3 id="ad-hoc-reading">Ad-hoc Reading<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#ad-hoc-reading">#</a></h3>
|
||
<p>The following two methods can be used on a file object to randomly access contents of a file:</p>
|
||
<h4 id="tell">tell()<a aria-hidden class="header-link" tabindex="-1" href="#tell">#</a></h4>
|
||
<p><code>tell()</code> returns the current byte position (integer) of the file object in the file.</p>
|
||
<p>Let us consider the same file <code>info.txt</code> for the below example:</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>f = <span class="hljs-built_in">open</span>(<span class="hljs-string">'info.txt'</span>, <span class="hljs-string">'r'</span>)
|
||
<span class="hljs-meta">>>> </span>f.read(<span class="hljs-number">4</span>)
|
||
<span class="hljs-string">'Hell'</span>
|
||
<span class="hljs-meta">>>> </span>f.tell()
|
||
<span class="hljs-number">4</span>
|
||
</code></pre>
|
||
<h4 id="seek">seek()<a aria-hidden class="header-link" tabindex="-1" href="#seek">#</a></h4>
|
||
<p><code>seek(offset, reference=0)</code> can be used to seek a location in the file object which is
|
||
<code>offset</code> bytes from the provided <code>reference</code>.
|
||
</p>
|
||
<p>The default value for <code>reference</code> is <code>0</code> which stands for the beginning of the
|
||
file. For this default <code>reference</code>, the <code>offset</code> has to be a whole number
|
||
(<code>>=0</code>).</p>
|
||
<p>Other allowed values of <code>reference</code> are:</p>
|
||
<ul>
|
||
<li><code>1</code>, which denotes that the offset will be calculated from the current position of the
|
||
file object (<code>offset</code> can be positive or negative)</li>
|
||
<li><code>2</code>, which denotes that the offset is calculated from the end of the file
|
||
(<code>offset</code> is negative)</li>
|
||
</ul>
|
||
<p><strong>Note</strong>: In text files (those opened without a <code>b</code> in the mode string), only
|
||
seek relative to the beginning of the file (<code>reference = 0</code>) is allowed.
|
||
<code>reference = 1 or 2</code> is only valid when the file is opened in binary mode.
|
||
</p>
|
||
<p>Let us consider the same file <code>info.txt</code> for the below example:</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>f.seek(<span class="hljs-number">6</span>)
|
||
<span class="hljs-number">6</span>
|
||
|
||
<span class="hljs-comment"># Hello World\nThank You</span>
|
||
<span class="hljs-comment"># ^</span>
|
||
<span class="hljs-comment"># Position of file pointer</span>
|
||
<span class="hljs-comment"># after seek.</span>
|
||
|
||
<span class="hljs-meta">>>> </span>f.read()
|
||
<span class="hljs-string">'World\nThank You'</span>
|
||
<span class="hljs-meta">>>> </span>f.tell()
|
||
<span class="hljs-number">21</span>
|
||
|
||
<span class="hljs-meta">>>> </span>f.seek(<span class="hljs-number">12</span>)
|
||
<span class="hljs-number">12</span>
|
||
|
||
<span class="hljs-comment"># Hello World\nThank You</span>
|
||
<span class="hljs-comment"># ^</span>
|
||
<span class="hljs-comment"># Position of file pointer</span>
|
||
<span class="hljs-comment"># after seek.</span>
|
||
|
||
<span class="hljs-meta">>>> </span>f.read()
|
||
<span class="hljs-string">'Thank You'</span>
|
||
</code></pre>
|
||
<h2 id="writing-a-file">Writing a File<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#writing-a-file">#</a></h2>
|
||
<p>The following modes support file writing:</p>
|
||
<ul>
|
||
<li>Writing from the beginning of a file : <code>r+</code>, <code>r+b</code>, <code>w</code>,
|
||
<code>x</code>, <code>wb</code>, <code>w+</code>, <code>w+b</code>.
|
||
</li>
|
||
<li>Appending at the end of an existing file : <code>a</code>, <code>ab</code>, <code>a+</code>,
|
||
<code>a+b</code>.
|
||
</li>
|
||
</ul>
|
||
<p>The following methods can be used to write data in a file:</p>
|
||
<h4 id="write">write()<a aria-hidden class="header-link" tabindex="-1" href="#write">#</a></h4>
|
||
<p><code>write(s)</code> method is useful for writing a string <code>s</code> into a file.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>s = <span class="hljs-string">"Hi World\nThank You"</span>
|
||
<span class="hljs-meta">>>> </span>f = <span class="hljs-built_in">open</span>(<span class="hljs-string">"info.txt"</span>, <span class="hljs-string">"w"</span>)
|
||
<span class="hljs-meta">>>> </span>f.write(s)
|
||
<span class="hljs-number">21</span>
|
||
<span class="hljs-comment"># Number of characters written</span>
|
||
|
||
<span class="hljs-meta">>>> </span>f.close()
|
||
</code></pre>
|
||
<p>Now, on opening <code>info.txt</code> using a text editor, the following content is displayed.</p>
|
||
<pre><code>Hi World
|
||
Thank You
|
||
</code></pre>
|
||
<h4 id="writelines">writelines()<a aria-hidden class="header-link" tabindex="-1" href="#writelines">#</a>
|
||
</h4>
|
||
<p><code>writelines(lines)</code> method writes a list of strings into a file.</p>
|
||
<p>This method does not add the line separator (newline character <code>\n</code>), so they should be
|
||
present at the end of each string.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>lines = [<span class="hljs-string">"Hi World\n"</span>,
|
||
<span class="hljs-meta">... </span> <span class="hljs-string">"Thank You\n"</span>]
|
||
<span class="hljs-meta">>>> </span>f = <span class="hljs-built_in">open</span>(<span class="hljs-string">"info.txt"</span>, <span class="hljs-string">"w"</span>)
|
||
<span class="hljs-meta">>>> </span>f.writelines(lines)
|
||
<span class="hljs-meta">>>> </span>f.close()
|
||
</code></pre>
|
||
<p>Now, on opening <code>info.txt</code> using a text editor, the following content is displayed.</p>
|
||
<pre><code>Hi World
|
||
Thank You
|
||
|
||
</code></pre>
|
||
<p>Note the empty line at the end which is added due to the <code>\n</code> at the end of the last string.
|
||
</p>
|
||
<h2 id="reading--writing-binary-files-using-pickle-module">Reading & Writing Binary Files using
|
||
<code>pickle</code> Module<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#reading--writing-binary-files-using-pickle-module">#</a>
|
||
</h2>
|
||
<p>In Python, the protocols to read and write binary files (<code>.dat</code> or <code>.pickle</code> file
|
||
extension) have been implemented in the built-in <code>pickle</code> module.</p>
|
||
<p><code>pickle</code> is a Python specific binary file format which can not only be used to store binary
|
||
data, but also store any Python object.</p>
|
||
<p>This process of translating data structures (lists, dictionaries, etc.) and code objects (classes,
|
||
functions, etc.) into bytes that can be stored in a binary file is known as
|
||
<strong>Serialization</strong>. This binary file can be stored on disk or shared and it can be
|
||
de-serialized and used later via Python.
|
||
</p>
|
||
<h3 id="dumping-data">Dumping Data<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#dumping-data">#</a></h3>
|
||
<p>The <code>dump()</code> function can be used to write the pickled representation of any data or object
|
||
into a file.</p>
|
||
<p><strong>Syntax</strong>: <code>pickle.dump(obj,file)</code></p>
|
||
<p>where:</p>
|
||
<ul>
|
||
<li><code>obj</code> is the object to be written</li>
|
||
<li><code>file</code> is an open file object (opened in binary write <code>wb</code> or append
|
||
<code>ab</code> mode).
|
||
</li>
|
||
</ul>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> pickle
|
||
<span class="hljs-meta">>>> </span>l = [[<span class="hljs-string">"Anita"</span>,<span class="hljs-string">"Maths"</span>,<span class="hljs-number">83</span>],
|
||
<span class="hljs-meta">... </span> [<span class="hljs-string">"Amar"</span>,<span class="hljs-string">"Maths"</span>,<span class="hljs-number">95</span>],
|
||
<span class="hljs-meta">... </span> [<span class="hljs-string">"Ani"</span>,<span class="hljs-string">"Maths"</span>,<span class="hljs-number">90</span>]]
|
||
<span class="hljs-meta">>>> </span>f = <span class="hljs-built_in">open</span>(<span class="hljs-string">"marks.dat"</span>, <span class="hljs-string">"wb"</span>)
|
||
<span class="hljs-meta">>>> </span>pickle.dump(l, f)
|
||
<span class="hljs-meta">>>> </span>f.close()
|
||
</code></pre>
|
||
<h3 id="loading-data">Loading Data<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#loading-data">#</a></h3>
|
||
<p>The <code>load()</code> function can be used to read the pickled representation of an object or data from
|
||
a file.</p>
|
||
<p><strong>Syntax</strong>: <code>pickle.load(file)</code></p>
|
||
<p>where <code>file</code> is an open file object (opened in binary read mode <code>rb</code>).</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">import</span> pickle
|
||
<span class="hljs-meta">>>> </span>f = <span class="hljs-built_in">open</span>(<span class="hljs-string">"marks.dat"</span>, <span class="hljs-string">"rb"</span>)
|
||
<span class="hljs-meta">>>> </span>l = pickle.load(f)
|
||
<span class="hljs-meta">>>> </span>f.close()
|
||
<span class="hljs-meta">>>> </span>l
|
||
[[<span class="hljs-string">'Anita'</span>, <span class="hljs-string">'Maths'</span>, <span class="hljs-number">83</span>], [<span class="hljs-string">'Amar'</span>, <span class="hljs-string">'Maths'</span>, <span class="hljs-number">95</span>], [<span class="hljs-string">'Ani'</span>, <span class="hljs-string">'Maths'</span>, <span class="hljs-number">90</span>]]
|
||
</code></pre>
|
||
<h3 id="example-traversing-a-binary-file">Example: Traversing a Binary File<a aria-hidden
|
||
class="header-link" tabindex="-1" href="#example-traversing-a-binary-file">#</a></h3>
|
||
<p>Write a program which performs the following Record Keeping activities:</p>
|
||
<ul>
|
||
<li>Accept some student marks as input and write the data in a binary file</li>
|
||
<li>read all data from the file</li>
|
||
<li>add some more data to the file</li>
|
||
<li>show the entire contents of the file</li>
|
||
</ul>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> pickle
|
||
|
||
<span class="hljs-comment"># Open file in binary write mode</span>
|
||
f = <span class="hljs-built_in">open</span>(<span class="hljs-string">"marks.dat"</span>, <span class="hljs-string">"wb"</span>)
|
||
|
||
<span class="hljs-comment"># Enter student marks data</span>
|
||
flag = <span class="hljs-number">1</span>
|
||
<span class="hljs-keyword">while</span> flag != <span class="hljs-number">0</span>:
|
||
name = <span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter student name: "</span>)
|
||
subject = <span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter subject: "</span>)
|
||
marks = <span class="hljs-built_in">float</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter marks: "</span>))
|
||
rec = [name, subject, marks]
|
||
pickle.dump(rec, f)
|
||
flag = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter 1 to add more or 0 to terminate: "</span>))
|
||
f.close()
|
||
|
||
<span class="hljs-comment"># read contents of file and display</span>
|
||
f = <span class="hljs-built_in">open</span>(<span class="hljs-string">"marks.dat"</span>, <span class="hljs-string">"rb"</span>)
|
||
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"File contents:"</span>)
|
||
|
||
<span class="hljs-comment"># Iteratively read all pickle objects written </span>
|
||
<span class="hljs-comment"># in the file until the end of fie is reached</span>
|
||
<span class="hljs-keyword">try</span>:
|
||
<span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
|
||
rec = pickle.load(f)
|
||
<span class="hljs-built_in">print</span>(rec)
|
||
<span class="hljs-keyword">except</span> EOFError:
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"End of file reached"</span>)
|
||
f.close()
|
||
|
||
<span class="hljs-comment"># Add more data</span>
|
||
f = <span class="hljs-built_in">open</span>(<span class="hljs-string">"marks.dat"</span>, <span class="hljs-string">"ab"</span>)
|
||
flag = <span class="hljs-number">1</span>
|
||
<span class="hljs-keyword">while</span> flag != <span class="hljs-number">0</span>:
|
||
name = <span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter student name: "</span>)
|
||
subject = <span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter subject: "</span>)
|
||
marks = <span class="hljs-built_in">float</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter marks: "</span>))
|
||
rec = [name, subject, marks]
|
||
pickle.dump(rec, f)
|
||
flag = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter 1 to add more or 0 to terminate: "</span>))
|
||
f.close()
|
||
|
||
<span class="hljs-comment"># show all contents</span>
|
||
f = <span class="hljs-built_in">open</span>(<span class="hljs-string">"marks.dat"</span>, <span class="hljs-string">"rb"</span>)
|
||
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"File contents after appending:"</span>)
|
||
<span class="hljs-keyword">try</span>:
|
||
<span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
|
||
rec = pickle.load(f)
|
||
<span class="hljs-built_in">print</span>(rec)
|
||
<span class="hljs-keyword">except</span> EOFError:
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"End of file reached"</span>)
|
||
f.close()
|
||
</code></pre>
|
||
<p><strong>Input/Output</strong></p>
|
||
<pre><code>Enter student name: Anita
|
||
Enter subject: Maths
|
||
Enter marks: 83
|
||
Enter 1 to add more or 0 to terminate: 1
|
||
Enter student name: Amar
|
||
Enter subject: Maths
|
||
Enter marks: 95
|
||
Enter 1 to add more or 0 to terminate: 0
|
||
File contents:
|
||
['Anita', 'Maths', 83.0]
|
||
['Amar', 'Maths', 95.0]
|
||
End of file reached
|
||
Enter student name: Akash
|
||
Enter subject: Science
|
||
Enter marks: 92
|
||
Enter 1 to add more or 0 to terminate: 1
|
||
Enter student name: Ira
|
||
Enter subject: Science
|
||
Enter marks: 99
|
||
Enter 1 to add more or 0 to terminate: 0
|
||
File contents after appending:
|
||
['Anita', 'Maths', 83.0]
|
||
['Amar', 'Maths', 95.0]
|
||
['Akash', 'Science', 92.0]
|
||
['Ira', 'Science', 99.0]
|
||
End of file reached
|
||
</code></pre>
|
||
<h2 id="reading--writing-a-csv-file-using-csv-module">Reading & Writing a CSV File using
|
||
<code>csv</code> Module<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#reading--writing-a-csv-file-using-csv-module">#</a>
|
||
</h2>
|
||
<p>Comma-separated value (CSV) file format is one of the most common data serialization and exchange format
|
||
where each row is a set of values separated by a delimiter.</p>
|
||
<p>The main rules for creating a CSV file are:</p>
|
||
<ul>
|
||
<li>Each field is separated by a delimiter. Comma (<code>,</code>) is the default delimiter used in CSV
|
||
files, but other delimiters (<code>;</code>, <code>\t</code>, <code>|</code>, etc.) can also be
|
||
used.</li>
|
||
<li>If any field value contains a delimiter, it must be surrounded by a pair of quote characters
|
||
(usually double-quotes character <code>"</code> ).</li>
|
||
<li>There is an optional single header line which contains the names of the fields.</li>
|
||
</ul>
|
||
<p>An example CSV file containing the marks data is given below:</p>
|
||
<pre><code>Name,Subject,Marks
|
||
Anita,Maths,83.0
|
||
Amar,Maths,95.0
|
||
Akash,Science,92.0
|
||
Ira,Science,99.0
|
||
</code></pre>
|
||
<p>To demonstrate why quote characters are required, let us have a look at the below contents of a CSV file
|
||
which contains the average marks of some subjects (separated by comma) for each student.</p>
|
||
<pre><code>Name,Average Of,Marks
|
||
Anita,"Accounting,Maths",83.0
|
||
Amar,"Accounting,Maths",95.0
|
||
Akash,"Physics,Chemistry,Biology",92.0
|
||
Ira,"Physics,Chemistry,Biology",99.0
|
||
</code></pre>
|
||
<p>Python has built-in <code>csv</code> module which provides utilities to read and write CSV files.</p>
|
||
<h3 id="reading-csv-file">Reading CSV File<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#reading-csv-file">#</a></h3>
|
||
<p><code>csv.reader(csvfile, delimiter=',', quotechar='"')</code> function is used to return the reader
|
||
object which iterates over CSV file line-by-line and returns it as a list of strings.</p>
|
||
<p>The <code>csvfile</code> file object should be opened with <code>newline=''</code> argument as the
|
||
<code>csv</code> module has its own newline handling which correctly interprets the newlines depending
|
||
on platform or in case they are embedded inside quoted fields.
|
||
</p>
|
||
<p><strong>Example #1</strong></p>
|
||
<p>Let us write a program to read the contents of <code>marks.csv</code>.</p>
|
||
<p><strong>marks.csv</strong></p>
|
||
<pre><code>Name,Subject,Marks
|
||
Anita,Maths,83.0
|
||
Amar,Maths,95.0
|
||
Akash,Science,92.0
|
||
Ira,Science,99.0
|
||
</code></pre>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> csv
|
||
<span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(<span class="hljs-string">'marks.csv'</span>,
|
||
newline=<span class="hljs-string">''</span>) <span class="hljs-keyword">as</span> f:
|
||
reader = csv.reader(f)
|
||
<span class="hljs-keyword">for</span> row <span class="hljs-keyword">in</span> reader:
|
||
<span class="hljs-built_in">print</span>(row)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>['Name', 'Subject', 'Marks']
|
||
['Anita', 'Maths', '83.0']
|
||
['Amar', 'Maths', '95.0']
|
||
['Akash', 'Science', '92.0']
|
||
['Ira', 'Science', '99.0']
|
||
</code></pre>
|
||
<p><strong>Example #2</strong></p>
|
||
<p>Let us write a program to read the contents of <code>marks2.csv</code>.</p>
|
||
<p>Note the change in delimiter & quote character.</p>
|
||
<p><strong>marks2.csv</strong></p>
|
||
<pre><code>Name|Average Of|Marks
|
||
Anita|^Accounting|Maths^|83.0
|
||
Amar|^Accounting|Maths^|95.0
|
||
Akash|^Physics|Chemistry|Biology^|92.0
|
||
Ira|^Physics|Chemistry|Biology^|99.0
|
||
</code></pre>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> csv
|
||
<span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(<span class="hljs-string">'marks2.csv'</span>,
|
||
newline=<span class="hljs-string">''</span>) <span class="hljs-keyword">as</span> f:
|
||
reader = csv.reader(f,
|
||
delimiter=<span class="hljs-string">'|'</span>,
|
||
quotechar=<span class="hljs-string">'^'</span>)
|
||
<span class="hljs-keyword">for</span> row <span class="hljs-keyword">in</span> reader:
|
||
<span class="hljs-built_in">print</span>(row)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>['Name', 'Average Of', 'Marks']
|
||
['Anita', 'Accounting|Maths', '83.0']
|
||
['Amar', 'Accounting|Maths', '95.0']
|
||
['Akash', 'Physics|Chemistry|Biology', '92.0']
|
||
['Ira', 'Physics|Chemistry|Biology', '99.0']
|
||
</code></pre>
|
||
<h3 id="writing-csv-file">Writing CSV File<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#writing-csv-file">#</a></h3>
|
||
<p><code>csv.writer(csvfile, delimiter=',', quotechar='"')</code> function returns a writer object which
|
||
converts data in form of a list into delimited strings which is passed down to the file object for
|
||
writing.</p>
|
||
<p>All non-string data in the list are automatically converted into string before it is written.</p>
|
||
<p>The methods <code>writerow(row)</code> or <code>writerows(rows)</code> can be used to write a row (list
|
||
of strings) or list of rows to a CSV file.</p>
|
||
<p><strong>Example #3</strong></p>
|
||
<p>Write a program to create a CSV file containing subject-wise marks of students delimited by semi-colon
|
||
(<code>;</code>).</p>
|
||
<p><strong>Solution #1: Using writerow()</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> csv
|
||
|
||
h = [<span class="hljs-string">"Name"</span>,<span class="hljs-string">"Subject"</span>,<span class="hljs-string">"Marks"</span>]
|
||
|
||
marks = [[<span class="hljs-string">"Anita"</span>,<span class="hljs-string">"Maths"</span>,<span class="hljs-number">83.0</span>],
|
||
[<span class="hljs-string">"Amar"</span>,<span class="hljs-string">"Maths"</span>,<span class="hljs-number">95.0</span>],
|
||
[<span class="hljs-string">"Akash"</span>,<span class="hljs-string">"Science"</span>,<span class="hljs-number">92.0</span>],
|
||
[<span class="hljs-string">"Ira"</span>,<span class="hljs-string">"Science"</span>,<span class="hljs-number">99.0</span>]]
|
||
|
||
<span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(<span class="hljs-string">'marks.csv'</span>, <span class="hljs-string">'w'</span>,
|
||
newline=<span class="hljs-string">''</span>) <span class="hljs-keyword">as</span> f:
|
||
writer = csv.writer(f,
|
||
delimiter=<span class="hljs-string">';'</span>)
|
||
|
||
<span class="hljs-comment"># Writing header</span>
|
||
writer.writerow(h)
|
||
|
||
<span class="hljs-comment">#Writing Data</span>
|
||
<span class="hljs-keyword">for</span> row <span class="hljs-keyword">in</span> marks:
|
||
writer.writerow(row)
|
||
</code></pre>
|
||
<p><strong>Solution #2: Using writerows()</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> csv
|
||
|
||
h = [<span class="hljs-string">"Name"</span>,<span class="hljs-string">"Subject"</span>,<span class="hljs-string">"Marks"</span>]
|
||
|
||
marks = [[<span class="hljs-string">"Anita"</span>,<span class="hljs-string">"Maths"</span>,<span class="hljs-number">83.0</span>],
|
||
[<span class="hljs-string">"Amar"</span>,<span class="hljs-string">"Maths"</span>,<span class="hljs-number">95.0</span>],
|
||
[<span class="hljs-string">"Akash"</span>,<span class="hljs-string">"Science"</span>,<span class="hljs-number">92.0</span>],
|
||
[<span class="hljs-string">"Ira"</span>,<span class="hljs-string">"Science"</span>,<span class="hljs-number">99.0</span>]]
|
||
|
||
<span class="hljs-keyword">with</span> <span class="hljs-built_in">open</span>(<span class="hljs-string">'marks.csv'</span>, <span class="hljs-string">'w'</span>,
|
||
newline=<span class="hljs-string">''</span>) <span class="hljs-keyword">as</span> f:
|
||
writer = csv.writer(f,
|
||
delimiter=<span class="hljs-string">';'</span>)
|
||
|
||
<span class="hljs-comment"># Writing header</span>
|
||
writer.writerow(h)
|
||
|
||
<span class="hljs-comment">#Writing Data</span>
|
||
writer.writerows(marks)
|
||
</code></pre>
|
||
<p><strong>Output</strong> - marks.csv</p>
|
||
<pre><code>Name;Subject;Marks
|
||
Anita;Maths;83.0
|
||
Amar;Maths;95.0
|
||
Akash;Science;92.0
|
||
Ira;Science;99.0
|
||
</code></pre>
|
||
<h1 id="user-defined-functions-modules--packages">User Defined Functions, Modules & Packages<a
|
||
aria-hidden class="header-link" tabindex="-1" href="#user-defined-functions-modules--packages">#</a>
|
||
</h1>
|
||
<h2 id="user-defined-functions">User Defined Functions<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#user-defined-functions">#</a></h2>
|
||
<p>The built-in functions and modules of the Python Standard Library add tremendous value by performing
|
||
generic operations and can be utilised by developers for any task.</p>
|
||
<p>But, at times a programmer needs to perform a set of operations for a specific task multiple times. In
|
||
such cases instead of rewriting the statements again and again, the block of code can be wrapped into a
|
||
function which can be called anytime in the scope of the program.</p>
|
||
<p><strong>User-defined functions</strong> make the program more:</p>
|
||
<ul>
|
||
<li><strong>Organized</strong>, as a block of code is now replaced by a single function call which
|
||
performs a specific task.</li>
|
||
<li><strong>Manageable</strong>, due to reduction of code length.</li>
|
||
<li><strong>Reusable</strong>, as the user defined function can be used anywhere in the current program
|
||
or it can also be imported in another program.</li>
|
||
</ul>
|
||
<h2 id="function-structure">Function Structure<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#function-structure">#</a></h2>
|
||
<p>Let us take a deep dive into a user defined function (provided below) and understand its various
|
||
components:</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">adder</span>(<span class="hljs-params">f, s, t = <span class="hljs-literal">None</span></span>):
|
||
<span class="hljs-string">"""
|
||
Returns the sum of f, s and t.
|
||
If t is not provided,
|
||
return the sum of f and s.
|
||
"""</span>
|
||
s = f + s
|
||
<span class="hljs-keyword">if</span> t:
|
||
s += t
|
||
<span class="hljs-keyword">return</span> s
|
||
</code></pre>
|
||
<h3 id="function-header">Function Header<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#function-header">#</a></h3>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">adder</span>(<span class="hljs-params">f, s, t = <span class="hljs-literal">None</span></span>):
|
||
</code></pre>
|
||
<p>The function header begins with the keyword <code>def</code>.</p>
|
||
<p>The function name follows the <code>def</code> keyword. As it is an identifier, the same nomenclature is
|
||
followed while naming it. <code>adder</code> is the name of the function in the above example.</p>
|
||
<p>The function name is followed by a pair of parenthesis <code>( )</code>.</p>
|
||
<p>In case any parameters are required by the function, they are enclosed inside the parentheses.
|
||
<code>f, s, t = None</code> are the three parameters of the function.
|
||
</p>
|
||
<p>Finally, the function header ends with a colon.</p>
|
||
<h3 id="function-body">Function Body<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#function-body">#</a></h3>
|
||
<p>The body of the function consists of one or more Python statements which have the same amount of
|
||
indentation (4 spaces) from the function header.</p>
|
||
<p>It is a good practice to include the documentation string at the beginning of the function body that
|
||
briefly explains how it works. This docstring can either be a single-line or a multiline string literal.
|
||
In the above example the docstring is:</p>
|
||
<pre><code class="hljs language-python"> <span class="hljs-string">"""
|
||
Returns the sum of f, s and t.
|
||
If t is not provided,
|
||
return the sum of f and s.
|
||
"""</span>
|
||
</code></pre>
|
||
<p>This docstring is followed by a series of statements which represent the set of instructions to be
|
||
executed. The set of instructions in the above example are</p>
|
||
<pre><code class="hljs language-python"> s = f + s
|
||
<span class="hljs-keyword">if</span> t:
|
||
s += t
|
||
</code></pre>
|
||
<p>The code block finally ends with a <code>return</code> statement which returns one or more values.</p>
|
||
<pre><code class="hljs language-python"> <span class="hljs-keyword">return</span> s
|
||
</code></pre>
|
||
<p>In the above example the value of <code>s</code> is returned which is the sum.</p>
|
||
<p>A missing <code>return</code> statement or a <code>return</code> statement returning no value implies
|
||
that the function returns <code>None</code>. These functions are known as void functions which display
|
||
the result of statements via <code>print()</code> function.</p>
|
||
<h2 id="parameters-and-arguments">Parameters and Arguments<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#parameters-and-arguments">#</a></h2>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">adder</span>(<span class="hljs-params">f, s, t = <span class="hljs-literal">None</span></span>):
|
||
<span class="hljs-string">"""
|
||
Returns the sum of f, s and t.
|
||
If t is not provided,
|
||
return the sum of f and s.
|
||
"""</span>
|
||
s = f + s
|
||
<span class="hljs-keyword">if</span> t:
|
||
s += t
|
||
<span class="hljs-keyword">return</span> s
|
||
</code></pre>
|
||
<p>After defining the above function, let us now invoke or call the function:</p>
|
||
<pre><code class="hljs language-python">fst = <span class="hljs-number">20</span>
|
||
snd = <span class="hljs-number">10</span>
|
||
trd = <span class="hljs-number">10</span>
|
||
sm1 = adder(fst, snd, trd)
|
||
sm2 = adder(fst, snd)
|
||
</code></pre>
|
||
<p><code>f</code>, <code>s</code> and <code>t</code> are known as positional parameters as they have a
|
||
defined position in the function definition.</p>
|
||
<p>Also there is a provision to assign a default value to a parameter using <code>=</code>.</p>
|
||
<p>In the above example <code>t</code> has a default value of <code>None</code>.</p>
|
||
<p>Arguments are the values passed to a function (or method) when it is called. In the above example
|
||
<code>fst</code>, <code>snd</code> and <code>trd</code> are the arguments. Since <code>t</code> has a
|
||
default value, the function can be invoked with or without the <code>trd</code> argument as shown for
|
||
<code>sm2</code>.
|
||
</p>
|
||
<p>Argument values are assigned to the corresponding function parameters that are available as local
|
||
variables inside the function.</p>
|
||
<p>Thus, value of <code>fst</code> is assigned to <code>f</code> and <code>snd</code> is assigned to
|
||
<code>s</code>. In case there is no third argument, <code>t</code> has the default value
|
||
<code>None</code>.
|
||
</p>
|
||
<p>The values of <code>sm1</code> and <code>sm2</code> after executing the script are:</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span>sm1
|
||
<span class="hljs-number">40</span>
|
||
<span class="hljs-meta">>>> </span>sm2
|
||
<span class="hljs-number">30</span>
|
||
</code></pre>
|
||
<h2 id="scope-of-variables">Scope of Variables<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#scope-of-variables">#</a></h2>
|
||
<p>In Python, every variable has a well defined scope, i.e., it is accessible by a part of the program and
|
||
it cannot be accessed from outside its scope.</p>
|
||
<p>Based on their scope, there are two types of variables:</p>
|
||
<h3 id="local-variables">Local Variables<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#local-variables">#</a></h3>
|
||
<p>Local variables are defined inside a function or a code block and can only be accessed where they are
|
||
defined.</p>
|
||
<p>They exist only during the execution of the function or the code block.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">triple</span>(<span class="hljs-params">a</span>):
|
||
result = <span class="hljs-number">3</span>*a
|
||
<span class="hljs-comment"># variable result </span>
|
||
<span class="hljs-comment"># is accessible locally</span>
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"local:"</span>, result)
|
||
|
||
<span class="hljs-comment"># Outputs value of result</span>
|
||
<span class="hljs-comment"># inside the function </span>
|
||
triple(<span class="hljs-number">3</span>)
|
||
|
||
<span class="hljs-comment"># Throws an error as result is </span>
|
||
<span class="hljs-comment"># not accessible outside the scope </span>
|
||
<span class="hljs-comment"># of function triple()</span>
|
||
<span class="hljs-built_in">print</span>(<span class="hljs-string">"outside:"</span>, result)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>local: 9
|
||
Traceback (most recent call last):
|
||
File "<stdin>", line 1, in <module>
|
||
NameError: name 'result' is not defined
|
||
</code></pre>
|
||
<h3 id="global-variables">Global Variables<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#global-variables">#</a></h3>
|
||
<p>Variables defined outside any function or code block are known as global variables.</p>
|
||
<p>They are often used to specify mathematical constants, file path or other such values and can be accessed
|
||
anywhere in the source code (by functions or code blocks).</p>
|
||
<p>Below example demonstrates how the global variable <code>n</code> can be accessed by all the functions.
|
||
</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">n = <span class="hljs-number">10</span>
|
||
|
||
<span class="hljs-keyword">def</span> <span class="hljs-title function_">uno</span>():
|
||
<span class="hljs-built_in">print</span>(n)
|
||
|
||
<span class="hljs-keyword">def</span> <span class="hljs-title function_">tres</span>():
|
||
<span class="hljs-built_in">print</span>(n*<span class="hljs-number">3</span>)
|
||
|
||
uno()
|
||
tres()
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>10
|
||
30
|
||
</code></pre>
|
||
<p>In case a variable is defined inside a function with the same name as that of a global variable, then the
|
||
variable is considered as a local variable and all references made to the variable point to this local
|
||
variable.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">n = <span class="hljs-number">10</span>
|
||
|
||
<span class="hljs-comment"># local n inside the</span>
|
||
<span class="hljs-comment"># function</span>
|
||
<span class="hljs-keyword">def</span> <span class="hljs-title function_">uno</span>():
|
||
n = <span class="hljs-number">5</span>
|
||
<span class="hljs-built_in">print</span>(n)
|
||
|
||
<span class="hljs-comment"># global n inside the</span>
|
||
<span class="hljs-comment"># function</span>
|
||
<span class="hljs-keyword">def</span> <span class="hljs-title function_">tres</span>():
|
||
<span class="hljs-built_in">print</span>(n*<span class="hljs-number">3</span>)
|
||
|
||
uno()
|
||
tres()
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>5
|
||
30
|
||
</code></pre>
|
||
<p>Any changes made to a global variable inside a code block or a function can modify it for that session.
|
||
This can have an impact on all the code blocks/functions that access and use it.</p>
|
||
<p>To modify the value of a global variable one can use the <code>global</code> keyword as shown in the
|
||
example below.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python">n = <span class="hljs-number">10</span>
|
||
|
||
<span class="hljs-comment"># function modifies the </span>
|
||
<span class="hljs-comment"># value of global n</span>
|
||
<span class="hljs-keyword">def</span> <span class="hljs-title function_">uno</span>():
|
||
<span class="hljs-keyword">global</span> n
|
||
n = <span class="hljs-number">5</span>
|
||
<span class="hljs-built_in">print</span>(n)
|
||
|
||
<span class="hljs-keyword">def</span> <span class="hljs-title function_">tres</span>():
|
||
<span class="hljs-built_in">print</span>(n*<span class="hljs-number">3</span>)
|
||
|
||
uno()
|
||
tres()
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>5
|
||
15
|
||
</code></pre>
|
||
<h2 id="passing-objects-of-mutable-type-to-a-function">Passing Objects of Mutable Type to a Function<a
|
||
aria-hidden class="header-link" tabindex="-1"
|
||
href="#passing-objects-of-mutable-type-to-a-function">#</a></h2>
|
||
<p>When mutable objects (<code>list</code>, <code>dict</code>) are provided as an argument to a function,
|
||
any modification made to the corresponding parameters in the body of the function leads to the
|
||
modification of the original object.</p>
|
||
<p>Hence, care should be taken while passing mutable objects.</p>
|
||
<h3 id="passing-a-list">Passing a List<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#passing-a-list">#</a></h3>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">repeat</span>(<span class="hljs-params">l</span>):
|
||
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> <span class="hljs-built_in">range</span>(<span class="hljs-built_in">len</span>(l)):
|
||
l[i] = l[i]*<span class="hljs-number">2</span>
|
||
|
||
l = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>]
|
||
<span class="hljs-built_in">print</span>(l)
|
||
repeat(l)
|
||
<span class="hljs-comment"># l is modified</span>
|
||
<span class="hljs-built_in">print</span>(l)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>[1, 2, 3]
|
||
[2, 4, 6]
|
||
</code></pre>
|
||
<h3 id="passing-a-dictionary">Passing a Dictionary<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#passing-a-dictionary">#</a></h3>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">repeat</span>(<span class="hljs-params">d</span>):
|
||
<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> d.keys():
|
||
d[i] = d[i]*<span class="hljs-number">2</span>
|
||
|
||
d = {<span class="hljs-string">'a'</span>:<span class="hljs-number">1</span>, <span class="hljs-string">'b'</span>:<span class="hljs-number">2</span>, <span class="hljs-string">'c'</span>:<span class="hljs-number">3</span>}
|
||
<span class="hljs-built_in">print</span>(d)
|
||
repeat(d)
|
||
<span class="hljs-comment"># d is modified</span>
|
||
<span class="hljs-built_in">print</span>(d)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>{'a': 1, 'b': 2, 'c': 3}
|
||
{'a': 2, 'b': 4, 'c': 6}
|
||
</code></pre>
|
||
<h2 id="what-is-a-module-how-to-create-a-module">What is a Module? How to Create a Module?<a aria-hidden
|
||
class="header-link" tabindex="-1" href="#what-is-a-module-how-to-create-a-module">#</a></h2>
|
||
<p>Once a function is defined in the Python interpreter, it can be called any number of times. But, these
|
||
function definitions are lost upon exiting the interpreter.</p>
|
||
<p>To solve this problem we can create a python script with the function definitions at the beginning of teh
|
||
file, followed by the rest of the code which includes statements invoking the defined functions.</p>
|
||
<p>But, this process is tedious and not managable as what makes user-defined functions powerful is that the
|
||
programmer can - <strong>Write once, and use many times</strong>.</p>
|
||
<p>Instead of repeating the function definition again and again for each new program, one can put all the
|
||
function definitions in a file from which the required function can be imported and invoked either in
|
||
script mode or interactive mode.</p>
|
||
<p>This file (<code>.py</code> extension) is known as a <code>module</code> and it is the most basic form of
|
||
reusable code accessible by other programs.</p>
|
||
<p>Let us create a new file <code>basics.py</code> containing the following functions:</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">adder</span>(<span class="hljs-params">f, s, t = <span class="hljs-literal">None</span></span>):
|
||
<span class="hljs-string">"""
|
||
Returns the sum of f, s and t.
|
||
If t is not provided,
|
||
return the sum of f and s.
|
||
"""</span>
|
||
s = f + s
|
||
<span class="hljs-keyword">if</span> t:
|
||
s += t
|
||
<span class="hljs-keyword">return</span> s
|
||
|
||
<span class="hljs-keyword">def</span> <span class="hljs-title function_">tripler</span>(<span class="hljs-params">a</span>):
|
||
<span class="hljs-string">"""
|
||
Multiplies a by 3 and
|
||
returns it
|
||
"""</span>
|
||
result = <span class="hljs-number">3</span>*a
|
||
<span class="hljs-keyword">return</span> result
|
||
</code></pre>
|
||
<p>After saving the <code>basics.py</code> file, reopen IDLE and create a new file <code>test.py</code> in
|
||
the same directory as basics.py.</p>
|
||
<p>The name of the file is the module name which is also available as the value of the global variable
|
||
<code>__name__</code> in the module.
|
||
</p>
|
||
<p>Import the functions of the basics module in <code>test.py</code> by executing the following statement.
|
||
</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> basics
|
||
</code></pre>
|
||
<p>The above <code>import</code> statement loads all the functions available in the <code>basics</code>
|
||
module. To access any function in the module, simply type the module name followed by a period
|
||
(<code>.</code>), followed by the function name.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> basics
|
||
sa = basics.adder(<span class="hljs-number">20</span>, <span class="hljs-number">10</span>, <span class="hljs-number">10</span>)
|
||
st = basics.tripler(<span class="hljs-number">20</span>)
|
||
<span class="hljs-built_in">print</span>(sa)
|
||
<span class="hljs-built_in">print</span>(st)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>40
|
||
60
|
||
</code></pre>
|
||
<p>The <code>as</code> keyword can also be used to create an alias which makes it easier and more manageable
|
||
to use in the program.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">import</span> basics <span class="hljs-keyword">as</span> ba
|
||
sa = ba.adder(<span class="hljs-number">20</span>, <span class="hljs-number">10</span>, <span class="hljs-number">10</span>)
|
||
st = ba.tripler(<span class="hljs-number">20</span>)
|
||
<span class="hljs-built_in">print</span>(sa)
|
||
<span class="hljs-built_in">print</span>(st)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>40
|
||
60
|
||
</code></pre>
|
||
<p>Instead of loading all the functions in a module, the <code>from</code> statement can be used to access
|
||
only specified functions.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">from</span> basics <span class="hljs-keyword">import</span> adder
|
||
sa = adder(<span class="hljs-number">20</span>, <span class="hljs-number">10</span>, <span class="hljs-number">10</span>)
|
||
<span class="hljs-built_in">print</span>(sa)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>40
|
||
</code></pre>
|
||
<p>To import all functions and global variables in the module the <code>*</code> wildcard character can be
|
||
used.</p>
|
||
<p><strong>Code</strong></p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">from</span> basics <span class="hljs-keyword">import</span> *
|
||
sa = adder(<span class="hljs-number">20</span>, <span class="hljs-number">10</span>, <span class="hljs-number">10</span>)
|
||
st = tripler(<span class="hljs-number">20</span>)
|
||
</code></pre>
|
||
<p><strong>Output</strong></p>
|
||
<pre><code>40
|
||
60
|
||
</code></pre>
|
||
<p>The above method of using <code>*</code> to import the contents of a module is not recommended as it can
|
||
clutter the namespace and cause issues if there are conflicts between the identifiers defined by the
|
||
programmer and those defined in the module/package.</p>
|
||
<h2 id="executable-scripts--modules">Executable Scripts / Modules<a aria-hidden class="header-link"
|
||
tabindex="-1" href="#executable-scripts--modules">#</a></h2>
|
||
<p>Apart from containing definitions, a module can also contain block of code which is executed whenever the
|
||
stand-alone script is run in script mode. The block has to be enclosed in an <code>if</code> statement
|
||
as shown below:</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
|
||
...code to be executed...
|
||
</code></pre>
|
||
<p>Using the above pattern, a file can be imported or executed directly.</p>
|
||
<p>Let us undertake an example module (save it as <code>multi.py</code>) which multiplies two numbers:</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">multiply</span>(<span class="hljs-params">a, b</span>):
|
||
<span class="hljs-keyword">return</span> a * b
|
||
|
||
f = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter a: "</span>))
|
||
s = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter b: "</span>))
|
||
<span class="hljs-built_in">print</span>(multiply(f, s))
|
||
</code></pre>
|
||
<p>Now when we try to load all functions from the module it automatically executes the input assignment
|
||
statements and prints the output.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> test <span class="hljs-keyword">import</span> *
|
||
Enter a: <span class="hljs-number">4</span>
|
||
Enter b: <span class="hljs-number">5</span>
|
||
<span class="hljs-number">20</span>
|
||
<span class="hljs-meta">>>> </span>
|
||
</code></pre>
|
||
<p>Let us modify the code:</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-keyword">def</span> <span class="hljs-title function_">multiply</span>(<span class="hljs-params">a, b</span>):
|
||
<span class="hljs-keyword">return</span> a * b
|
||
|
||
<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
|
||
f = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter a: "</span>))
|
||
s = <span class="hljs-built_in">int</span>(<span class="hljs-built_in">input</span>(<span class="hljs-string">"Enter b: "</span>))
|
||
<span class="hljs-built_in">print</span>(multiply(f, s))
|
||
</code></pre>
|
||
<p>Now, the block will execute only if the script is executed directly and not when the file is imported as
|
||
a module.</p>
|
||
<pre><code class="hljs language-python"><span class="hljs-meta">>>> </span><span class="hljs-keyword">from</span> test <span class="hljs-keyword">import</span> *
|
||
<span class="hljs-meta">>>> </span>multiply(<span class="hljs-number">4</span>, <span class="hljs-number">5</span>)
|
||
<span class="hljs-number">20</span>
|
||
</code></pre>
|
||
<h2 id="what-is-a-package-introduction-to-pypi-how-to-create-a-python-package">What is a Package?
|
||
Introduction to PyPi. How to Create a Python Package?<a aria-hidden class="header-link" tabindex="-1"
|
||
href="#what-is-a-package-introduction-to-pypi-how-to-create-a-python-package">#</a></h2>
|
||
<p>A collection of modules which can work together to provide a common functionality is known as a
|
||
<strong>package</strong>.
|
||
</p>
|
||
<p>These modules are present in a folder along with the <code>__init__.py</code> file which tells Python
|
||
that this folder is a package.</p>
|
||
<p>A package can also contain subfolders (sub-packages), each containing their respective
|
||
<code>__init__.py</code> files.
|
||
</p>
|
||
<p>Let us take the example of a package called <code>restaurant</code> which consists of various modules to
|
||
perform activities such as order booking, reservation, staff attendance, etc.</p>
|
||
<p>Here is a possible structure for the package:</p>
|
||
<pre><code>restaurant/
|
||
__init__.py
|
||
orders.py
|
||
reservation.py
|
||
employee.py
|
||
inventory.py
|
||
</code></pre>
|
||
<p>A package is simply the directory containing sub-packages and modules, but when this package or a
|
||
collection of packages are made available for others to use (eg. via PyPI) it is known as a
|
||
<strong>library</strong>.
|
||
</p>
|
||
<p>For example, <code>restaurant</code> can be called a library if it provides reusable codes to manage a
|
||
restaurant and is built using multiple packages which handle the various aspects of a restaurant like
|
||
human resource management, inventory management, order fulfilment and billing, etc.</p>
|
||
<p>One should note that the above definition is not strict and often the terms package and library are used
|
||
interchangeably.</p>
|
||
</div>
|
||
</main>
|
||
<div class="top-bar" data-js="top-bar"><button class="top-bar__menu-toggle-button"
|
||
data-js="top-bar-menu-toggle-button"><svg class="top-bar__menu-toggle-button-menu-svg" viewBox="0 0 16 16"
|
||
xmlns="http://www.w3.org/2000/svg">
|
||
<path fill="currentColor" fill-rule="evenodd" clip-rule="evenodd"
|
||
d="M0 2.75C0 2.33579.335786 2 .75 2h14.5c.4142 0 .75.33579.75.75s-.3358.75-.75.75H.75C.335786 3.5 0 3.16421 0 2.75zM0 8c0-.41421.335786-.75.75-.75h14.5c.4142 0 .75.33579.75.75s-.3358.75-.75.75H.75C.335786 8.75 0 8.41421 0 8zm.75 4.5c-.414214 0-.75.3358-.75.75s.335786.75.75.75h14.5c.4142 0 .75-.3358.75-.75s-.3358-.75-.75-.75H.75z" />
|
||
</svg> <svg class="top-bar__menu-toggle-button-close-svg" viewBox="0 0 16 16"
|
||
xmlns="http://www.w3.org/2000/svg">
|
||
<path fill="currentColor" fill-rule="evenodd" clip-rule="evenodd"
|
||
d="M1.28033.21967c-.292893-.2928933-.767767-.2928933-1.06066 0-.2928933.292893-.2928933.767767 0 1.06066L6.93934 8 .21967 14.7197c-.2928933.2929-.2928933.7677 0 1.0606.292893.2929.767767.2929 1.06066 0L8 9.06066l6.7197 6.71964c.2929.2929.7677.2929 1.0606 0 .2929-.2929.2929-.7677 0-1.0606L9.06066 8l6.71964-6.71967c.2929-.292893.2929-.767767 0-1.06066-.2929-.2928933-.7677-.2928933-1.0606 0L8 6.93934 1.28033.21967z" />
|
||
</svg></button>
|
||
<div class="top-bar__title"><a class="top-bar__title-link" href="https://animator.github.io/learn-python/"
|
||
data-js="top-bar-title-link">Learn Python 3 by Ankit Mahato </a><span
|
||
class="top-bar__title-version">v2022.10</span></div>
|
||
<div class="top-bar__items">
|
||
<ul>
|
||
<li><a href="https://github.com/animator/learn-python/blob/main/pdf/learn-python-v2022.10.pdf"
|
||
target="_blank">PDF</a></li>
|
||
<li><a href="https://github.com/animator/learn-python" target="_blank">Star it on GitHub</a></li>
|
||
</ul>
|
||
</div>
|
||
</div>
|
||
<div class="menu" data-js="menu">
|
||
<ul class="menu__links">
|
||
<li><a href="https://github.com/animator/learn-python/blob/main/pdf/learn-python-v2022.10.pdf"
|
||
target="_blank">PDF</a></li>
|
||
<li><a href="https://github.com/animator/learn-python" target="_blank">GitHub</a></li>
|
||
</ul>
|
||
<ul>
|
||
<li><a href="#learn-python-3">Learn Python 3</a></li>
|
||
<li><a href="#how-to-read-this-book">How to read this book?</a></li>
|
||
<li><a href="#table-of-contents">Table of Contents</a></li>
|
||
<li><a href="#introduction">Introduction</a>
|
||
<ul>
|
||
<li><a href="#introduction-to-programming-languages">Introduction to Programming Languages</a></li>
|
||
<li><a href="#introduction-to-python">Introduction to Python</a></li>
|
||
<li><a href="#advantages-of-python">Advantages of Python</a></li>
|
||
<li><a href="#installing-python-in-windows">Installing Python in Windows</a></li>
|
||
<li><a href="#installing-python-in-macos-apple">Installing Python in macOS (Apple)</a></li>
|
||
<li><a href="#execution-modes">Execution Modes</a></li>
|
||
<li><a href="#interactive-mode-of-execution">Interactive Mode of Execution</a></li>
|
||
<li><a href="#script-mode-of-execution">Script Mode of Execution</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#python-fundamentals">Python Fundamentals</a>
|
||
<ul>
|
||
<li><a href="#tokens-introduction">Tokens: Introduction</a></li>
|
||
<li><a href="#tokens-keywords">Tokens: Keywords</a></li>
|
||
<li><a href="#tokens-identifiers">Tokens: Identifiers</a></li>
|
||
<li><a href="#tokens-literals">Tokens: Literals</a>
|
||
<ul>
|
||
<li><a href="#numeric-literals">Numeric Literals</a></li>
|
||
<li><a href="#boolean-literals">Boolean Literals</a></li>
|
||
<li><a href="#string-literals">String Literals</a></li>
|
||
<li><a href="#special-literal">Special Literal</a></li>
|
||
<li><a href="#collection-of-literals">Collection of Literals</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#tokens-operators">Tokens: Operators</a></li>
|
||
<li><a href="#tokens-delimiters">Tokens: Delimiters</a></li>
|
||
<li><a href="#character-set">Character Set</a></li>
|
||
<li><a href="#blocks-and-indentation">Blocks and Indentation</a></li>
|
||
<li><a href="#comments">Comments</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#variables-objects--data-types">Variables, Objects & Data Types</a>
|
||
<ul>
|
||
<li><a href="#what-are-objects--variables">What are Objects & Variables?</a></li>
|
||
<li><a href="#variables--assignment-statements">Variables & Assignment Statements</a></li>
|
||
<li><a href="#built-in-data-types">Built-in Data Types</a>
|
||
<ul>
|
||
<li><a href="#numeric-types---int-float-complex-bool">Numeric Types - <code>int</code>,
|
||
<code>float</code>, <code>complex</code>, <code>bool</code></a></li>
|
||
<li><a href="#sequence-types---str-list-tuple">Sequence Types - <code>str</code>,
|
||
<code>list</code>, <code>tuple</code></a></li>
|
||
<li><a href="#set-type---set">Set Type - <code>set</code></a></li>
|
||
<li><a href="#mapping-type---dict">Mapping Type - <code>dict</code></a></li>
|
||
<li><a href="#special-type---none">Special Type - <code>None</code></a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#type-checking">Type Checking</a></li>
|
||
<li><a href="#type-casting">Type Casting</a></li>
|
||
<li><a href="#mutable--immutable-data-types">Mutable & Immutable Data Types</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#input--output">Input / Output</a>
|
||
<ul>
|
||
<li><a href="#how-to-accept-user-input">How to Accept User Input</a></li>
|
||
<li><a href="#displaying-output">Displaying Output</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#operators--expressions">Operators & Expressions</a>
|
||
<ul>
|
||
<li><a href="#introduction-to-operators">Introduction to Operators</a></li>
|
||
<li><a href="#arithmetic-operators">Arithmetic Operators</a></li>
|
||
<li><a href="#relational-operators">Relational Operators</a></li>
|
||
<li><a href="#assignment-operators">Assignment Operators</a></li>
|
||
<li><a href="#logical-operators">Logical Operators</a></li>
|
||
<li><a href="#identity-operators">Identity Operators</a></li>
|
||
<li><a href="#membership-operators">Membership Operators</a></li>
|
||
<li><a href="#expressions">Expressions</a></li>
|
||
<li><a href="#operator-precedence-with-examples">Operator Precedence with Examples</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#errors--exception-handling">Errors & Exception Handling</a>
|
||
<ul>
|
||
<li><a href="#error-types">Error Types</a></li>
|
||
<li><a href="#syntax-error">Syntax Error</a></li>
|
||
<li><a href="#runtime-error">Runtime Error</a></li>
|
||
<li><a href="#logical-error">Logical Error</a></li>
|
||
<li><a href="#exceptions">Exceptions</a>
|
||
<ul>
|
||
<li><a href="#raise">raise</a></li>
|
||
<li><a href="#assert">assert</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#exception-handling">Exception Handling</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#control-flow">Control Flow</a>
|
||
<ul>
|
||
<li><a href="#introduction-to-control-flow">Introduction to Control Flow</a></li>
|
||
<li><a href="#sequential-flow">Sequential Flow</a></li>
|
||
<li><a href="#selection-statements-if--else">Selection Statements: if .. else</a></li>
|
||
<li><a href="#iteration-for">Iteration: for</a></li>
|
||
<li><a href="#iteration-while">Iteration: while</a></li>
|
||
<li><a href="#jump-statements">Jump Statements</a>
|
||
<ul>
|
||
<li><a href="#pass">pass</a></li>
|
||
<li><a href="#break">break</a></li>
|
||
<li><a href="#continue">continue</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#nested-loops">Nested Loops</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#strings">Strings</a>
|
||
<ul>
|
||
<li><a href="#strings-introduction--creation">Strings: Introduction & Creation</a></li>
|
||
<li><a href="#accessing-characters-of-a-string">Accessing Characters of a String</a></li>
|
||
<li><a href="#string-operations">String Operations</a></li>
|
||
<li><a href="#introduction-to-string-methods">Introduction to String Methods</a></li>
|
||
<li><a href="#convert-case-of-strings">Convert Case of Strings</a></li>
|
||
<li><a href="#check-characters-of-a-string">Check Characters of a String</a></li>
|
||
<li><a href="#split-a-string">Split a String</a></li>
|
||
<li><a href="#strip-characters-from-a-string">Strip Characters from a String</a></li>
|
||
<li><a href="#check-prefix-or-suffix-in-a-string">Check Prefix or Suffix in a String</a></li>
|
||
<li><a href="#find--replace-characters-in-a-string">Find & Replace Characters in a String</a>
|
||
</li>
|
||
<li><a href="#traversing-a-string">Traversing a String</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#list">List</a>
|
||
<ul>
|
||
<li><a href="#what-is-a-python-list-how-to-create-a-list">What is a Python List? How to Create a
|
||
List?</a></li>
|
||
<li><a href="#accessing-items-of-a-list">Accessing Items of a List</a></li>
|
||
<li><a href="#modifying-a-list">Modifying a List</a></li>
|
||
<li><a href="#removing-item-from-a-list">Removing Item from a List</a></li>
|
||
<li><a href="#list-operations">List Operations</a></li>
|
||
<li><a href="#traversing-a-list">Traversing a List</a></li>
|
||
<li><a href="#built-in-functions-that-can-be-used-for-a-list">Built-in Functions that can be used
|
||
for a List</a></li>
|
||
<li><a href="#introduction-to-list-methods">Introduction to List Methods</a></li>
|
||
<li><a href="#adding-items-to-a-list">Adding Items to a List</a></li>
|
||
<li><a href="#removing-items-from-a-list">Removing Items from a List</a></li>
|
||
<li><a href="#counting-or-locating-items-in-a-list">Counting or Locating Items in a List</a></li>
|
||
<li><a href="#reversing-items">Reversing Items</a></li>
|
||
<li><a href="#sorting-a-list">Sorting a List</a></li>
|
||
<li><a href="#copying-a-list">Copying a List</a></li>
|
||
<li><a href="#nested-list">Nested List</a></li>
|
||
<li><a href="#list-comprehension">List Comprehension</a></li>
|
||
<li><a href="#sample-programs">Sample Programs</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#tuple">Tuple</a>
|
||
<ul>
|
||
<li><a href="#list-vs-tuple">List vs Tuple</a></li>
|
||
<li><a href="#how-to-create-tuple">How to Create Tuple?</a></li>
|
||
<li><a href="#what-is-a-singleton">What is a Singleton?</a></li>
|
||
<li><a href="#accessing-items-of-a-tuple">Accessing Items of a Tuple</a></li>
|
||
<li><a href="#tuples-are-immutable">Tuples are Immutable</a></li>
|
||
<li><a href="#tuple-operations">Tuple Operations</a></li>
|
||
<li><a href="#traversing-a-tuple">Traversing a Tuple</a></li>
|
||
<li><a href="#built-in-functions-that-can-be-used-for-a-tuple">Built-in Functions that can be used
|
||
for a Tuple</a></li>
|
||
<li><a href="#locating-items-in-a-tuple">Locating Items in a Tuple</a></li>
|
||
<li><a href="#counting-the-occurrence-of-an-item">Counting the Occurrence of an Item</a></li>
|
||
<li><a href="#new-tuple-with-reversed-items">New Tuple with Reversed Items</a></li>
|
||
<li><a href="#new-tuple-with-sorted-items">New Tuple with Sorted Items</a></li>
|
||
<li><a href="#nested-tuple">Nested Tuple</a></li>
|
||
<li><a href="#understanding-the-immutable-nature-of-tuples">Understanding the Immutable Nature of
|
||
Tuples</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#dictionary">Dictionary</a>
|
||
<ul>
|
||
<li><a href="#what-is-a-dictionary">What is a Dictionary?</a></li>
|
||
<li><a href="#how-to-create-a-dictionary">How to Create a Dictionary</a></li>
|
||
<li><a href="#accessing-items-keyvalue-of-a-dictionary">Accessing Items (Key:Value) of a
|
||
Dictionary</a></li>
|
||
<li><a href="#updating-a-dictionary">Updating a Dictionary</a></li>
|
||
<li><a href="#removing-an-item-keyvalue-from-a-dictionary">Removing an Item (Key:Value) from a
|
||
Dictionary</a></li>
|
||
<li><a href="#dictionary-operations">Dictionary Operations</a></li>
|
||
<li><a href="#traversing-a-dictionary">Traversing a Dictionary</a></li>
|
||
<li><a href="#built-in-functions-for-a-dictionary">Built-in Functions for a Dictionary</a></li>
|
||
<li><a href="#creating-a-copy-of-a-dictionary">Creating a Copy of a Dictionary</a></li>
|
||
<li><a href="#nested-dictionary">Nested Dictionary</a></li>
|
||
<li><a href="#sample-programs-1">Sample Programs</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#python-standard-library">Python Standard Library</a>
|
||
<ul>
|
||
<li><a href="#built-in-functions">Built-in Functions</a></li>
|
||
<li><a href="#mathematical-functions">Mathematical Functions</a></li>
|
||
<li><a href="#type-functions">Type Functions</a></li>
|
||
<li><a href="#io-functions">I/O Functions</a></li>
|
||
<li><a href="#baseunicode-conversion-functions">Base/Unicode Conversion Functions</a></li>
|
||
<li><a href="#what-are-built-in-modules">What are Built-in Modules?</a></li>
|
||
<li><a href="#math-module">math Module</a></li>
|
||
<li><a href="#random-module">random Module</a></li>
|
||
<li><a href="#statistics-module">statistics Module</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#file-handling">File Handling</a>
|
||
<ul>
|
||
<li><a href="#file-handling-in-python---introduction--overview">File Handling in Python -
|
||
Introduction & Overview</a></li>
|
||
<li><a href="#text-files-vs-binary-files---use-case-file-formats-examples">Text Files vs Binary
|
||
Files - Use Case, File Formats, Examples</a></li>
|
||
<li><a href="#file-opening--closing">File Opening & Closing</a></li>
|
||
<li><a href="#file-reading">File Reading</a>
|
||
<ul>
|
||
<li><a href="#sequential-reading">Sequential Reading</a></li>
|
||
<li><a href="#ad-hoc-reading">Ad-hoc Reading</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#writing-a-file">Writing a File</a></li>
|
||
<li><a href="#reading--writing-binary-files-using-pickle-module">Reading & Writing Binary Files
|
||
using <code>pickle</code> Module</a>
|
||
<ul>
|
||
<li><a href="#dumping-data">Dumping Data</a></li>
|
||
<li><a href="#loading-data">Loading Data</a></li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#reading--writing-a-csv-file-using-csv-module">Reading & Writing a CSV File using
|
||
<code>csv</code> Module</a>
|
||
<ul>
|
||
<li><a href="#reading-csv-file">Reading CSV File</a></li>
|
||
<li><a href="#writing-csv-file">Writing CSV File</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</li>
|
||
<li><a href="#user-defined-functions-modules--packages">User Defined Functions, Modules & Packages</a>
|
||
<ul>
|
||
<li><a href="#user-defined-functions">User Defined Functions</a></li>
|
||
<li><a href="#function-structure">Function Structure</a></li>
|
||
<li><a href="#parameters-and-arguments">Parameters and Arguments</a></li>
|
||
<li><a href="#scope-of-variables">Scope of Variables</a></li>
|
||
<li><a href="#passing-objects-of-mutable-type-to-a-function">Passing Objects of Mutable Type to a
|
||
Function</a></li>
|
||
<li><a href="#what-is-a-module-how-to-create-a-module">What is a Module? How to Create a Module?</a>
|
||
</li>
|
||
<li><a href="#executable-scripts--modules">Executable Scripts / Modules</a></li>
|
||
<li><a href="#what-is-a-package-introduction-to-pypi-how-to-create-a-python-package">What is a
|
||
Package? Introduction to PyPi. How to Create a Python Package?</a></li>
|
||
</ul>
|
||
</li>
|
||
</ul>
|
||
</div>
|
||
<script>(() => { "use strict"; function t(t, e) { for (; null !== t && !0 !== e(t);)t = t.parentElement; return t } function e(t) { const { activeClassName: e, contentElement: o, menuElement: i, scrollMarginTopOffset: l, topBarElement: r } = t; function c() { return Array.prototype.slice.call(o.querySelectorAll("[id]")) } function u() { const t = c(), e = t[t.length - 1], n = window.innerHeight - (r.offsetHeight + l) - (o.offsetHeight - e.offsetTop); n < 0 ? o.removeAttribute("style") : o.style.paddingBottom = `${n}px` } let s; u(), window.addEventListener("resize", (function () { window.clearTimeout(s), s = window.setTimeout((function () { u() }), 200) })), window.addEventListener("scroll", (function () { const t = c(), o = function (t) { const { idElements: e, scrollMarginTop: n } = t, o = e.slice().reverse(), i = window.scrollY; for (const t of o) if (t.offsetTop - n - 2 <= i) return t.getAttribute("id"); return null }({ idElements: t, scrollMarginTop: r.offsetHeight + l }); n({ activeClassName: e, element: i, id: o }); const u = function (t) { const { activeId: e, idElements: n } = t; if (null === e) return null; const o = n.findIndex((function (t) { return t.getAttribute("id") === e })), i = n.slice(0, o + 1).reverse().find((function (t) { return "H1" === t.tagName })); if (void 0 !== i) return i.getAttribute("id"); const l = n.find((function (t) { return "H1" === t.tagName })); if (void 0 === l) return null; return l.getAttribute("id") }({ activeId: o, idElements: t }); n({ activeClassName: e, element: r, id: u }) })) } function n(t) { const { element: e, id: n, activeClassName: o } = t, i = e.querySelector(`.${o}`); if (null !== i && i.classList.remove(o), null === n) return; const l = e.querySelector(`[href="#${null === n ? "" : n}"]`); null !== l && l.classList.add(o) } !function () { const n = document.querySelector('[data-js="content"]'), o = document.querySelector('[data-js="top-bar"]'), i = document.querySelector('[data-js="top-bar-menu-toggle-button"]'), l = document.querySelector('[data-js="top-bar-title-link"]'), r = document.querySelector('[data-js="menu"]'); null !== i && function (e) { const { breakpoint: n, topBarMenuToggleButtonElement: o, visibleClassName: i } = e; function l() { document.body.classList.toggle(i) } o.addEventListener("click", l), window.addEventListener("click", (function (e) { !1 !== document.body.classList.contains(i) && (window.innerWidth >= n || null === t(e.target, (function (t) { return t === o })) && l()) })), window.addEventListener("keydown", (function (t) { "Escape" === t.key && l() })) }({ breakpoint: 1600, topBarMenuToggleButtonElement: i, visibleClassName: "--menu-visible" }), null !== r && null !== l && function (t) { const { topBarTitleLinkElement: e, menuElement: n } = t; e.addEventListener("click", (function (t) { !0 !== t.metaKey && !0 !== t.shiftKey && (t.preventDefault(), history.pushState("", document.title, `${window.location.pathname}${window.location.search}`), window.scrollTo({ top: 0 }), n.scrollTo({ top: 0 })) })) }({ menuElement: r, topBarTitleLinkElement: l }), null !== r && function (e, n) { function o(t) { const o = e.querySelector(`[href="${t}"]`); if (null === o) return; const i = o.getBoundingClientRect(), l = null === n ? 0 : n.offsetHeight, r = window.innerHeight; if (i.top >= l && i.bottom <= r) return; const c = 1 * window.parseFloat(window.getComputedStyle(document.documentElement).fontSize); e.scrollTo({ top: Math.max(0, o.offsetTop - c) }) } function i() { const t = window.location.hash; "" !== t ? o(t) : e.scrollTo({ top: 0 }) } window.addEventListener("click", (function (n) { const i = n.target; if ("A" !== i.tagName) return; const l = i.getAttribute("href"); null !== l && null === t(i, (function (t) { return t === e })) && o(l) })), window.addEventListener("popstate", i), i() }(r, o), null !== r && null !== n && null !== o && e({ activeClassName: "--scroll-spy-active", contentElement: n, menuElement: r, scrollMarginTopOffset: 40, topBarElement: o }) }() })();</script>
|
||
</body>
|
||
|
||
</html> |