Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Python

Uploaded by

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

Python

Uploaded by

redmonter John
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Introduction

 Introduction to python programming


Why Python?
 Each AI programming language has its own perks
that make it better for some applications and less
appropriate for others
 Python, Java, R, Julia, and C++ are currently
leading the list of the top used tools for
development.
 Among the most popular ones are Python, Java, R,
Scala, Lisp, Prolog, Julia, and C++. Languages
such as Rust, MATLAB, and Haskell also offer
certain advantages.
Python
 was developed in 1991 by Guido van Rossum
 as a high-level, interpreted, and object-oriented
programming language
 promotes code readability and simplicity principles
 Python has established itself as the most popular
language among AI developers. Why?
 Python is well suited for data collection, analysis,
modeling, and visualization.
 good support for accessing all major database types.
Cont..
 The language has an extensive ecosystem of
libraries and frameworks for AI development.
 the most popular libraries machine learning
and deep learning written in Python are
 TensorFlow,
 Scikit-Learn,
 Keras, Pandas,
 matplotlib, and PyTorch.
Cont..
Pros: Cons:
 Easy to learn  Slow
 Code readability  High memory usage
 Simplicity  Errors appear at runtime
 Community support

Top use cases:


 Server backend
 Machine learning frameworks
 Data science
 Visualization
Introduction to Python
Topics that will be covered

 Installing Python  While loops


 Variable  Dictionaries
 Loops  Tex files
 Numbers  Function
 If statement  Object
 String  oriented programming
 Lists
Installing Python
 download the latest version of Python
(version 3.9 as of this lecture)
IDLE is a simple integrated development
environment (IDE) that comes with Python.

Some of the IDE


 Pycharm
 Python shell
 Anaconda
 Jupyter Note Book
A first program

temp = eval (input(‘Enter a temperature in Celsius: ‘))


print(‘In Fahrenheit, that is’, 9/5*temp+32)

program that computes the average of two


numbers that the user enters:
num1 = eval(input('Enter the first number: '))
num2 = eval(input('Enter the second number: '))
print('The average of the numbers you entered is', (num1+num2)/2)
Getting input
The basic structure is
variable name = input(message to user)

Eg.
name = input('Enter your name: ')
print('Hello, ', name)
Variable
Variable names
There are just a couple of rules to follow when naming
your variables.
 Variable names can contain letters, numbers, and the
underscore.
 Variable names cannot contain spaces.
 Variable names cannot start with a number.
 Case matters for instance, temp and Temp are
different.
For loops
There are several ways to repeat things in Python, the most
common of which is the for loop.

The structure of a for loop is as follows:

for variable name in range( number of times to repeat ):


statements to be repeated
eg.
for i in range(3):
num = eval(input('Enter a number: '))
print ('The square of your number is', num*num)
print('The loop is now done.')
for i in range(3):
print(i+1, '-- Hello')
Output
1 -- Hello
2 -- Hello
3 -- Hello

python set the variable i0


The range function
The value we put in the range function determines how
many times we will loop. The way range
works is it produces a list of numbers from zero to the
value minus one.
Statement Values generated
range(10) --------0,1,2,3,4,5,6,7,8,9
range(1,10) -----1,2,3,4,5,6,7,8,9
range(3,7) -----3,4,5,6
range(2,15,3) -------2,5,8,11,14
range(9,2,-1) -------9,8,7,6,5,4,3
A Trickier Example
The program below prints a rectangle of stars that
is 4 rows tall and 6 rows wide.
for i in range(4):
print(‘*’ *6)
Ex. Write program that Calculate Fibonacci
sequence
Math Operators
Here is a list of the common operators in Python:
Operator Description
+ addition
- subtraction
* multiplication
/ division
** exponentiation
// integer division
% modulo (remainder)
Random numbers
from random import randint -- randint function from random class
from random import randint
x = randint(1,10)
print('A random number between 1 and 10: ', x)
Math functions
To get help about math class
>>>import math
>>> dir(math)

Ex.
Write a program that generates a random number, x, between 1
and 50, a random number y between 2 and 5, and computes xy
.
If statements
from random import randint
num = randint(1,10)
guess = eval(input('Enter your guess: '))
if guess==num:
print('You got it!')
The comparison operators are ==, >, <, >=, <=, and !=.
That last one is for not equals.
Order of operations In terms of order of operations, and
is done before or
grade = eval(input('Enter your score: '))
if grade>=90:
print('A')
elif grade>=80:
print('B')
elif grade>=70:
print('C')
elif grade>=60:
print('D'):
else:
print('F')
Exercise
Write a program that asks the user to enter a number and prints
out all the divisors of that number.
Counting
Very often we want our programs to count how many times something
happens.
count = 0
for i in range(10):
num = eval(input('Enter a number: '))
if num>10:
count=count+1
print('There are', count, 'numbers greater than 10.')
A program counts how many of the squares from 12 to 100 2
end in a
4.
count = 0
for i in range(1,101):
if (i**2)%10==4:
count = count + 1
print(count)
Strings
Strings are a data type in Python for dealing with text. Python has a
number of powerful features for manipulating strings.
A string is created by enclosing text in quotes. You can use either
single quotes, ', or double quotes, ". A triple-quote can be used for
multi-line strings.
s = 'Hello'
t = "Hello"
m = """This is a long string that is
spread across two lines.""“
num = (int)(input('Enter a number: ')) # to insert number
string = input('Enter a string: ') # to insert string
Length --- len(variable name)
Concatination ------ + operator
Repeatition ----- * operator are used
Example 2 The + operator can be used to build up a
string, piece by piece
s=‘'
for i in range(10):
t = input('Enter a letter: ')
if t=='a' or t=='e' or t=='i' or t=='o' or t=='u':
s=s+t
print(s)
The in operator
The in operator is used to tell if a string contains something. For
example:
if 'a' in string:
print('Your string contains the letter a.')
You can combine in with the not operator to tell if a string does not
contain something:
if ';' not in string:
print('Your string does not contain any semicolons.')

if t=='a' or t=='e' or t=='i' or t=='o' or t=='u':


Using the in operator, we can replace that statement with the
following:
if t in 'aeiou':
Indexing
Statement Result Description
s[0] P first character of s
s[1] y second character of s
s[-1] n last character of s
s[-2] o second-to-last character of s
Slices
A slice is used to pick out part of a string
index: 0 1 2 3 4 5 6 7 8 9
letters: a b c d e f g h i j
The basic structure is
string name[starting location : ending location+1]
s[2:5] -> cde characters at indices 2, 3, 4
s[ :5] -> abcde first five characters
s[5: ] -> fghij characters from index 5 to the end
s[-2: ] -> ij last two characters
s[ : ] -> abcdefghij entire string
s[1:7:2] -> bdf characters from index 1 to 6, by twos
s[ : :-1] ->jihgfedcba a negative step reverses the string
Python strings are immutable, which means we can’t
modify any part of them.
S[0]=‘a’ abdcdef
s = s[:4] + 'X' + s[5:]
for i in range(len(s)):
print (s[i])
String Method
Method Description
lower()  a string with every letter of the original in lowercase
upper()  s a string with every letter of the original in uppercase
replace(x,y)  a string with every occurrence of x replaced by y
count(x)  counts the number of occurrences of x in the string
index(x)  the location of the first occurrence of x
isalpha()  True if every character of the string is a letter
Example
Program that check whether the email address is proper email
or not
s = input('Enter some text: ')
Flag=0
for i in range(len(s)):
if s[i]=='a':
print(‘proper email address’)
break
Flag = 1
If(Flag==0):
print(‘improper email address’)
Write a program that removes all capitalization and common punctuation from a
string s.
s = s.lower()
for c in ',.;:-?!()\'"':
s = s.replace(c, '')
Example . A simple and very old method of sending secret messages is
the substitution cipher.
alphabet = 'abcdefghijklmnopqrstuvwxyz'
key = 'xznlwebgjhqdyvtkfuompciasr'
secret_message = input('Enter your message: ')
secret_message = secret_message.lower()
for c in secret_message:
if c.isalpha():
print(key[alphabet.index(c)],end='')
else:
print(c, end='')
Lists
Creating lists Here is a simple list:
L = [1,2,3]
The empty list is [ ].
Printing lists You can use the print function to print the entire contents of a list.
L = [1,2,3]
print(L)
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]]
Looping — The same two types of loops that work for strings also work for lists.
print out the items of a list, one-by-one, on separate lines.
for i in range(len(L)):
print(L[i])
List methods
Here are some list methods:
Method Description
append(x) adds x to the end of the list
sort() sorts the list
count(x) returns the number of times x
occurs in the list
index(x) returns the location of the first
occurrence of x
reverse() reverses the list
remove(x) removes first occurrence of x
from the list
pop(p) removes the item at index p and
returns its value
insert(p,x) inserts x at index p of the list
Example 6 Here is a program to play a simple quiz game.
num_right = 0
# Question 1
print('What is the capital of France?', end=' ')
guess = input()
if guess.lower()=='paris':
print('Correct!')
num_right+=1
else:
print('Wrong. The answer is Paris.')
print('You have', num_right, 'out of 1 right')
#Question 2
print('Which state has only one neighbor?', end=' ')
guess = input()
if guess.lower()=='maine':
print('Correct!')
num_right+=1
else:
print('Wrong. The answer is Maine.')
print('You have', num_right, 'out of 2 right,')
questions = ['What is the capital of France?',
'Which state has only one neighbor?']
answers = ['Paris','Maine']
num_right = 0
for i in range(len(questions)):
guess = input(questions[i])
if guess.lower()==answers[i].lower():
print('Correct')
num_right=num_right+1
else:
print('Wrong. The answer is', answers[i])
print('You have', num_right, 'out of', i+1, 'right.')
Lists and the random module
There are some nice functions in the random module that work on lists.
Function Description
choice(L) picks a random item from L
sample(L,n) picks a group of n random items from L
shuffle(L) Shuffles the items of L
Here is a nice use of shuffle to pick a random ordering of players
in a game.
from random import shuffle
players = ['Joe', 'Bob', 'Sue', 'Sally']
shuffle(players)
for p in players:
print(p, 'it is your turn.')
# code to play the game goes here...
split
The split method returns a list of the words of a string.
The method assumes that words are separated by whitespace, which can be either
spaces, tabs or newline characters.
Here is an example:
s = 'Hi! This is a test.'
print(s.split())
Here is a program that counts how many times a certain word occurs in a string.
from string import punctuation
s = input('Enter a string: ')
for c in punctuation:
s = s.replace(c, '')
s = s.lower()
L = s.split()
word = input('Enter a word: ')
print(word, 'appears', L.count(word), 'times.')
Two-dimensional lists
There are a number of common things that can be represented by
two-dimensional lists, like a Tictac-toe board or the pixels on a
computer screen. Here is an example:
L = [[1,2,3],[4,5,6], [7,8,9]]
Indexing
We use two indices to access individual items. To get the entry in
row r, column c, use the following:
L[r][c]

for r in range(10):
for c in range(5):
print(L[r][c], end=" ")
print()
While loops
temp = 0
while temp!=-1000:
temp = eval(input('Enter a temperature (-1000 to quit): '))
print('In Fahrenheit that is', 9/5*temp+32)

A simple program that played a simple random number guessing game.

from random import randint


secret_num = randint(1,10)
guess = 0
while guess != secret_num:
guess = eval(input('Guess the secret number: '))
print('You finally got it!')
The else statement
There is an optional else that you can use with break statements.
The code indented under the else gets executed only if the loop
completes without a break happening.

for i in range(10):
num = eval(input('Enter number: '))
if num<0:
print('Stopped early')
break
else:
print('User entered all ten values')
from random import randint
secret_num = randint(1,100)
for num_guesses in range(5):
guess = eval(input('Enter your guess (1-100): '))
if guess < secret_num:
print('HIGHER.', 5-num_guesses, 'guesses left.\n')
elif guess > secret_num:
print('LOWER.', 5-num_guesses, 'guesses left.\n')
else:
print('You got it!')
break
else:
print('You lose. The correct number is', secret_num)
Here is an example that tells a person born on
January 1, 1991 how old they are in 2010.
birthday = 'January 1, 1991'
year = int(birthday[-4:])
print('You are', 2021-year, 'years old.')
String formatting
uses the format method of strings.
Formatting integers To format integers, the formatting code is {:d}. Putting a
number in front of the d allows us to right-justify integers.
Here is an example:
print('{:3d}'.format(2))
print('{:3d}'.format(25))
print('{:3d}'.format(138))
2
25
138
To center integers instead of right-justifying, use the ^ character, and to left-justify,
use the < character.
print('{:^5d}'.format(2))
print('{:^5d}'.format(222))
print('{:^5d}'.format(13834))
2
122
13834
Formatting floats To format a floating point number, the formatting
code is {:f}. To only display
the number to two decimal places, use {:.2f}.
Formatting strings To format strings, the formatting code is {:s}.
Here is an example that centers
some text:
print('{:^10s}'.format('Hi'))
print('{:^10s}'.format('there!'))
Hi
there!
To right-justify a string, use the > character:
print('{:>6s}'.format('Hi'))
print('{:>6s}'.format('There'))
Hi
there!
Dictionaries
A dictionary is a more general version of a list
Here is a dictionary of the days in the months of the year:
days = {'January':31, 'February':28, 'March':31, ‘
April':30,’May':31, 'June':30, 'July':31,
'August':31,'September':30, 'October':31,
'November':30, 'December':31}

for key in days:


print(days[key])
Example 1 You can use a dictionary as an actual dictionary
of definitions:
d = {'dog' : 'has a tail and goes woof!',
'cat' : 'says meow',
'mouse' : 'chased by cats'}

Here is an example of the dictionary in use:


word = input('Enter a word: ')
print('The definition is:', d[word])

Output
Enter a word: mouse
The definition is: chased by cats
Functions
Functions are defined with the def statement.
The statement ends with a colon, and the code that is part of
the function is indented below the def statement.

def print_hello():
print('Hello!')

print_hello()
print('1234567')
print_hello()
Arguments
We can pass values to functions. Here is an example:
def print_hello(n):
print('Hello ' * n)
print()
print_hello(3)
print_hello(5)
times = 2
print_hello(times)
Returning values
We can write functions that perform calculations and return a result.
Example 1 Here is a simple function that converts temperatures from Celsius to
Fahrenheit.
def convert(t):
return t*9/5+32
print(convert(20))
Default arguments and keyword arguments
You can specify a default value for an argument.
This makes it optional, and if the caller decides not to use it,
then it takes the default value. Here is an example:
def multiple_print(string, n=1)
print(string * n)
print()
multiple_print('Hello', 5)
multiple_print('Hello')
def fancy_print(text, color='black', background='white',
style='normal', justify='left'):
Object-Oriented Programming
 everything is an object
 A class is a template for objects. It contains the code for all the
object’s methods.
class Example:
def __init__(self, a, b):
self.a = a
self.b = b
def add(self):
return self.a + self.b
e = Example(8, 6)
print(e.add())
Python labraries/ packages

 Pandas
 Numpy
 Scipy
 Matplotlib
 Seaborn
 Scikit learn
 Tensorflow
 Keras

You might also like