You are on page 1of 33

Introduction to

Python

 1
“This versatility means that
the CIA has used it for
hacking, Google for crawling
webpages, Pixar for
producing movies and
Spotify for recommending
songs.”

 2
Top Skills in Data
Science

 3
 4
Languages
Some influential ones:
◦ FORTRAN
◦ science / engineering

◦ COBOL
◦ business data

◦ LISP
◦ logic and AI

◦ BASIC
◦ a simple language

 5
Programming Basics
code or source code: The sequence
of instructions in a program.

syntax: The set of legal structures


and commands that can be used in
a particular programming language.

output: The messages printed to


the user by a program.

console: The text box onto which


output is printed.
◦ Some source code editors pop up the
console as an external window, and
others contain their own console
window.

 6
Input/Output, Repetition
(loops)
and Selection (if/else)

7

print
 print : Produces text output on the console.
 Syntax:
print "Message"
print Expression
 Prints the given text message or expression value on the
console, and moves the cursor down to the next line.

print Item1, Item2, ..., ItemN


 Prints several messages and/or expressions on the same line.

 Examples:
print ("Hello, world!“)
age = 37
print (“Your age is: “,age)

Output:
Hello, world!
Your age is 37
 8
input
input : Reads a number from user input.

◦ You can assign (store) the result of input into a variable.


◦ Example:
age = eval(input("How old are you? "))
print ("Your age is", age)
print ("You have", 60 - age, "years until
retirement“)

Output:

How old are you? 37


Your age is 37
You have 23 years until retirement

 9
The for loop
for loop: Repeats a set of statements over a group of values.
◦ Syntax:

for variableName in groupOfValues:


statements

◦ We indent the statements to be repeated with tabs or spaces.


◦ variableName gives a name to each value, so you can refer to it in the statements.
◦ groupOfValues can be a range of integers, specified with the range function.

◦ Example:

for x in range(1, 6):


print (x, "squared is", x * x)

Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25  10
range
The range function specifies a range of integers:
◦ range(start, stop) - the integers between start (inclusive)
and stop (exclusive)

◦ It can also accept a third value specifying the change between values.
◦ range(start, stop, step) - the integers between start (inclusive)
and stop (exclusive) by step

◦ Example:
for x in range(5, 0, -1):
print (x)
print ("Blastoff!”)

Output:
5
4
3
2
1
Blastoff!

 11
Exercise
Write a program that prints following triangle. Size of the triangle is taken
as an input from the user. (i.e. the following triangle is of size 5.)

*
**
***
****
*****

 12
Cumulative loops
Some loops incrementally compute a value that is initialized outside the
loop. This is sometimes called a cumulative sum.

sum = 0
for i in range(1, 11):
sum = sum + (i * i)
print ("sum of first 10 squares is", sum)

Output:
sum of first 10 squares is 385

 13
if
if statement: Executes a group of statements
only if a certain condition is true. Otherwise, the
statements are skipped.
◦ Syntax:
if condition:
statements

Example:
gpa = 3.4
if gpa > 2.0:
print "Your application is
accepted."

 14
if/else
if/else statement: Executes one block of
statements if a certain condition is True, and a
second block of statements if it is False.

◦ Syntax:
if condition:
statements
else:
statements

Example:
gpa = 1.4
if gpa > 2.0:
print "Welcome to The
University!"
else:
print "Your application is
denied."

 15
if/else
Multiple conditions can be chained with elif ("else
if"):

if condition:
statements
elif condition:
statements
else:
statements

 16
Exercise

People often forget closing parentheses when entering formulas.


Write a program that asks the user to enter a formula and prints
out whether the formula has the same number of opening and
closing parentheses.

 17
Strings and Lists

 18
Strings
string: A sequence of text characters in a program.
◦ Strings start and end with quotation mark " or apostrophe ' characters.
◦ Examples:

“Hello"
"This is a string"
"This, too, is a string. It can be very long!"

A string may span across multiple lines or contain a " character. A triple-quote is used
for this purpose:

""" This is
a legal String. ""“

""" This is also a "legal" String. """

 19
Strings
A string can represent characters by preceding them with a backslash.
◦ \t tab character
◦ \n new line character
◦ \" quotation mark character

Example: "Hello\tthere\nHow are you?“

Output: Hello there


How are you?

 20
Concatenation and
repetition
The operators + and * can be used on strings.

o + operator combines two strings. This operation is called concatenation.

o * operator repeats a string a certain number of times.

Following are some examples:

 21
Indexes
Characters in a string are numbered with index starting at 0:
◦ Example:
alpha = “abcdefghij"

index 0 1 2 3 4 5 6 7 8 9
character a b c d e f g h i j

Accessing an individual character of a string:


variableName [ index ]

◦ Example:
print(alpha, "starts with", alpha[0])

Output:
abcdefghij starts with a

 22
Indexes
Negative indices count backwards from the end of the string.

index 0 1 2 3 4 5 6 7 8 9
character a b c d e f g h i j

◦ Example:
print(alpha[-1],alpha[-2])

Output:
j i

◦ What will print(alpha[10]) display?

 23
String Looping
Often we want to scan through a string one character at a time.

◦ Example:
alpha = “abcdefghij"

◦ for x in range(len(alpha)):
print(alpha[x])

◦ If we don’t want to keep track of location in the string we can use a simpler
loop:

◦ for x in alpha:
print(x)

 24
String methods
len(string) - number of characters in a string (including spaces)
str.lower(string) - lowercase version of a string
str.upper(string) - uppercase version of a string

Example:
name = "Martin Douglas Stepp"
length = len(name)
big_name = str.upper(name)
print(big_name, "has", length, "characters“)

Output:
MARTIN DOUGLAS STEPP has 20 characters
 25
Lists
Simple list:
L = [1, 2, 3]
A long list:

nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
39, 40]

 26
Lists
Input: We can use eval(input()) to allow the user to enter a list. Here is an
example:

L = eval(input('Enter a list: '))


print('The first element is ', L[0])

Data types Lists can contain all kinds of things, even other lists. For example,
the following is a valid list:

[1, 2.718, 'abc', [5,6,7]]

 27
Lists (Similarities with
strings)
Len — The number of items in L is given by len(L).
In — The in operator tells you if a list contains something.

Here are some examples:


◦ if 2 in L:

◦ print('Your list contains the number 2.')

Indexing and slicing — These work exactly as with strings:

◦ L[0] is the first item of the list L


◦ L[:3] gives the first three items.

 28
Lists Looping
Loops with lists work similarly as with Strings

◦ Example:
L = [1, 2, 3, 4]

◦ for x in range(len(L)):
print(L[x])

◦ If we don’t want to keep track of location in the string we can use a


simpler loop:

◦ for item in L:
print(item)

 29
Lists Built-in-Functions

◦ How to calculate average of values in a list L?

 30
Lists Methods

 31
List Example
Write a program that generates a list L of 50 random numbers between 1 and 100.

from random import randint


L = []
for i in range(50):
L.append(randint(1,100))

An alternative to append is to use the following:


L = L + [randint(1,100)]

 32
Exercise
Write a program that generates a list of 20 random numbers
between 1 and 100.
(a) Print the list.
(b) Print the average of the elements in the list.
(c) Print the largest and smallest values in the list.
(d) Print the second largest and second smallest entries in
the list
(e) Print how many even numbers are in the list.

 33

You might also like