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

lbobgdt-03-Intro Programming python

The document provides an introduction to Python programming, covering its history, basic concepts, and syntax. It explains scalar objects, variables, operators, and the differences between compiled and interpreted languages. Additionally, it includes examples of Python code, such as printing 'Hello World!' and manipulating data types.

Uploaded by

kahetrahd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

lbobgdt-03-Intro Programming python

The document provides an introduction to Python programming, covering its history, basic concepts, and syntax. It explains scalar objects, variables, operators, and the differences between compiled and interpreted languages. Additionally, it includes examples of Python code, such as printing 'Hello World!' and manipulating data types.

Uploaded by

kahetrahd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

1/14/2025

BIGDATA
Big Data Techniques
and Technologies

Bobby Reyes

Introduction to Programming
with Python
Scalar Objects (int, float, complex, bool, string, NoneType)
Operators and Precedence of Operators
Variables, Assignment statement
print() statement
input() statement

1
1/14/2025

What is Python?
◼ Python…
◼ …is a general purpose interpreted programming language.
◼ …is a language that supports multiple approaches to software
design, principally structured and object-oriented
programming.
◼ …provides automatic memory management and garbage
collection
◼ …is extensible
◼ …is dynamically typed.

Some History
◼ “Over six years ago, in December 1989, I was
looking for a "hobby" programming project that
would keep me occupied during the week around
Christmas… I chose Python as a working title for
the project, being in a slightly irreverent mood
(and a big fan of Monty Python's Flying Circus).”
–Python creator Guido Van Rossum, from the foreword
to Programming Python (1st ed.)

◼ Goals:
◼ An easy and intuitive language just as powerful as major
competitors
◼ Open source, so anyone can contribute to its development
◼ Code that is as understandable as plain English
◼ Suitability for everyday tasks, allowing for short
development times

2
1/14/2025

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.

Python Programs

▪ a program is a sequence of definitions and commands


◦ definitions evaluated
◦ commands executed by Python interpreter in a shell
▪ commands (statements) instruct interpreter to do
something
▪ can be typed directly in a shell or stored in a file that is read
into the shell and evaluated

3
1/14/2025

Compiling and Interpreting


◼ Two basic approaches in executing a program in a prog. language:
◼ Compiler: Many languages require you to compile (translate)
your program into a form that the machine understands.
compiler execute
source code byte code output
Hello.java Hello.class

◼ Interpreter: Python is instead directly interpreted into


machine instructions.
interpreter
source code output
Hello.py

Compiling vs. Interpreting


Compiled Interpreted
▪ Faster programs ▪ Slower programs
▪ Compiled code runs directly on CPU ▪ Sometimes as fast as
▪ Can communicate directly with compiled, rarely faster
hardware ▪ Faster development
▪ Longer development ▪ Easier debugging
▪ Edit / compile / test cycle is longer! ▪ Debugging can stop
▪ Harder to debug anywhere, swap in new
code, more control over
▪ Usually requires a special compilation
state of program
▪ (almost always) takes more code to get
▪ (almost always) takes less
things done
code to get things done
▪ More control over program behavior
▪ Less control over program
behavior

4
1/14/2025

The Python Interpreter


Install Python,
Open a terminal (cmd window)
and Run the python interpreter:
• Python is an interpreted
language C:\> python
Python 3.11.4 (default: …
• The interpreter provides Type “help”, “copyright”, …
an interactive
>>> ← python interpreter prompt
environment to play with
the language >>> 3 + 7
10
• Outputs and Results of
expressions are printed >>> 3 < 15
on the screen True
>>> 'print me'
'print me'
>>> print('print me’)
print me
>>>

Hello, World!
◼ Install Anaconda3 and launch JupyterLab. In JupyterLab,
open a Console and enter the following code:
print("Hello World!")

▪ Then press Shift+Enter to execute.


Output:
Hello World!
◼ Open a Text File (editor) and enter the following code:
print("Hello World!")

Save file as hello.py.


◼ To execute, type %run hello.py in a console.
◼ Congratulations! You have written your first Python program!

5
1/14/2025

Hello World!
◼ In a Jupyter Notebook:
print("Hello World!") ← in Code cell
Hello World! ← Output

◼ To execute the Hello, World! (hello.py) python script:


%run hello.py
Hello World!

Google Colab
◼ Can also work with a hosted Jupyter Notebook service,
e.g. colab.google.com

6
1/14/2025

Objects
OBJECT
▪ programs manipulate data objects
S
▪ objects have a type that defines the kinds of things
programs can do to them
◦ Ana is a human so she can walk, speak English, etc.
◦ Chewbacca is a wookie so he can walk, “mwaaarhrhh”, etc.
▪ objects are
◦ scalar (cannot be subdivided)
◦ non-scalar (have internal structure that can be accessed)

Scalar Objects
SCALAR
▪ int – represent integers, ex. 5
OBJECTS
▪ float – represent real numbers, ex. 3.27
▪ complex – represent complex numbers, ex. 3.27 + 2j
▪ bool – represent Boolean values True and False
▪ str – represent String, a sequence of characters
enclosed in “” or ‘’, ex. “This is it!”
▪ NoneType – special and has one value, None
▪ can use type()function to see the type of an object

>>> type(5)
int
>>> type(3.0)
float

7
1/14/2025

Numbers: Integers

◼ Integer – represents
whole numbers,
positive or negative, >>> 132224
without decimals, of 132224
unlimited length >>> 132323 ** 4
306578259430545516241
>>>

Numbers: Floating Points

◼ Floating point numbers >>> 1.23232


represent real numbers 1.23232
with decimal points >>> print(1.23232)
◼ int(x) converts x to an 1.23232
integer >>> 1.3E7
13000000.0
◼ float(x) converts x
>>> int(2.0)
to a floating point
2
◼ The interpreter >>> float(2)
shows a lot of digits 2.0

8
1/14/2025

Numbers: Complex
◼ Built into Python
◼ A complex number comprises a
real part and an imaginary part
◼ Denoted as a + bj, where
a is the real part, >>> x = 3 + 2j
b is the imaginary part, and >>> y = -1j
>>> x + y
j is the imaginary unit (3+1j)
◼ Same operations are supported >>> x * y (2-3j)
>>> z = complex(2,5)
as integer and float >>> z
◼ Use complex() function to (2+5j)
create a complex data type or
convert / cast into complex data
type

String Literals
◼ think of as a sequence of case sensitive characters
◼ Can use single or double quotes, and
three quotes for a multi-line string
◼ can compare strings with ==, >, < etc.

>>> 'I am a string'


'I am a string'
>>> "So am I!"
'So am I!’
>>> '''This is the first line.
Here is the second line.'''
'This is the first line.\nHere is the second line.'

9
1/14/2025

Type Conversions (Cast)


TYPE CONVERSIONS
▪(CAST)
can convert object of one type to another
▪ float(3) converts integer 3 to float 3.0
▪ int(3.9) truncates float 3.9 to integer 3

Printing to Console

▪ to show output from code to a user, use print function

In [11]: 3+2
Out[11]: 5
PRINTING TO CONSOLE
In [12]: print(3+2)
5

10
1/14/2025

Expressions

▪ combine objects and operators to form expressions


▪ an expression has a value, which has a type
▪ syntax for a simple expression
<object> <operator> <object>

Operators on ints and floats


◼ Arithmetic operators we will use:
+ - * / addition, subtraction/negation, multiplication, division
// % integer division (quotient), modulus (a.k.a. remainder)
** exponentiation

▪ i+j → the sum


if both are ints, result is int
▪ i-j → the difference if either or both are floats, result is float
▪ i*j → the product
▪ i/j → division result is float

▪ i//j → integer division; the quotient when i is divided by j


▪ i%j → modulus; the remainder when i is divided by j
▪ i**j → exponentiation; i to the power of j

11
1/14/2025

A quick note on the


increment operator shorthand
▪ Python has a common idiom that is not necessary, but
which is used frequently and is therefore worth noting:
x += 1
Is the same as:
x=x+1 SIMPLE OPERATIONS
▪ This also works for other operators:
x += y # adds y to the value of x
x *= y # multiplies x by the value y
x -= y # subtracts y from x
x /= y # divides x by y

Precedence of Operators
▪ precedence: Order in which operations are evaluated
▪ PEMDAS rule:
▪ Parentheses used to tell Python to do these operations first
** Exponentiation has a higher precedence
* / // % Multiplication / Division
Addition / Subtraction
SIMPLE OPERATIONS
+ -

◦ If at same level, operations evaluated left to right

◦ Thus 1 + 3 * 4 is 13

◦ Exercise: What is the value of the following expressions?


1 + 2 * 3 ** 4
10 / 4 // 3
10 // 4 / 3

12
1/14/2025

String Concatenation

◼ + is overloaded to do
concatenation
>>> x = 'hello'
>>> x = x + ' there'
>>> x
'hello there'

Substrings and Methods


•square brackets used to perform indexing into a
string to get the value at a certain index/position
s = "abc"
index: 0 1 2  indexing always starts at 0
index: -3 -2 -1  last element always at index -1

>>> s = '012345'
>>> s[3] •len(String) – returns the length
'3' (number of characters) in the String
>>> s[1:4]
'123' •str(Object) – returns a String
>>> s[2:] representation of the Object
'2345'
>>> x='string'; len(x)
>>> s[:4]
6
'0123'
>>> s[-2] >>> str(10.3)
'4' '10.3'

13
1/14/2025

String Manipulation

▪ can slice strings using [start:stop:step]


▪ if give two numbers, [start:stop], step=1 by default
▪ you can also omit numbers and leave just colons
s = "abcdefgh"
s[3:6] → evaluates to "def", same as s[3:6:1]
s[3:6:2] → evaluates to "df"
s[::] → evaluates to "abcdefgh", same as s[0:len(s):1]
s[::-1] → evaluates to "hgfedbca", same as s[-1:-(len(s)+1):-1]
s[4:1:-2]→ evaluates to "ec"

Math Commands
◼ Python has useful commands (or called functions) for performing
calculations.
Command name Description Constant Description
abs(value) absolute value e 2.7182818...
ceil(value) rounds up pi 3.1415926...
cos(value) cosine, in radians
floor(value) rounds down
log(value) logarithm, base e
• Note: python is
log10(value) logarithm, base 10 case-sensitive
max(value1, value2) larger of two values • abs is different from
min(value1, value2) smaller of two values Abs, ABS
round(value) nearest whole number
sin(value) sine, in radians
sqrt(value) square root

◼ To use many of these commands, you must write the following at


the top of your Python program:
from math import *

14
1/14/2025

Variables
◼ variable: A named piece of memory that can store a value.
◼ Usage:
◼ Compute an expression's result,

◼ store that result into a variable,

◼ and use that variable later in the program.


In memory:
◼ Variable names: x
◼ Must begin with a letter (a - z, A - B) or underscore _
◼ Other characters can be letters, numbers or _
◼ Are case sensitive: capitalization counts!
◼ Can be any reasonable length
◼ By convention, it is common to have:
◼ Variable names that start with lower case letters, and
◼ Class names beginning with a capital letter
➢ but you can do whatever you want.
◼ Some keywords are reserved and cannot be used as variable
names due to them serving an in-built Python function
◼ i.e. and, while, continue, break

Abstracting Expressions
▪ why give names to values of expressions?
▪ to reuse names instead of values
▪ easier to change code later

ABSTRACTING
pi = 3.14159
EXPRESSIONS
radius = 2.2
area = pi*(radius**2)

◼ Python is dynamically typed


➢ the type of the variable is derived from the value
it is assigned.

15
1/14/2025

Variables
◼ assignment statement*: Stores a value into a variable.
* binds name to value
◼ Syntax:
name = value
◼ Examples: In memory:
x = 5 x 5
gpa = 3.14
gpa 3.14

◼ A variable that has been given a value can be used in expressions.


x + 4 is 9
▪ Assignment can be done en masse:
x = y = z = 1
▪ Multiple assignments can be done on one line:
x, y, z = 1, 2.39, 'cat'

◼ Exercise: Evaluate the quadratic equation for a given a, b, and c.

Programming vs Math
▪ in programming, you do not “solve for x”
In memory:

pi 3.14159

CHANGING BINDINGS
pi = 3.14159
radius 2.2

radius = 2.2 area


area = pi*(radius**2)
radius = radius+1

16
1/14/2025

Changing Bindings
▪ can re-bind variable names using new assignment
statements
▪ previous value may still be stored in memory but lost
the handle for it
CHANGING BINDINGS
▪ value for area does not change until you tell the
computer to do the calculation again
3.14
pi = 3.14159 pi
2.2
radius = 2.2 radius
area = pi*(radius**2) area 3.2

radius = radius+1 15.1976

Swapping Values of Variables


▪To swap the values of two variables (say x and y),
normally require the use of a temporary variable

>>> print(x,y)
10 20
>>> temp = x
>>> x = y
>>> y = temp
>>> print(x,y)
20 10

17
1/14/2025

Strings
▪ strings are “immutable” – cannot be modified
s = "hello"
s[0] = 'y' → gives an error
s = 'y'+s[1:len(s)] → is allowed,
s bound to new object

"hello"

"yello"

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 = 45
print("You have", 65 – age, "years until retirement")

Output:
Hello, world!
You have 20 years until retirement

18
1/14/2025

Example: print Statement

• Elements separated by commas print with a space between them

>>> print('hello', 'there')


hello there

• The end parameter can be used to append any string at the end
of the output of the print statement in python.

>>> print('hello’, end=''); print('there’)


hellothere

String Formatting
◼ Similar to C’s printf
<formatted string> % <elements to insert>
◼ Can usually just use %s for everything,
it will convert the object to its String representation.

>>> "One, %d, three" % 2


'One, 2, three'
>>> "%d, two, %s" % (1,3)
'1, two, 3'
>>> "%s two %s" % (1, 'three')
'1 two three'
>>>

19
1/14/2025

input
◼ input : Takes input from the user.
◼ You can assign (store) the result of input into a variable.
◼ Input read is returned as a string; typecast / convert input string to
correct type before using in arithmetic operations
◼ Example:
age = int(input("How old are you? "))
print("Your age is", age)
print("You have", 65–age, "years until retirement")

Output:
How old are you? 53
Your age is 53
You have 12 years until retirement

◼ Exercise: Write a Python program that prompts the user for his/her
amount of money, then reports how many Nintendo Wiis the person
can afford, and how much more money he/she will need to afford an
additional Wii.

input: Example
input.py
print("What's your name?")
name = input("> ")

print("What year were you born?")


birthyear = int(input("> "))

print("Hi ", name, "!", "You are ", 2024 –birthyear, “y.o.”)

% python input.py
What's your name?
> Michael
What year were you born?
>1980
Hi Michael! You are 44 y.o.

20
1/14/2025

Coding Best Practices & Guidelines


1. Focus on Code readability
2. Choose meaningful variable and function names
• Acceptable naming conventions:
Camel Case (e.g. userName) vs Snake Case (e.g. user_name)
3. Avoid using a Single Identifier for multiple purposes
4. Use comments and whitespace effectively
5. Use indentation and consistent formatting
6. Prioritize Documentation (include README.txt file, docstrings)
7. Efficient Data Processing; Avoid unnecessary loops and iterations
8. Effective Version Control and Collaboration
9. Try to formalize Exception Handling (try-catch block)
10. Standardize Headers for Different Modules

21

You might also like