Introduction to Python — Day 1/3

Sudh Bhoi
5 min readMay 24, 2020

--

< Day 0: Download Python

Python Basics

Python is an example of very commonly used modern programming language. It was released in 1991, while C was first released in 1972. It is an excellent and versatile language choice for making complex C operations much simpler. Like,

  • String Manipulation
  • Networking

Fortunately, Python is heavily inspired by C (its primary interpreter, Cpython, is actually written in C) and so the syntax should be a shallow learning curve for a C programmer. Unlike a C program, which typically has to be compiled before you can run it, a Python program can be run (in Python interpreter) without explicitly compiling it first.

Scalar Objects

Objects which cannot be subdivided are called scalar objects. (While, the objects which can be subdivided and their internal structure accessed are called non-scalar objects). In Python,

  • int — represent integers
  • float — represent real numbers
  • bool — represent boolean values True and False
  • NoneTypespecial and has one value, None

You can use type() to see the type of an object:

In [2]: type(7.0)
Out[2]: float

You can convert objects from one type to another.

float(7)      # converts integer 7 to float 7.0
int(3.9) # truncates float 3.9 to integer 3
# Note that there is difference between int() and round()

Also i/j results in float while i//j results in int division.

Indentation matters in Python

It is how you denote block of code.

Indentation in Python

Variables

Python variables have two big differences from C.

  • No type specifier.
  • Declared by initialisation only.
  • (and no semicolon!)
C vs Python Variables

String

Strings can be enclosed in quotation marks or single quotes.

hi = “hello there”
greetings = ‘hello’

Various operations can be performed on strings.

  • ‘ab’ + ‘cd’ performs string concatenation
  • 3 * ‘ab’ performs successive concatenation
  • len(‘abcd’) calculates the length of the string
  • ‘abcd’[1] performs indexing
  • ‘abcd’[1:3] performs slicing

String can be sliced using [start:stop:step]

s = “abcdefgh”s[::-1]                       # evaluates to “hgfedcba”
s[3:6] # evaluates to “def”
s[-1] # evaluates to “h”

Strings are immutable

s = “hello”s[0] = “y”                    # error
s = “y” + s[1:len(s)] # s is a new object

Conditionals

All of the old favourites from C are still available for you to use, but they look a little bit different now.

Loops

Two varieties (No do while loops):

  • while
  • for
C vs Python Loops

In range(start, stop, step) the default values are start = 0 and step = 1.

Note that the ++ is not the increment operator in Python.

Functions

Python has support for functions as well. Like variables, we don’t need to specify the return type of the function (because it doesn’t matter), nor the data types of any parameters.

All functions are introduced with the def keyword.

• Also, no need for main; the interpreter reads from top to bottom!

• If you wish to define main nonetheless (and you might want to!), you must at the very end of your code have:

if __name__ == “__main__”:
main()

Example: Function to find the square root of a given number

def square(x):
“””
Input: x, an integer
Returns the square of x
“””
return x ** 2
def main():
print(square(5)) # calling the function
if __name__ == "__main__":
main() # outputs 25

Note that (triple quotes) “”” … “”” are used for multiple line string literals. In the above code snippet it is used as docstring/specification for the square() (doing so is optional but recommended).

Function are first class objects. Functions arguments can take on any type, even other functions.

def func_a():
print('inside func_a’)
def func_b(y):
print('inside func_b’)
return y
def func_c(z):
print('inside func_c’)
return z()

print(func_a())
print(5 + func_b(2))
print(func_c(func_a)) # call func_c takes another function
# func_a as a parameter

Interestingly, in Python, you’ll often have to decide between using keyword argument and positional arguments. Each of the following invocation is equivalent.

def printName(firstName, lastName, reverse = False):
if reverse:
print(lastName + ‘, ‘ + firstName)
else:
print(firstName, lastName)

printName(“Sudh”, “Bhoi”, False)
printName(“Sudh”, “Bhoi”)
printName(“Sudh”, lastName = “Bhoi”, reverse = False)
printName(lastName = “Bhoi”, reverse = False, firstName = “Sudh”)

Output: print()

Following are ways to interpolate variables into our printed statements.

x = 1
x_str = str(x)
print("my fav num is", x, ".", "x =", x)
print("my fav num is " + x_str + ". " + "x = " + x_str)
print("my fav num is {}. x = {}".format(x, x))

Note the difference in spaces and variables passed into the above print statements.

Input: input()

input() prints whatever is within the quotes. Then, it returns the user entered sequence. You can bind that value to a variable for reference.

text = input(“Type anything... “)
print(5*text)

Note that input returns string and must be cast if working with numbers.

num = int(input(“Type a number... “))
print(5*num)

Including Files

Just like C programs can consist of multiple files to form a single program, so can Python programs tie files together.

File Handling

Every operating system has its own way of handling files; Python provides an operating-system independent means to access files, using a file handle.

nameHandle = open(‘kids’, ‘w’)

It creates a file named kids and returns file handle which you can name and thus reference. The w indicates that the file is to be opened for writing into.

Example:

nameHandle = open(‘kids’, ‘w’)for i in range(2):
name = input(‘Enter name: ‘)
nameHandle.write(name + ‘\’)
nameHandle.close()
nameHandle = open(‘kids’, ‘r’)
for line in nameHandle:
print(line)
nameHandle.close()

Programming Assignment

Question 0

  1. Write a program that prints Fibonacci Series.
  2. Write a program that gets an integer input from user and calculates its square root using
  3. Exhaustive enumeration and
  4. Newton-Raphson approximation algorithm.
  5. Write a recursive program that finds GCD of two given numbers.
  6. Write a recursive program for Tower of Hanoi.

Question 1

Assume S is string of lower case characters. Write a program that counts up the number of vowels contained in the string S.

Question 2

Write a program that prints the number of times string “bob” occurs in S.

Question 3

Write a program that prints longest substring in alphabetical order. In case of ties, print first substring.

--

--