keyboard_arrow_down Python Programming for Beginners
Engr. Lovelyn C. Garcia
data science
Take a while to adjust your bearings. Study the icons above.
There are two major types of cells:
1) Markdown cells - simple text. One can do html tags like BOLD or latex like $\beta$$\beta$.
2) Code cells - cells where we can run code.
Shortcuts
1) CTRL-M then H to see help
2) CTRL-M then S to save notebook
3) CTRL-ENTER to Run Code but stay in the same cell
4) SHIFT-ENTER to Run Code and advance to the next cell
5) You can use TAB to see available functions. You can use SHIFT-TAB repeatedly for the documentation.
Hello CE4C
keyboard_arrow_down 1. My first python script
Print "Hello World"
print('Hello World')
Hello World
Note: the order of instruction matters a lot. Example. try to make a triangle.
print(' /|')
print(' / |')
print(' / |')
print(' /___|')
/|
/ |
/ |
/___|
keyboard_arrow_down 2. Constants
Fixed values such as numbers, letters and strings, are called constants because their value does not change. Run the
program to check the difference between printing a constant numerical value and the constant string.
#print(123)
print('cdm')
cdm
keyboard_arrow_down 2. Variables and Data Types
A variable is simply a name the programmer uses to refer to the computer storage location.
Varaibles are used to hold values.
You cannot use reserved words as variable names/identifiers.
A variable is used in programming to store a memory
import keyword
[Link]
['False',
'None',
'True',
'and',
'as',
'assert',
'async',
'await',
'break',
'class',
'continue',
'def',
'del',
'elif',
'else',
'except',
'finally',
'for',
'from',
'global',
'if',
'import',
'in',
'is',
'lambda',
'nonlocal',
'not',
'or',
'pass',
'raise',
'return',
'try',
'while',
'with',
'yield']
keyboard_arrow_down Strings
Strings may be declared with a single quote (') or double quote ("), some even use triple double quotes("""). One may
use them interchangeable but some prefer to follow a specific format.
#print('CDM')
#print("CDM")
#print("""CDM""")
print('CDM")
File "<ipython-input-12-940053f0c31e>", line 4
print('CDM")
^
SyntaxError: unterminated string literal (detected at line 4)
keyboard_arrow_down Using variable or identifier in storing strings
print('I love to eat Donut')
print('It cost 49 pesos')
I love to eat Donut
It cost 49 pesos
food = 'spaghetti'
price = '150'
print('I love to eat', food,'.' )
print('It cost',price, 'pesos')
I love to eat spaghetti .
It cost 150 pesos
# different ways to write a string
my_name = "Rhey Ann Paz"
print('Rhey Ann Paz')
print(my_name)
print(my_name +','+' ''Engineer')
print('Rhey Ann\nPaz')
print('\tRhey Ann Paz')
Rhey Ann Paz
Rhey Ann Paz
Rhey Ann Paz, Engineer
Rhey Ann
Paz
Rhey Ann Paz
# print in upper case
print(my_name.upper())
RHEY ANN PAZ
# print in lower case
print(my_name.lower())
rhey ann paz
#check if upper or lower
print(my_name.upper())
print(my_name.upper().islower())
RHEY ANN PAZ
False
# find the length of the string
print(len(my_name))
12
Find a letter or character in a string
Note: In a string, the first character starts with 0.
#Find a letter or character in a string
#Note: In a string, the first character starts with 0.
print(my_name[5])
from __future__ import annotations
# Index Function
print(my_name.index('a'))
print(my_name.index(an))
10
#replace function
print(my_name.replace('ann',"lumawag"))
Rhey Ann Paz
keyboard_arrow_down Numeric
Python numeric data type is used to hold numeric values like:
int - hold signed integers of non-limited length
Float - hold floating precision numbers and it is accurate up to 15 decimal places
complex number - holds complex numbers
x =300
print(type(x))
<class 'int'>
y = 123.456
print(type(y))
<class 'float'>
z = 300+3j
print(type(z))
<class 'complex'>
#convert a number to a string
print(str(x))
print(type(str(x)))
print('The price is',x)
300
<class 'str'>
The price is 300
print('The price is',+ x)
The price is 300
print('The price is',x+y)
The price is 423.456
# Find the absolute value
my_num = -5
print(abs(my_num))
# Power Function
print(pow(2,5))
32
# Maximum function (getting the maximum)
print(max(1,45,65,48,2))
65
# Minimum function
print(min(1,45,65,48,2))
# Round function
print(round(3.1818926184186416132))
# import math function (to access more math functions)
from math import *
print(sqrt(36))
print(floor(4.6))
print(ceil(4.6))
6.0
4
5
keyboard_arrow_down String
a sequence of characters. In python it is represented by either a single or double quotes.
x = 'I love Kim Renzy Lumawag'
y = 'I love my Family'
print(x,y)
print(x+y)
print(x,'and',y)
I love Kim Renzy Lumawag I love my Family
I love Kim Renzy LumawagI love my Family
I love Kim Renzy Lumawag and I love my Family
Start coding or generate with AI.
# let us try triple quotes
keyboard_arrow_down Getting Input from A User
input()
name = input('Enter your name: ')
print('Hello', name, "!")
Enter your name: Rhey Ann Paz
Hello Rhey Ann Paz !
Your Turn! Using the input() command, make a program that will output the following: Name and Place are variables.
Hello Lovelyn from Batangas. Welcome to Colegio de Muntinlupa!
name = input('Enter your name: ')
place = input('Enter your place: ')
print('Hello', name, "from", place,'.',"Welcome to colegio de Muntinlupa")
Enter your name: rhey ann
Enter your place: dbg
Hello rhey ann from dbg . Welcome to colegio de Muntinlupa
name = input('Enter your name: ')
age = input('Enter your age: ')
print('My name is', name, 'and I am', age, '.')
Enter your name: rhey ann
Enter your age: 22
My name is rhey ann and I am 22 .
print('My name is{}, and I am {}.'.format(name,age))
My name isrhey ann, and I am 22.
num1 = float(input('Enter a number: '))
num2 = float(input('Enter another number: '))
result = int(num1) + int(num2)
print(result)
Enter a number: 5
Enter another number: 6.2
11
#Using int function
#Using float function
keyboard_arrow_down Let us play mad libs game
A letter from your secret admirer...
first_name = input('Enter your first name: ')
verb1 = input('Enter any verb: ')
subject = input('Enter subject in school: ')
body_part = input('Enter a body part: ')
a_sound = input('Enter a sound: ')
color=input('Enter a color: ')
body_part2 = input('Enter another body part: ')
adjective = input('Enter any adjective: ')
Enter your first name: Rhey Ann
Enter any verb: watching
Enter subject in school: structural theory
Enter a body part: eyes
Enter a sound: laughing
Enter a color: blue
Enter another body part: hands
Enter any adjective: caring
print('Dear',first_name)
print('The first time I saw you my heart', verb1, 'with joy')
print('We were in', subject, 'class and you raised your',body_part, 'to ask a question.')
print('Your voice sounded like', a_sound,'.')
print('Then i noticed your', color, body_part2,'.')
print('It is so', adjective,'!')
Dear Rhey Ann
The first time I saw you my heart watching with joy
We were in structural theory class and you raised your eyes to ask a question.
Your voice sounded like laughing .
Then i noticed your blue hands .
It is so caring !
keyboard_arrow_down List
use square bracket [ ] to create a list
.append(obj), appends a new object at the end of a list
.count(obj), counts the repetitions of a given element in a list
.extend(seq), adds multiple values of another sequence at the end of a list (using a new list to extend the original
list)
.index(obj), finds the indexing location with the first match with a value in the list
.insert(index, obj), inserts an object in the list
.pop(obj=list[-1]), removes an element (last one by default) from the list and returns value of the element
.remove(obj), removes the first match with a given value from the list
.reverse(), reverse elements in a list
.sort([func]), sorting the original list
friends = ['Aaron','Enzzel','Daniel','Nicus']
list1 = [123,'Enzzel','False']
print(friends)
print(list1)
['Aaron', 'Enzzel', 'Daniel', 'Nicus']
[123, 'Aaron', 'False']
#to access the elements in the list
print(friends[1])
Enzzel
# to access the elements backward
print(friends[-1])
Nicus
# to select the last two elements
print(friends[2:])
['Daniel', 'Nicus']
# to add elements in the list
# use 'append' when adding one element only at the end of the list
[Link]('Raelene')
print(friends)
['Aaron', 'Enzzel', 'Daniel', 'Nicus', 'Raelene', 'Raelene', 'Raelene', 'Raelene', 'Raelene']
# to access selected elements
print(friends[2:3])
['Daniel']
print(friends[0:3])
['Aaron', 'Enzzel', 'Daniel']
# to change the element in the list
friends[2]='Den'
print(friends)
['Aaron', 'Enzzel', 'Den', 'Nicus', 'Raelene', 'Raelene', 'Raelene', 'Raelene', 'Raelene']
# using the Extend function
fav_num =[11,24,15,9,4]
[Link](fav_num)
print(friends)
['Aaron', 'Enzzel', 'Den', 'Nicus', 'Raelene', 'Raelene', 'Raelene', 'Raelene', 'Raelene', 11, 24, 15, 9,
# use 'insert' when adding an element at the middle of the list
[Link](3,'kim')
print(friends)
['Aaron', 'Enzzel', 'Den', 'kim', 'Nicus', 'Raelene', 'Raelene', 'Raelene', 'Raelene', 'Raelene', 11, 24,
# use 'remove' the elements
[Link]('Raelene')
print(friends)
['Aaron', 'Enzzel', 'Den', 'kim', 'Nicus', 'Raelene', 'Raelene', 'Raelene', 11, 24, 15, 9, 4]
# use 'clear' to remove all the data on the list
[Link]()
print(friends)
[]
#use 'pop' to remove the last element on the list
[Link](-1)
print(friends)
['Aaron', 'Enzzel', 'Den', 'kim', 'Nicus', 'Raelene', 'Raelene', 'Raelene', 11, 24, 15]
# use 'index' to search a specific element in the list
print([Link]('Raelene'))
# use 'count' to count similar values inside the list
friends = ['Aaron', 'Enzzel', 'Den', 'kim', 'Nicus', 'Raelene', 'Raelene', 'Raelene', 11, 24, 15]
print([Link]('Raelene'))
# use 'sort' the list in ascending order
friends = ['Aaron', 'Enzzel', 'Den', 'kim', 'Nicus', 'Raelene', 'Raelene', 'Raelene']
[Link]()
print(friends)
fav_num =[11,24,15,9,4]
fav_num.sort()
print(fav_num)
['Aaron', 'Den', 'Enzzel', 'Nicus', 'Raelene', 'Raelene', 'Raelene', 'kim']
[4, 9, 11, 15, 24]
# to reverse the list
fav_num.reverse()
print(fav_num)
[24, 15, 11, 9, 4]
# to copy another list
kopya = [Link]()
print(kopya)
[]
print(friends)
print(kopya)
[]
[]
keyboard_arrow_down Tuples
similar to list but they are immutable
use () to create a tuple
cannot use append in tuple
tup = (3,8)
print(tup)
print(tup[1])
tup[1]=61
print(tup)
(3, 8)
8
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-2c6ffc00581b> in <cell line: 0>()
2 print(tup)
3 print(tup[1])
----> 4 tup[1]=61
5 print(tup)
TypeError: 'tuple' object does not support item assignment
Next steps: Explain error
Note: Tuples actually use less space in the memory as opposed to Lists, resulting in faster processing.
keyboard_arrow_down Dictionaries
an unordered sequence of data of key-value pair form.
uses a curly braces {}
webster = {'1':'Rhey-ann-paz','2':'Kim-Renzy-Lumawag'}
print(webster)
webster
{'1': 'Rhey-ann-paz', '2': 'Kim-Renzy-Lumawag'}
{'1': 'Rhey-ann-paz', '2': 'Kim-Renzy-Lumawag'}
Start coding or generate with AI.
# to access the elements in the dictionary
webster['1']
'Rhey-ann-paz'
print('My name is',webster['1'])
My name is Rhey-ann-paz
Arithmetic
Python uses basic arithmetic functions which are normally present on most if not all programming languages.
keyboard_arrow_down Addition
a = 5+3
a
keyboard_arrow_down Subtraction
a = 5-3
a
keyboard_arrow_down Multiplication
a = 5*3
a
15
keyboard_arrow_down Division
a = 5/3
a
1.6666666666666667
keyboard_arrow_down Exponent
a = 5**3
a
125
keyboard_arrow_down Modulus Division
a = 5%3
a
keyboard_arrow_down Integer Division
a = 5//3
a
keyboard_arrow_down Increment
a = 5
a +=1
a
keyboard_arrow_down Decrement
a = 5
a -=1
a
keyboard_arrow_down Comparison Operators
3 >7
False
3<7
True
7 >=7
True
1 <=4
True
3 ==3
True
3 ==4
'love'== 'Live'
False
keyboard_arrow_down Sets
A set is an unordered collection of data with no duplicate elements. It supports operations like union, intersection, or
difference; similar as in Mathematics.
set1 =set(['a','b','c','d','e','f'])
set2 = set(['a','b','x','y','z'])
print(set1)
print(set2)
{'a', 'f', 'b', 'd', 'e', 'c'}
{'a', 'b', 'y', 'x', 'z'}
# intersection
print('\tintersection:', set1 & set2)
#union
print('\tunion:', set1 | set2)
#difference
print('\tdifference:', set1 - set2)
intersection: {'a', 'b'}
union: {'a', 'f', 'b', 'y', 'd', 'x', 'z', 'e', 'c'}
difference: {'e', 'c', 'd', 'f'}
keyboard_arrow_down Your Turn!!! Write the code for
$$ f(x) = \frac{x^2}{x+e^{-x}} $$$$ f(x) = \frac{x^2}{x+e^{-x}} $$
1) x = 2, and e = 2.718 should be equal to 1.8732175014618024
x = 2
e = 2.718
y = ((x**2)/(x+e**-x))
print(y)
1.8732175014618024
keyboard_arrow_down Functions
a self-block of code
it is used when you have a block of statements that need to be executed multiple times within the program.
[Link]
def fahr_to_kelvin(temp):
return ((temp - 32) * (5/9)) + 273.15
fahr_to_kelvin(65)
291.4833333333333
fahr_to_kelvin(456)
508.7055555555555
# Create the function that will greet the user
def pagbati(name):
print('Mabuhay Pilippinas and ikaw', name)
#kapag may check na naka save na yung function
#to call the function
pagbati()
Mabuhay Pilippinas!
pagbati('RheyAnn')
Mabuhay Pilippinas and ikaw RheyAnn
# use 'return' statement - give an information back
def cube(num1):
return num1*num1*num1
print(cube(2))
# another way of storing the output
def cube(num1):
return num1*num1*num1
result = cube(2)
print(result)
#pwede na nasa iisang code lang yung result no need to seperate another code box
# be mindful sa indent para magkaron ng outcome
keyboard_arrow_down Conditional Statements
If Statement
It tells the program to execute a certain part of the code only if a particular condition is true.
if_statement_2.png
# simple statement (simplest) w/out 'what if'
# palaging may colon sa dulo like def
if 'Acts' in ['Matther','Mark','Luke','John']:
print('ayos')
keyboard_arrow_down Your Turn. Create a python program for given problem:
if_statement.png
x = 50
if x < 10:
print('smaller')
if x > 20:
print('Bigger')
print('Finished')
Bigger
Finished
keyboard_arrow_down If Else statement
If Statement: It is used to analyze if the condition at hand is true or false. The code block below it is only
executed when the condition is met.
If Else Statement: This statement is similar to the If statement, but it adds another block of code that is executed
when the conditions are not met. In this article, we will take a look at this statement type and its example.
Nested If: In situations when we have to check more than one condition and execute instructions, nested if it is
used. if_else.png
# make a program that will check if the number is even or odd
num3 = int(input('Please enter a number to check: '))
if num3 %2 == 0:
print('The number is even')
else:
print('The number is odd')
Please enter a number to check: 12
The number is even
keyboard_arrow_down If elif else statement
[Link]
x = 25
y = 50
if x> y:
print('x is greater')
elif x < y:
print('y is greater')
else:
print('the numberis equal')
y is greater
keyboard_arrow_down For Loop Statement
it is used when you need iteration for_loop.png
# Write a program that will display a series of numbers starting from 1 to 15 using the for loop statement
Start coding or generate with AI.
Note: end =' ' appends space instead of newline
keyboard_arrow_down Your Turn!!!!
Write a code that will display the string ' I will be successful one day!' on the screen 5 times using the for loop
statement!
Start coding or generate with AI.
keyboard_arrow_down Challenge:
Write a program that will generate a multiplication table with 12 rows and 12 columns. for_loop1.png
Start coding or generate with AI.
keyboard_arrow_down While Loop
it is used to execute a number of statements or body till the specified condition is true. Once the condition is
false, the control will come out of the loop. while_loop.png
# Write a code that will print ' I will be successful one day' in 5 times using the while loop statement
keyboard_arrow_down Plotting in Python
Start coding or generate with AI.
Start coding or generate with AI.
Start coding or generate with AI.
Start coding or generate with AI.
Start coding or generate with AI.
keyboard_arrow_down Your Turn:
Plot z=f(n,m) =
$$ z= f(n,m) = 9-n^2-m^2 $$$$ z= f(n,m) = 9-n^2-m^2 $$
Start coding or generate with AI.
keyboard_arrow_down 3D Plotting
#wireframe plotting
# surface plotting
# syntax for plotting
keyboard_arrow_down Your turn!!!
Make a plot of the surface $f(x,y)=sin(x)⋅cos(y)for−5≤x≤5,−5≤y≤5$$f(x,y)=sin(x)⋅cos(y)for−5≤x≤5,−5≤y≤5$ using the
plot_surface function. Take care to use a sufficiently fine discretization in x and y to make the plot look smooth.
import [Link] as plt
import numpy as np
Start coding or generate with AI.
JOB WELL DONE PYTHONISTAS!!!!