Introduction to Programming - Lecture 2

Agenda for the class

  1. Linux terminal Basics (~20 minutes)
  2. Lists (~15 minutes)
    • List functions such as append etc.
    • Mutability
    • Slicing/len()
    • nested lists
  3. Basic Input and Output (5-10 minutes)
  4. Creating a small program (Remaining time)

Lists

  1. A default python datatype.
  2. Strings and lists have some similar features, like length, indexing of elements etc.
  3. Basic differences from strings are
    • Mutability: Lists are mutable whereas strings are not. This basically means we can make changes to lists after initiailizing but we can't do that in strings.
    • Lists can have multiple datatypes within them.

In [ ]:
squares=[0,1,4,9,16,25] #list_name = [value1,value2,value3,...] 
print(squares)
print("Length is:",len(squares))

In [ ]:
print(squares[3])

In [ ]:
squares.append(36)
print(squares)

In [ ]:
squares.append("forty-nine")
print(squares)

In [ ]:
squares.extend([64,81])
print(squares)

In [ ]:
squares[7]=49
print(squares)

In [ ]:
print(squares[0:3])

In [ ]:
4 in squares

Some other list methods

  1. list.index(x)
  2. list.count(x)
  3. list.insert(i,x)

Link: https://docs.python.org/3/tutorial/datastructures.html


In [ ]:
L1 = [ 10, [20,21,22,23], 30, [40,41], 50 ]
print(L1)

In [ ]:
print(L1[0])

In [ ]:
print(L1[1])

In [ ]:
print(L1[0][0]) # L1[0] gives us the first element of the list, which is an integer(10). Since integers cannot be 
                # indexed like a string or list, we get an error.

In [ ]:
print(L1[1][0])

Input methods


In [ ]:
n1=input("Enter first number: ")
n2=input("Enter second number: ")

In [ ]:
sum=n1+n2
print(sum)

In [ ]:
a=int(n1)
b=int(n2)
sum=a+b
print(sum)

In [ ]:
num='-3.15'
pie=float(num)
print(pie)

Short Assignment 1 :

Getting comfortable with list operations is important. Even though the problem can be concisely solved with the
use of for loop, since loops haven't been taught yet, you can solve it by a bunch of slicing statements instead.

1. Take a string as input and print it explained by the example below. Given length of string is equal to 12.

   Example
   --------

   Input : HelloWorlds!

   Output :

   HelloWorlds!
   Hlools
   Hlod
   Hol
   HWs
   Ho
   !sdlroWolleH
   !drWle
   !lWl
   !rl
   !oe
   !W


2. Take two strings as input and print it as explained by the example below.
   Total sum length of both strings is 19.

   Example
   -------

   Input : string1 --> "DireStraits", string2 --> "TheKinks"

   Output :

   stiartSeriDskniKehT
   sirSrDsih
   stDs
   srs
   ss

In [ ]: