Python Essential Classroom Series – 01/Aug/2021

Order of Operations

  • Consider the following expression 6 + 2 * -3
  • Python language follows the same order of operations as in math world. You can remember order of operation by the acronym PEMDAS: Parenthesis first, exponential second, multiplication/division third and Addition/Subtraction fourth
6 + 2 * -3

6 - 6

0
  • Now if we write the expression
(6+2) * - 3

8 * -3 
-24
  • Other expression (100-5**3)/5
(100-5**3)/5
(100 - 125)/5
-25/5
-5.0
  • Other expression 6 + 15 % 4
6 + 15 % 4
6 + 3
9
  • Other expression 2 ** 2 + 24 // 4
4 + 6
10

Spacing in Python

  • In python, spaces after a number or symbol donot carry any mean. So 5**2 and 5 ** 2 both will give you result 25
  • Spaces are meant to enhance readability, so space are generally encourage between operands & operators 5 ** 2

Number Types: Integers and Floats

  • Add 5 to 3.14 => 8.14 (float) implicit conversion (5 is converted to float)
  • Explicit conversion
x = 6.0
y = int(x)

Preview

  • Convert from int to float float(6)

Complex Number Types

  • Python inclues complex numbers as an official type Preview Preview
  • Refer Here for complex math in python

Comments in Python

  • Comments are extra blocks of code that donot run. They are meant to clarify code for readers.
  • In Python any text following # symbol on a single line is comment
# In this python file we will be calculating the area of circle
# We accept radius input from user
radius = float(input('Enter radius: '))

# Set the value of pi to a variable
pi = 3.14
area = pi * radius ** 2
print(f"Area of circle with radius {radius} is {area}")
  • Exercise: Write a program with decent comments to calculate area and perimeter of rectange. Take two inputs length and breadth
# This program calculates the area of rectangle

# input for length
length = float(input('Enter the length: '))

# input for breadth
breadth = float(input('Enter the breadth: '))

# calculate area
area = length * breadth

# calculate perimeter
perimeter = 2 * (length + breadth)

print(f"Area is {area} and perimeter is {perimeter}")

Docstrings

  • Docstrings, are short for document strings.
  • These state what a given document such as program, a function or a class actually does.
  • The primary difference in syntax between docstring and comment is that docstrings are intended to be written over multiple lines which is accomplished with triple quotes
  • Docstrings also help in creating a documentation for the document, class and functions
  • Refer Here for the PEP about document strings
  • Refer Here for PEP-8 styling guide for docstrings
  • Refer Here for Google style guide for python
  • Google has proposed docstring which are also widely adopted. Refer 3.8 section in google style guide Refer Here
  • Refer Here for the sample class with docstrings

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin