Introduction to Python (Mon Oct 21, 2024)

1 + 2
3
print("hello, world!")
hello, world!

We use markdown to write notes.

Press Shift + Enter to execute a cell.

You can write heading using:

# Heading level 1
## Heading level 2

Heading level 1

Heading level 2

You can also write math.

$x^2 + y^2 = z^2$

$\Sigma_{x=0}^{n}{x} = \frac{n (n+1)}{2}$

\(x^2 + y^2 = z^2\)

\(\Sigma_{x=0}^{n}{x} = \frac{n (n+1)}{2}\)

Quick Recap of Python

print("hello, world!")
hello, world!

Python Datatypes

x = 1
print(x)

x = "hello"
print(x)
1
hello

Integers

Python has integers.

7 + 2
9
7 - 2
5
7 * 2
14
7 / 2
3.5

To perform integer division, use the // operator.

7 // 2
3
2 ** 10
1024
2 ** 1000
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376

Floating Point Numbers

Python has floating point numbers too.

1.2 + 2.3
3.5
0.1 + 0.2 
0.30000000000000004

Please checkout https://0.30000000000000004.com/ for explanation.

Strings

Strings in Python can be closed in single quotes of double quotes.

"hello"
'hello'
'world'
'world'
"hello" + "world"
'helloworld'
"hello" * 5
'hellohellohellohellohello'
line = "-" * 40
print(line)
----------------------------------------
len("hello")
5

Problem: Can you write a program to generate the following pattern using Python code? It has exactly 20 hyphen (-) characters.

@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@-@

Problem: Write a program to display a header and footer for name as shown below.

name = "Python"
# your code here

Will produce:

------
Python
------

If the value of name is “Bangalore”, the output would be:

---------
Bangalore
---------
name = "Python"
print(name)
Python

Python supports multi-line strings too!

message  = """
Hello everyone,

Welcome to the FCP class.
"""
message
'\nHello everyone,\n\nWelcome to the FCP class.\n'
print(message)

Hello everyone,

Welcome to the FCP class.

String Formatting

Python uses format strings for string formatting.

They are like regular strings, but start with a prefix f.

name = "Python"
message = f"Hello {name}"
print(message)
Hello Python
name = "Anand"
message = f"""
Dear {name},

Good morning!
"""
print(message)

Dear Anand,

Good morning!
n = 12

for i in range(1, 11):
    print(f"{n} * {i} = {n*i}")
12 * 1 = 12
12 * 2 = 24
12 * 3 = 36
12 * 4 = 48
12 * 5 = 60
12 * 6 = 72
12 * 7 = 84
12 * 8 = 96
12 * 9 = 108
12 * 10 = 120

The string formatting supports aligning.

n = 12

for i in range(1, 11):
    print(f"{n:2d} * {i:2d} = {n*i:3d}")
12 *  1 =  12
12 *  2 =  24
12 *  3 =  36
12 *  4 =  48
12 *  5 =  60
12 *  6 =  72
12 *  7 =  84
12 *  8 =  96
12 *  9 = 108
12 * 10 = 120

Python has good support for unicode text.

name = "ಭಾರತೀಯ ಅಂಕಿಅಂಶಗಳ ಸಂಸ್ಥೆ"
print("Welcome to", name)
Welcome to ಭಾರತೀಯ ಅಂಕಿಅಂಶಗಳ ಸಂಸ್ಥೆ
print("\u0c05\u0c06\u0c07\u0c08") # telugu
print("\u0c85\u0c86\u0c87\u0c88") # kannada
print("\u0905\u0906\u0907\u0908") # hindi
అఆఇఈ
ಅಆಇಈ
अआइई
cat = "\U0001f638"
cat
'😸'
cat * 10
'😸😸😸😸😸😸😸😸😸😸'

Lists

[1, 2, 3, 4]
[1, 2, 3, 4]
x = ["a", "b", "c", "d"]
x
['a', 'b', 'c', 'd']
len(x)
4
names = ["Alice", "Bob", "Charlie", "Dave"]
names
['Alice', 'Bob', 'Charlie', 'Dave']
len(names)
4
names[0]
'Alice'
names[1]
'Bob'

We can use for loop to iterate over a list.

for name in names:
    print("Hello", name)
Hello Alice
Hello Bob
Hello Charlie
Hello Dave

How to print them in the same line?

for name in names:
    print("Hello", name, end=" * ")
Hello Alice * Hello Bob * Hello Charlie * Hello Dave * 

Dictionaries

phone_numbers = {
    "Alice": 1234,
    "Bob": 2345,
    "Charlie": 3456
}
phone_numbers
{'Alice': 1234, 'Bob': 2345, 'Charlie': 3456}
phone_numbers["Alice"]
1234
phone_numbers["Dave"] = 4567
phone_numbers
{'Alice': 1234, 'Bob': 2345, 'Charlie': 3456, 'Dave': 4567}
phone_numbers["Alice"] = 1235
phone_numbers
{'Alice': 1235, 'Bob': 2345, 'Charlie': 3456, 'Dave': 4567}

Functions, Methods & Modules

Python has many built-in functions.

print("hello")
hello
len("hello")
5
sum([1, 2, 3, 4, 5])
15

Python doesn’t allow operations on incompatible datatypes.

1 + "2"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[75], line 1
----> 1 1 + "2"

TypeError: unsupported operand type(s) for +: 'int' and 'str'

The built-in functions int and str can be used to convert values to integer and string respectively.

str(1) + "2"
'12'
1 + int("2")
3

Example: Counting the number of digits in a number

12345
12345
2 ** 100
1267650600228229401496703205376
# how many digits  are there in number n?
n = 2 ** 100

len(str(n))
31

Writing our own functions

def square(x):
    return x*x
square(4)
16

Can we convert the count digits example into a function?

def count_digits(n):
    return len(str(n))
count_digits(2**100)
31