Basic Commands in Python - agastya2002/IECSE-ML-Winter-2020 GitHub Wiki

Now that you have your python system up and running, its time to get our feet wet.

Python Basics

Note:

These commands shown below can be executed individually in each cell in a jupyter notebook for a better understanding. For those not using notebooks can write the commands shown into a single program and execute it in one go:

Print statement

print()

The print() function prints the given object to the standard output device (screen) or to the text stream file.

print("Hello, World!")
Hello, World!
a = 10
b = 10.5

print(a)
print(b)
10
10.5

Working with Input

input()

The input() method reads a line from input, converts into a string and returns it.

end

end - end is printed at last

name = input("Enter the name of your organisation:")
print("Hello",end=' ')
print(name)
Enter the name of your organisation:iecse
Hello iecse

Variables and Operators

Rules for naming identifiers:

The first character of the identifier must be a letter of the alphabet ( uppercase ASCII or lowercase ASCII or Unicode character) or an underscore (_).

The rest of the identifier name can consist of letters (uppercase ASCII or lowercase ASCII or Unicode character), underscores (_) or digits (0-9).

Identifier names are case-sensitive. For example, myname and myName are not the same. Note the lowercase n in the former and the uppercase N in the latter. Examples of valid identifier names are i, name_2_3. Examples of invalid identifier names are 2things, this is spaced out, my-name and >a1b2_c3.

Arithmetic Operators

a = 10
b = 21

print(a+b)
print(a-b)
print(a*b)
print("%0.4f"%(a/b)) # prints upto 4 digits after the decimal
print(a//b) # the corresponds to floor division, eg: 5//2 = 2(not 2.5)
#Exponent/Power Function
print(a**b)# eg 2**3 = 8
print(b%a)# prints the remainder of the division eg 5%2 = 1
31
-11
210
0.4762
0
1000000000000000000000
1

Multiple Variable Assignment

We can assign multiple variables in one go:

a,b,c = 10,20,30.34
# This functions print the variables
print(a,b,c)
10 20 30.34

Control Flow Structures

If Else Blocks

Decision making is required when we want to execute a code only if a certain condition is satisfied.

The if…elif…else statement is used in Python for decision making.

mood  = input()

if mood=="Good":
    print("I am feeling good!")
    print("I should definitely code!")
    
elif mood=="Sad":
    print("I think I should code to feel better!")

else:
    print("Lets just code")
Good
I am feeling good!
I should definitely code!

Here, the program evaluates the test expression and will execute statement(s) only if the text expression is True.

If the text expression is False, the statement(s) is not executed.

In Python, the body of the if statement is indicated by the indentation. Body starts with an indentation and the first unindented line marks the end.

Python interprets non-zero values as True. None and 0 are interpreted as False.

Python if Statement Flowchart

Flowchart of if statement in Python programming

Loops in Python

Python programming offers two kinds of loop, the for loop and the while loop. Using these loops along with loop control statements like break and continue, we can create various forms of loop. while loop:

n = 10
i = 1

while i<=n:
    print("Step %d"%i)
    i = i + 1

print("Loop Finished")
    
Step 1
Step 2
Step 3
Step 4
Step 5
Step 6
Step 7
Step 8
Step 9
Step 10
Loop Finished

for loop:

for i in range(1,10,2):
    print(i,end=",")
1,3,5,7,9,
no = 10
ans = 1

for i in range(1,11):
    ans *= i
    
print(ans)
3628800
for i in range(10,1,-2):
    print(i,end=',')
10,8,6,4,2,

Note:

range() Parameters

The range() type returns an immutable sequence of numbers between the given start integer to the stop integer. range() constructor has two forms of definition:

range(stop)
range(start, stop[, step])

range() takes mainly three arguments having the same use in both definitions:

  • start - integer starting from which the sequence of integers is to be returned
  • stop - integer before which the sequence of integers is to be returned.
    The range of integers end at stop - 1.
  • step (Optional) - integer value which determines the increment between each integer in the sequence

range(stop)

  • Returns a sequence of numbers starting from 0 to stop - 1
  • Returns an empty sequence if stop is negative or 0. range(start, stop[, step])

Data Types in Python

Built-in data types

Numbers

  • int a = 10 Signed Integer
  • long a = 345L (L) Long integers
  • float a = 45.67 (.) Floating point real values
  • complex a = 3.14J (J) Contains integer in the range 0 to 255.

Strings

String Create string variables by enclosing characters in quotes. Python uses single quotes ' double quotes " and triple quotes """ to denote literal strings.

Lists

List is like an array, heterogeneous list. List variables are declared by using brackets [ ] following the variable name. All lists in Python are zero-based indexed. Lists can contain different variable types. Lists are mutable.

myList = [ 1,2,3.5,"Hello"]
print(myList)
print(type(myList))
[1, 2, 3.5, 'Hello']
<class 'list'>
l2 = list([1,2,3])
print(l2)
print(type(l2))
[1, 2, 3]
<class 'list'>
l3 = list(l2)
print(l3)

l3 = l3 + l2
print(l3)

l3.extend(l2)
print(l3)
[1, 2, 3]
[1, 2, 3, 1, 2, 3]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
# List of Square of the numbers from 1 to 5
l4 = [i*i for i in range(1,6)]
print(l4)
[1, 4, 9, 16, 25]

List slicing

print(l4[0:3])
print(l4[-3:])
[1, 4, 9]
[9, 16, 25]

We can access a range of items in a list by using the slicing operator (colon). The indexes and slices can be better visualised using the following: Image result for python list slice

Insertion and Deletion

  • append()

The append() method adds a single item to the end of the list. The syntax of the append() method is: list.append(item)

  • insert()

The insert() method inserts an element to the list at a given index. The syntax of insert() method is list.insert(index, element)

  • del

The syntax of del statement is: del obj_name

Here, del is a Python keyword. And, obj_name can be variables, user-defined objects, lists, items within lists, dictionaries etc. Can also be used to remove multiple items from lists using slices.

l = [1,2]
l.append(3)

l.append([1.0,2.1])
l += [4,5,6]
print(l)
[1, 2, 3, [1.0, 2.1], 4, 5, 6]
l.insert(2,20)
print(l)
[1, 2, 20, 3, [1.0, 2.1], 4, 5, 6]
del l[0]
print(l)
[2, 20, 3, [1.0, 2.1], 4, 5, 6]
l = ([1,2,3])
l = l*4
print(l)
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
for x in l:
    print(x)
1
2
3
1
2
3
1
2
3
1
2
3

Searching and Sorting on lists

  • index()

The index() method searches an element in the list and returns its index. In simple terms, the index() method finds the given element in a list and returns its position.

If the same element is present more than once, the method returns the index of the first occurrence of the element.

Note: Index in Python starts from 0, not 1.

The syntax of the index() method is: list.index(element)

  • sort()

will sort the list in place

  • sorted()

will return a new sorted list

l = [4,5,1,3,2]
l = sorted(l)
print(l)
[1, 2, 3, 4, 5]
l = [4,5,1,3,2]

l.sort(reverse=True)
print(l)
[5, 4, 3, 2, 1]

Tuples

Tuples are given by () Tuples are fixed in size once they are assigned. They don't have append and extend methods.

t = (1,2,3,"Hello")
print(t)
(1, 2, 3, 'Hello')
# Convert a tuple into a list

l = list(t)
print(l)

l[0] = 5
print(l)
[1, 2, 3, 'Hello']
[5, 2, 3, 'Hello']
t2 = tuple(l)
print(t2)
(5, 2, 3, 'Hello')
#concatentation
print(t2 + t)

#Repetion
t2 = t2*3
print(t2)
(5, 2, 3, 'Hello', 1, 2, 3, 'Hello')
(5, 2, 3, 'Hello', 5, 2, 3, 'Hello', 5, 2, 3, 'Hello')
del t
print(t)
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-27-755ed05ee266> in <module>
      1 del t
----> 2 print(t)


NameError: name 't' is not defined

Dictionaries in Python

Dictionaries in Python are lists of Key:Value pairs. This is a very powerful datatype to hold a lot of related information that can be associated through keys.

The main operation of a dictionary is to extract a value based on the key name. Unlike lists, where index numbers are used, dictionaries allow the use of a key to access its members. Dictionaries can also be used to sort, iterate and compare data.

d = {"Mango":100,"Apple":80}
print(d)
#Look Up
print(d["Mango"])

d["Guava"] = 60
print(d)

d["Grape"] = [10,20]
print(d["Grape"])

d["Pineapple"] = {"Small":90,"Large":150}

print(d["Pineapple"]["Small"])
{'Mango': 100, 'Apple': 80}
100
{'Mango': 100, 'Apple': 80, 'Guava': 60}
[10, 20]
90
print(d.keys())
print(d.values())
print(type(d.get("Mangoes")))
dict_keys(['Mango', 'Apple', 'Guava', 'Grape', 'Pineapple'])
dict_values([100, 80, 60, [10, 20], {'Small': 90, 'Large': 150}])
<class 'NoneType'>
if "Mangoes" in d:
    print("Price of Mango is %d"%(d["Mango"]))
else:
    print("Doesn't exist")
Doesn't exist
del d["Pineapple"]
l = list(d.items())
print(l)
[('Mango', 100), ('Apple', 80), ('Guava', 60), ('Grape', [10, 20])]

Functions in Python

You can create functions to make your program modular, and helps in making code reusable in order to avoid repetition.

Creating a function

def my_function():
  print("Hello World")

Calling a function

def my_function():
  print("Hello World")

my_function()
Hello World

Passing Parameters and Default Parameters

def my_function(fname):
  print(fname + " Refsnes")

my_function("Emil")
my_function("Tobias")
my_function("Linus")
Emil Refsnes
Tobias Refsnes
Linus Refsnes
def my_function(country = "Norway"):
  print("I am from " + country)

my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
I am from Sweden
I am from India
I am from Norway
I am from Brazil

Passing List as parameter

def my_function(food):
  for x in food:
    print(x)

fruits = ["apple", "banana", "cherry"]

my_function(fruits)
apple
banana
cherry

Return values

def my_function(x):
  return 5 * x

print(my_function(3))
15

Recursion

# An example of a recursive function to
# find the factorial of a number

def calc_factorial(x):
    """This is a recursive function
    to find the factorial of an integer"""

    if x == 1:
        return 1
    else:
        return (x * calc_factorial(x-1))

num = 4
print("The factorial of", num, "is", calc_factorial(num))
The factorial of 4 is 24
⚠️ **GitHub.com Fallback** ⚠️