You are on page 1of 25

Week 2: Basic data types, Variables, expressions, inputs and outputs

Computing Programming with


Python
Ronny Estrella
● Basic data types (strings, numbers, booleans)
● Variables and expressions
● Input and output

CLASS
CONTENTS
Introduction

Class Computing Programming with Python

Professor Ronny Estrella (restrella@solbrigde.ac.kr;


ronnyestrella@hotmail.com )

Lecture Time Monday/Wednesday 10:30 am - 12:00 pm

Place Online via Zoom


Assignment 3 Week

● Topics:
a. A basic calculator

Write a python code that prompts


the user to enter two numbers and
then prompts the user to enter an
operator (+, -, *, /). The program
should then perform the
corresponding operation on the two
numbers and output the result.
Assignment 3 Week

● Topics: f-strings

● What is f-strings?
● Examples how we can use
f-strings?
● Why we use it better than only
print() function?
Review Quiz
● What is programming?
● Why programming is important?
● What is code?
● What is anaconda?
● What is python?
● What is the difference between compiler and
interpreter?
● What is IDLE?
Solution
1. Largest and Smallest: Generate twenty random integers from 0 to 100 and output the largest and
smallest integers.
2. Even Integer Output: Generate a single random number, from 0 to 100, then output all the even
integers from 0 to the random number.
3. Odd Integer Output: Generate a single random number, from 0 to 100. If the number is greater than
40 then output all the odd integers from 40 to the random number. If the number is less than 40,
output all the odd integers from 0 to 40.
4. Upload to Smart WSU system your results in a .ipynb or .py format
Exercise 1 Exercise 2 Exercise 3

import random
import random
# Generate twenty random import random
# Generate a single random number
integers between 0 and 100
between 0 and 100
random_integers = # Generate a single random
random_number = random.randint(0,
[random.randint(0, 100) for _ number between 0 and 100
100)
in range(20)] random_number =
random.randint(0, 100)
# Check if the random number is
# Output the largest and
greater than 40
smallest integers # Output all the even integers
if random_number > 40:
largest_integer = from 0 up to and including the
# Output all the odd integers
max(random_integers) random number
from 40 up to and including the
smallest_integer = for i in range(0,
random number
min(random_integers) random_number+1, 2):
for i in range(41,
print(i, end=' ')
random_number+1, 2):
print("Random integers:",
print(i, end=' ')
random_integers)
else:
print("Largest integer:",
# Output all the odd integers
largest_integer)
from 0 to 40
print("Smallest integer:",
for i in range(1, 41, 2):
smallest_integer)
print(i, end=' ')
Python Interpreter
● Interpreter languages
provides an interactive
environment
● Results are printed
directly on the screen
Data Types
Name Type Description

Integers int Whole numbers: 2, 100, 1000

Floating point float With decimal point: 2.3, 45.1

String str A order sequence of characters: ‘Hello’ “Ronny”

Lists list Order sequence of objects [ ‘a’, 100, ‘Ronny’,’2.1’]

Dictionaries dict Key: values pairs :


{“Korea”:”Seoul”,”Japan”:”Tokyo”,”Ecuador”:”Quito”}

Tuples tup Ordered immutable sequence of objects: (10, “a”,2.45)

Sets set Unordered collection of unique objects: {“a”,”b”}

Booleans bool Logical value: True or False


Practice
# Strings
string1 = "Hello, World!"
string2 = 'Python is awesome'

# Numeric data types


integer1 = 42
integer2 = -3
float1 = 3.14
float2 = -2.5

# Boolean data type


boolean1 = True
boolean2 = False

# Print the data types using the type() function


print(type(string1)) # <class 'str'>
print(type(string2)) # <class 'str'>
print(type(integer1)) # <class 'int'>
print(type(integer2)) # <class 'int'>
print(type(float1)) # <class 'float'>
print(type(float2)) # <class 'float'>
print(type(boolean1)) # <class 'bool'>
print(type(boolean2)) # <class 'bool'>
Do the same with the other types of python
# Lists
list1 = [1, 2, 3, 4, 5]
list2 = ["apple", "banana", "cherry"]

# Dictionaries
dict1 = {"name": "John", "age": 30, "city": "New York"}
dict2 = {"apple": 2, "banana": 4, "cherry": 6}

# Tuples
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 2, 3, 4, 5)

# Sets
set1 = {"apple", "banana", "cherry"}
set2 = {1, 2, 3, 4, 5}

# Print the data types using the type() function


print(type(list1)) # <class 'list'>
print(type(list2)) # <class 'list'>
print(type(dict1)) # <class 'dict'>
print(type(dict2)) # <class 'dict'>
print(type(tuple1)) # <class 'tuple'>
print(type(tuple2)) # <class 'tuple'>
print(type(set1)) # <class 'set'>
print(type(set2)) # <class 'set'>
Expressions
It is a data value or set of operations that Which order do you think operations follow?
allow us to compute a value:
● * / % ** have priority over + -
Examples:

● 13 + 20 * 2
● 25 * 2 / 5 But we can force a specific order using parentheses
● 30 - 16
● 40 + 5 + 10
● (3 + 4) * 2
Our expressions use arithmetic operators ● 2 * (5 - 1)

● +
● -
● *
● /
● %
● **
Math commands
If we want to perform calculations python has some useful commands or
functions

Function Description
abs(value) Get absolute value
ceil(value) Rounds up a value
cos(value) Return the cosine value in radians
floor(value) Rounds down a value
log(value) Return the logarithm base e
sqrt(value) Square root of a value
round(value) Round a value to the nearest whole number
min(value1, value2) Return the smaller number between two values
max(value1, value2) Return the bigger number between two values
int(value1) Convert a value into an integer
float(value1) Convert a value into a floating point number

from math import *


Variables
What do you think is a variable?
● A piece of memory that store a value and have a given name
○ Compute an expression results
○ Store a result into a variable
○ Allow us to use that result later into another expression or
program

Syntax:

Given_name = value1

Examples:

namePerson = “Ronny Estrella”


gpa_score = 4.5
classNumber001 = ‘701’
Python Variables Naming Rules
Python is a case-sensitive language, so it must define
(naming) of the variable as proper.

Here are some pythons variables rules :

● A variable name must start with a letter or the


underscore character (like _var or mVar)
● It can only contain alphanumeric characters and
underscores (A-z, 0-9, and _ )
● Don’t use special characters
● Variable names are case-sensitive (var, Var, and
VAR are three different variables)
● Don’t leave white spaces within variables names
● Don’t use common expressions or reserved
words
● Can’t start with a number
Shows text output on the console

print Syntax:
print “Value1”
print value1

You can print several messages or expressions on the


same line

print value1, value2, value3,...., valueN


Let’s practice:

● Store your name into a variable named (name)


● Store your age into a variable named (age),
● Store your country into a variable named (country)
● Store your height into a variable named (height)
● Print the values stored in 3 different lines
○ Print ‘My name is’, then variable name
○ Print “I am”, variable age and ‘years old’
○ Print “I am from” and variable country
○ Print “I am” variable height and “meters tall”
Ask a user to input a number or a string of characters into

input
a variable

Syntax:
value1 = input(“String of characters”)

You can print several messages or expressions on the


same line

print value1, value2, value3,...., valueN


Let’s practice:

● Store your name into a variable named (name)


● Store your age into a variable named (age),
● Store your country into a variable named (country)
● Store your height into a variable named (height)
● Print the values stored in 3 different lines
○ Print ‘My name is’, then variable name
○ Print “I am”, variable age and ‘years old’
○ Print “I am from” and variable country
○ Print “I am” variable height and “meters tall”
Exercise time
Let’s write a code that ask a person the amount of money they have, then reports how many lunches in
SolBridge cafeteria he can have, and how much additional money he/she will need to afford lunches for
a month.
Input Statements

str = input()
print(str)

Str = input(“Enter your name:”)

a = int(input(“Enter a number between 1 to 10: ”))

b = float(input(“Enter a float number: ” ))


Writing Files File Mode Meaning

r Opens a file for reading (default)


open()
Open a file for writing. If a file already exists, it deletes all the existing contents and adds new
● open(filename, mode) w
content from the start of the file.

f = open(‘/docs/mydata.txt’,w) x Open a file for exclusive creation. If the file already exists, this operation fails.

print(f.read()) a Open a file in the append mode and add new content at the end of the file.

f.close() b Open the file in binary mode.

t Opens a file in a text mode (default).

+ Open a file for updating (reading and writing).


Practice time
Write a Python program that allows the user to record their favorite movies
and series into a text file, with one movie or series per line. The program
should ask the user to input the name of a movie or series, and then write it
to a text file called my_favorites.txt. The program should continue to ask the
user for more movies or series until the user enters 'done'. After the user is
finished entering movies and series, the program should close the file and
print a message confirming that the movies and series have been saved to
the file.
Practice time
Write a Python program that allows the user to collect phone numbers and
save them to a text file. The program should ask the user to input the name
and phone number of a contact. The program should then save the contact
information to a text file called phone_book.txt, with each contact on a new
line in the format name:phone. The program should continue to ask the user
for more contacts until the user enters 'done'. After the user is finished
entering contacts, the program should close the file and print a message
confirming that the contacts have been saved to the file.
TAKEAWAYS

● Programming is the process of creating


computer software using a programming
language.
● Python is a high-level, interpreted
programming language that is widely used

Q&A
for various applications, including data
analysis, web development, and machine
learning.
● Python has a simple syntax and is easy to
Every question is welcome be learn for beginners.
free to express your thoughts ● Students should choose an IDE or text editor
to write and execute Python code, such as
PyCharm, Visual Studio Code or Anaconda
Gracias!!!
Thank you
감사합니다

You might also like