0% found this document useful (0 votes)
2 views

Python 1

Info about programming using python

Uploaded by

agentsalman1996
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python 1

Info about programming using python

Uploaded by

agentsalman1996
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

Introduction to Python

1

◼ USSAMA YAQUB, DISC 325


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

◼ USSAMA YAQUB, DISC 325 2



Top Skills in Data Science

◼ USSAMA YAQUB, DISC 325 3



◼ USSAMA YAQUB, DISC 325 4

Languages
Some influential ones:
◦ FORTRAN
◦ science / engineering

◦ COBOL
◦ business data

◦ LISP
◦ logic and AI

◦ BASIC
◦ a simple language

◼ USSAMA YAQUB, DISC 325 5



Brief History of Python
Invented in the Netherlands, early 90s by Guido van
Rossum
Named after Monty Python
Open sourced from the beginning
Scalable, object oriented and functional from the
beginning
Used by Google from the beginning
Increasingly popular
“Python is an experiment in how much freedom
programmers need. Too much freedom and
nobody can read another's code; too little and
expressiveness is endangered.”
- Guido van Rossum
Python is popular because
o Code readability
o Large community
o Open-source
o Libraries for everyday programming tasks

◼ USSAMA YAQUB, DISC 325 8



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.

◼ USSAMA YAQUB, DISC 325 9



Programming Basics
Data types:

Common data types are:

o Numeric data types


o Character data types
o Date and time data types
o Boolean data types

◼ USSAMA YAQUB, DISC 325 10



Sequence, Selection (if/else), and Iteration
(loops) – The Building Blocks of Programming
Languages

11

Sequence, Selection, and Iteration are the basic
elements that we use to tell the computer what to
do.

The code will look different depending on the


programming language we use, but the algorithm
will be the same.

◼ USSAMA YAQUB, DISC 325 12



Sequence– the order we want
the computer to execute the
instructions we provide as
programmers.

Most programming languages


simply execute instructions one
after another as they are read –
much like reading a recipe or a
book.

◼ USSAMA YAQUB, DISC 325 13



Selection– selecting which path of an
algorithm to execute depending on
some criteria.

◼ USSAMA YAQUB, DISC 325 14



Iteration– looping or
repeating. Many times, we
want to be able to repeat a set
of operations a specific
number of times or until some
condition occurs.

◼ USSAMA YAQUB, DISC 325 15



Programming Basics
Variable declaration

variable_name = value

variable_name is name of the variable you want to declare. Think


of it as a container containing data.

value is the initial value you want to assign to the variable.

For example, if you want to declare a variable called X and assign


it the value 10, you can do it like this:

X = 10

◼ USSAMA YAQUB, DISC 325 16



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

print Item1, Item2, ..., ItemN


o 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
◼ USSAMA YAQUB, DISC 325 17

Number manipulation
Example:

x = 14 + 16
print(x)

Y = X / 2

print(y)

◼ USSAMA YAQUB, DISC 325 18



input
input : Reads a number from user input.

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


◦ Example:
age = int(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

◼ USSAMA YAQUB, DISC 325 19



Adding comments
x = 14 + 16
print(x)

#dividing the number by 2

print (“Dividing “, x, “ by 2”)


Y = X / 2
print(Y)

◼ USSAMA YAQUB, DISC 325 20



Iteration

◼ USSAMA YAQUB, DISC 325 21



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

for variableName in range(number of times to repeat):


statement to be repeated

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


◦ A part of a for loop that is the loop variable. In the example below, the loop
variable is the variable i.
◦ The output of following program will be the numbers 0, 1, . . . , 99, each
printed on its own line.

for i in range(100):
print(i)

◼ USSAMA YAQUB, DISC 325 ◼22


The for loop
◦ 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

◼ USSAMA YAQUB, DISC 325 23



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!

◼ USSAMA YAQUB, DISC 325 24



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.)

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

◼ USSAMA YAQUB, DISC 325 25



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

print ("The sum of first 10 numbers is", sum)

Output:
?

◼ USSAMA YAQUB, DISC 325 26



while loop
o while loops in Python are employed for executing code indefinitely until a
specified condition is no longer met.
o Hence it is often used when the number of iterations is unpredictable.

while condition:
# code to execute

o Offer more flexibility than for loop as because the condition can be
based on any logical expression.

◼ USSAMA YAQUB, DISC 325 ◼27


while loop
o Continuing with our previous example, we can use while loop to continue to get
user values:

prog_stat = “"
while prog_stat != “Exit":
age = int(input("How old are you? "))
print ("Your age is", age)
print ("You have", 60 - age, "years until retirement")
prog_stat = (input("Enter Exit to stop"))

◼ USSAMA YAQUB, DISC 325 28



Selection

◼ USSAMA YAQUB, DISC 325 29



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.“)

◼ USSAMA YAQUB, DISC 325 30



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

if condition:
statements
elif condition:
statements
else:
statements

◼ USSAMA YAQUB, DISC 325 31



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."

◼ USSAMA YAQUB, DISC 325 32



Exercise
Write a program where if applicant GPA is less than 2.0, application is
denied. If GPA is between 2.0 and 3.0, than waitlist, and finally for GPA
greater than 3.0, application is accepted

◼ USSAMA YAQUB, DISC 325 ◼ 33


Exercise
Create a simple calculator, that takes 2 numbers as input from the user
along with the mathematical operation to perform (+,-,*,/) and displays
the result.

◼ USSAMA YAQUB, DISC 325 ◼34


Number Manipulation
The MOD function
The Mod function (%) in simple terms finds the reminder
So 7%3 will be 1 because when 7 is divided by 3, the reminder is 1
◦ 7 = 3(2) + 1

Examples:
5%2 = 1 (5 = 2*2 + 1)
10%4 = 2 (10 = 4*2 + 2)
20%10 = 0 (20 = 10*2 + 0)
25%13 = 12 (25 = 13*1 + 12)

◼ USSAMA YAQUB, DISC 325 35



Example
The following program checks if the input is odd or even

num = int(input('Enter a number: '))


if num%2 == 0:
print(‘The number is even’)
else:
print(‘The number is odd’)

◼ USSAMA YAQUB, DISC 325 36



Counting
This program gets 5 numbers from the user and counts
how many of those numbers are greater than 10.

count = 0
for i in range(5):
num = int(input('Enter a number: '))
if num>10:
count=count+1
print('There are', count, 'numbers greater than 10.')

◼ USSAMA YAQUB, DISC 325 37



Exercise

Print sum of all odd numbers between 110 and 150


(inclusive)

◼ USSAMA YAQUB, DISC 325 38



Counting
This program counts how many of the squares from 1 to 100
end in a 4.

count = 0
for i in range(1,101):
if (i**2)%10==4:
count = count + 1
print(count)

◼ USSAMA YAQUB, DISC 325 39



Exercise
Write a program that counts how many of the squares of
the numbers from 1 to 100 end in a 4 and how many end in
a 9.

◼ USSAMA YAQUB, DISC 325 40



Summing
This program will add up the numbers from 1 to 100. The way this works
is that each time we encounter a new number, we add it to our running
total sum.

sum = 0
for i in range(1,101):
sum = sum + i
print('The sum is', sum)

◼ USSAMA YAQUB, DISC 325 ◼41


Exercise

Count the number of integers that are multiples of 2 and 3


but not 5 in the first 100 numbers

◼ USSAMA YAQUB, DISC 325 ◼ 42


Lab Assignment

Make a grade calculator with the following conditions


• if percentage is above 90% then A+
• if percentage is between 80% and 89% then A
• if percentage is between 70% and 79% then B
• if percentage is between 60% and 69% then C
• if percentage is between 50% and 59% then D
• below that fail

◼ USSAMA YAQUB, DISC 325 43



Strings and Lists

44

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. """

◼ USSAMA YAQUB, DISC 325 45



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?

◼ USSAMA YAQUB, DISC 325 ◼46


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:

◼ USSAMA YAQUB, DISC 325 47



Indexes
Characters in a string are numbered with index starting at 0:
◦ Example:
s = “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(s, "starts with", s[0])

Output:
abcdefghij starts with a

◼ USSAMA YAQUB, DISC 325 48



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(s[-1],s[-2])

Output:
j i

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

◼ USSAMA YAQUB, DISC 325 49



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

◦ Example:
s = “abcdefghij"

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

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

◦ for x in s:
print(x)

◦ Use <end = “”> to keep output in a single line.


◼ USSAMA YAQUB, DISC 325 50

String Slices
A slice is used to pick out part of a string. It behaves like a combination of
indexing and the range function.

◦ Example:
s = “abcdefghij"

◼ USSAMA YAQUB, DISC 325 51



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
◼ USSAMA YAQUB, DISC 325 ◼52
Lab Assignment

Write a program that asks the user to enter a string and prints out the
number of vowels in the string. Also print the position of these vowels in
the string. Print any punctuation in the string such as ?,!. Also count the
number of parenthesis and whether their order is correctly contained in
the input string.
Following is a sample user input string:
What is going (on) here! Is this the {Python [101]} class?

◼ USSAMA YAQUB, DISC 325 53



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]

◼ USSAMA YAQUB, DISC 325 54



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]]

◼ USSAMA YAQUB, DISC 325 55



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.

◼ USSAMA YAQUB, DISC 325 56



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 list we can use a


simpler loop:

◦ for item in L:
print(item)

◼ USSAMA YAQUB, DISC 325 57



Lists Built-in-Functions

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

◼ USSAMA YAQUB, DISC 325 58



Lists Methods

◼ USSAMA YAQUB, DISC 325 59



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)]

◼ USSAMA YAQUB, DISC 325 ◼60


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 the count of even numbers are in the list.
(f) Print numbers in the list which are multiples of 3.

◼ USSAMA YAQUB, DISC 325 61



Regular Expressions

◼ USSAMA YAQUB, DISC 325 62



Regular expressions
o In Python, you can use the re module to work with regular expressions.
o A regular expression is a pattern that you want to search for or match within a
string.
o For example, the following regular expression pattern matches any string that
contains the word "apple":
import re
text = "I like to eat apples."
x = re.search(“apples", text)
if x:
print("Match found.”)
else:
print("No match found.")

◼ USSAMA YAQUB, DISC 325 63



RegEx Functions
o The re module offers a set of functions that allows us to search a string for a
match:

Function Description
findall Returns a list containing all matches
Returns a Match object if there is a
search
match anywhere in the string
Returns a list where the string has
split
been split at each match
Replaces one or many matches with a
sub
string

◼ USSAMA YAQUB, DISC 325 64



Metacharacters
o Metacharacters are characters with a special meaning:
Character Description
[] A set of characters
Signals a special sequence (can also be used to
\
escape special characters)
. Any character (except newline character)
^ Starts with
$ Ends with
* Zero or more occurrences
+ One or more occurrences
? Zero or one occurrences
{} Exactly the specified number of occurrences
| EitherUSSAMA

or YAQUB, DISC 325 65

Metacharacters
o Find all lower-case characters alphabetically between "a" and "m":

import re
text = "I like to eat apples."
x = re.findall("[a-m]", text)
print(x)

o Find all digit characters:

import re
text = "That will be 59 dollars"
x = re.findall("\d", text)
print(x)
◼ USSAMA YAQUB, DISC 325 66

Regular expressions
# Replace part of a string:
text = "I like to eat apples."
new_text = re.sub(pattern, "banana", text)
print(new_text)

# Split a string:
text = "red, green, blue"
parts = re.split(",", text)
print(parts)

◼ USSAMA YAQUB, DISC 325 67



Regular expressions
o In Python, you can use the re module to work with regular expressions.
o A regular expression is a pattern that you want to search for or match within a
string.
o For example, the following regular expression pattern matches any string that
contains the word "apple":
import re
pattern = r"apple“
text = "I like to eat apples."
match = re.search(pattern, text)
if match:
print("Match found:", match.group())
else:
print("No match found.")
◼ USSAMA YAQUB, DISC 325 68

You might also like