0% found this document useful (0 votes)
9 views68 pages

M01-Lecture Notes Python 1

The document provides an overview of Python's basic syntax, covering variables, data types, functions, and comments. It explains how to create and manipulate variables, the rules for naming them, and the use of data types such as strings, numbers, and booleans. Additionally, it discusses string operations, including indexing, slicing, and the use of arithmetic operators.

Uploaded by

Berly Brigith
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)
9 views68 pages

M01-Lecture Notes Python 1

The document provides an overview of Python's basic syntax, covering variables, data types, functions, and comments. It explains how to create and manipulate variables, the rules for naming them, and the use of data types such as strings, numbers, and booleans. Additionally, it discusses string operations, including indexing, slicing, and the use of arithmetic operators.

Uploaded by

Berly Brigith
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/ 68

Python Basic Syntax

© Faculty of Management
Python Basic Syntax
1. Variables
2. Data Types
3. Function
4. Comments
Variables
Variables in Python are named references to values stored in memory.
• Variables store and manipulate data
• Variables can hold various data types:
• numbers
• strings
• lists
• Variables act as containers
• New values can be assigned to variables
Creating Variables
Variables are containers to hold data values.
• Variable names are the labels for data containers.
• You can create a variable by specifying a name and assigning a value
using assignment operator (=).
variable_name=value

first_name="Hyunji" print(first_name)
Hyunji Julia
first_name="Julia" print(first_name)
first_name first_name
Rules for Variables
Rules for Python variables:
• Cannot start with a number
• Must start with a letter or the underscore character
• Only contain alpha-numeric characters and underscores
• A-z, 0-9, and _
• Case-sensitive
• age, Age, and AGE are different variables
• Can use either a short name (like x and y) or a more descriptive
name (e.g., age, carname, total_volume)
Data Types
String (Str) (e.g., ) 'Hello', "Hello World"
• String variables can be defined using single quotes
or double quotes.
Number (e.g., ) 99, 173.4
Boolean (e.g., ) True, False
Data Types & Variables
We do not need to declare types of variables.
We can change the data types after the variable has been defined.

x = 4 # x is of type int

x = "Sally" # x is now of type str 4 Sally

x x
What will be the type of variable x?
type(x)
type()
type() function
type(1)
# Output: int

type(3.7)
# Output: float

type("Hello") int = integer


#Output: str str = string
Function
Group of related statements that perform a specific task.

[Example] Input/Output Function


There are various kinds of input and output devices to effectively
process 'input → process → output'.

input() print()
print()
The print() function prints the specified message to the screen or other
standard output devices.

print(object1, object2, object3, ….)

• The object will be converted to a string before being printed.


• You can include as many objects as you like.

print("Name:", "Hyunji")
# Output
# Name: Hyunji
input()
The input() function is used when receiving data from the user at the
console (command prompt).

input(prompt)
prompt: A string representing a default message before the input.

input("What's your name?")


>>>
What’s your name? Hyunji
Comments

Hashtag
Number Sign
Octothorpe
Sharp
Pound Sign
Tic-Tac-Toe Sign
Comment Uses
Comments can be used to:
• Explain Python code
#This is a comment
print("Hello World")

• Make the code more readable


print("Hello World!") #This is a comment

• Prevent execution when testing code


#print("Hello World!")
print("Cheers Mate!")
Examples:
Python Basic Syntax

© Faculty of Management
Example: Personalized Greeting
Let’s build a program to ask the user’s name and print out the
message as follows:
Enter your name: Hyunji
Hello, Hyunji! Your drinks will be ready shortly.

• Variables
• input() and print() function
Personalized Greeting Program
1_Personalized_Greeting
# Prompt the user to enter their name
name = input("Enter your name: ")

# Display the greeting message


print("Hello, " ,name, "! Your drinks will be ready shortly.")

Run

Enter your name: Hyunji


Hello, Hyunji! Your drinks will be ready shortly.
Generating a String

© Faculty of Management
String Definition
A sequence of characters enclosed within either single (' ') or
double (" ") quotes.

Thank you so much for choosing our store!


Single quotes
msg='Thank you so much for choosing our store!'
print(msg)
Double quotes
msg="Thank you so much for choosing our store!"
print(msg)
String: Syntax Errors
Generate a string that includes a single quote inside a string.

Don't miss this offer!

Single quotes
promo_msg='Don't miss this offer'
print(promo_msg)
Avoiding String Syntax Errors
Generate a string that includes a single quote inside a string.

Don't miss this offer!


Double quotes
promo_msg="Don't miss this offer"
print(promo_msg)
Escape character
promo_message = 'Don\'t miss this offer'
\' : single quote character
print(promo_message)
Escape Character
A character that indicates that the following character should be treated
differently or have a special meaning in a string or a character sequence.

Character Combinations Usage


\' A single quote character
\" A double quote character
\\ A backslash character
\n A newline character
\t A tab character
The backslash(\) is used as the escape character.
Escape Character Example
Generate a message as below:

Limited-time offer! • Add a line between the first and second lines.
• Start the second line with a tab.
"SUMMER\25" • Include double quotes and a backslash in the
second line.

promo_msg_dc = 'Limited-time offer!\n\n\t"SUMMER\\25"'


print(promo_msg_dc)
Multi-line Strings
Multi-line strings can be represented by enclosing the text within
three single quotes(''' ''') or triple double (""" """) quotes

promo_msg_dc='''Limited-time offer!
Limited-time offer!
"SUMMER\\25"
"SUMMER\25" '''
print(promo_msg_dc)
Concatenation
When handling strings, the + operator combines two strings together.

James, Don't miss this offer!

name="James"
promo_msg="Don't miss this offer!"

promo_msg_nm=name+','+promo_msg
print(promo_msg_nm)
Concatenation: Type Error
Can you also concatenate integer variables with string variables?

SUMMERSALE\25

dc_rate=25

dc_code="SUMMERSALE\\"+dc_rate
print(dc_code)
Avoiding Concatenation Type Errors
Convert numbers to strings

dc_rate=25
dc_code="SUMMERSALE\\"+str(dc_rate)
print(dc_code) SUMMERSALE\25

dc_rate=10
dc_code="SUMMERSALE\\"+str(dc_rate)
print(dc_code) SUMMERSALE\10
f-strings
An f-strings allows for easy and concise string formatting. It stands for
“formatted” string literals.

dc_rate=25
dc_code=f"SUMMERSALE\\{dc_rate}" SUMMERSALE\25
print(dc_code)

• The syntax for an f-string involves prefixing the string with the letter "f"
before the opening quotation mark.
• Inside the string, expressions enclosed in curly braces {} are evaluated and
their values are inserted into the final string.
• These expressions can include variables, literals, or even complex
expressions.
f-string Application: E-mail Customization
E-mail for order confirmation

Dear James,

Thank you for your recent purchase. name="James"


Please find the details below: OrderID=12345
ProductName="Shirt"
Order ID: 12345 Price=30
Product Name: Shirt (Price: $30, Quantity: 2) Quantity=2
Total:$60

If you have any questions, please reach out to us.


E-mail Customization Code: f-string
e_mail=f"""
Dear {name},

Thank you for your recent purchase.


Please find the details below:

Order ID: {OrderID}


Product Name1: {ProductName} (Price: ${Price}, Quantity: {Quantity})
Total: ${Price*Quantity}

If you have any questions, please reach out to us.


"""

print(e_mail)
E-mail Customization Code: Multi-line string
e_mail=f"""
Dear {name},

Thank you for your recent purchase.


Please find the details below:

Order ID: {OrderID}


Product Name1: {ProductName} (Price: ${Price}, Quantity: {Quantity})
Total: ${Price*Quantity}

If you have any questions, please reach out to us.


"""

print(e_mail)
E-mail Customization Code: Curly brackets
e_mail=f""" name="James"
Dear {name}, OrderID=12345
ProductName="Shirt"
Thank you for your recent purchase. Price=30
Please find the details below: Quantity=2

Order ID: {OrderID}


Product Name1: {ProductName} (Price: ${Price}, Quantity: {Quantity})
Total: ${Price*Quantity}

If you have any questions, please reach out to us.


"""

print(e_mail)
f-string Application: Simple calculations
How can we calculate the total?
Order ID: 12345
Product Name: Shirt (Price: $30, Quantity: 2)
Total:$60

Order ID: {OrderID}


Product Name1: {ProductName} (Price: ${Price}, Quantity: {Quantity})
Total: ${Price*Quantity}
Summary
• A sequence of characters enclosed within either single ('') or
double (" ") quotes represents a string.
• Escape characters, indicated by a backslash (\), are used to
include special characters in strings.
• Multi-line strings can be created using triple quotes (''' or """),
preserving line breaks and formatting.
• Concatenation involves using the plus (+) operator to combine
strings.
• f-strings utilize the 'f' prefix and allow easy embedding of
variables and expressions within strings.
Extracting Information
from String Data

© Faculty of Management
Indexing
Accessing a specific character
Indexing: The process of accessing individual elements within a data
structure, such as a string or a list, using their position or index
number.
first_name="James"

[Example] What are the first and last characters


of the customer's first name?
Zero-based Index System
The index represents the position of an element within the sequence.

Zero-based index system: The first element in a sequence has an


index of 0, the second element has an index of 1, and so on.
Example: Zero-based Index System
To access a specific element in a sequence, you can use its
corresponding index within square brackets [].

first_name[0] index=0
0 1 2 3 4
first_name= J a m e s
Negative Indexing
Negative Indexing: The way to access elements starting from the end
rather than the beginning.

0 1 2 3 4
first_name= J a m e s
-5 -4 -3 -2 -1

first_name[-1]
Indexing Options
By referencing index numbers, we can retrieve specific characters
in a string.
0 1 2 3 4
J a m e s
-5 -4 -3 -2 -1

# First Character # Last Character


first_name="James" first_name="James"

first_name[0] first_name[4]
first_name[-5] first_name[-1]
Slicing
Slicing: A technique of extracting a portion or a subsequence from
a sequence object (e.g., string, list, etc.).
The syntax for slicing involves using square brackets [] with a colon:
to specify the start and end positions of the desired slice.
sequence[start:end]

•start: the index of the first element included in the slice.


If not specified, it defaults to the beginning of the sequence.
•end: the index of the first element excluded from the slice.
If not specified, it defaults to the end of the sequence
Examples: Slicing
Discount Coupon Code

dc_code="SUMMERSALE_25"

A. The first part of the discount code, preceding the word "SALE," typically
includes the season associated with the sales (e.g., summer).
B. The discount rate of the promotion coupon can be extracted from the discount
code by considering the last two characters.
Example A: Start & End
[Example A] Extract information about the season from coupon codes
First index number - where the slice starts
(inclusive)
Second index number - where the slice ends
dc_code[0:6]
(exclusive)

0 1 2 3 4 5 6 7 8 9 10 11 12
dc_code= S U M M E R S A L E _ 2 5
-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Example A: Find ()
[Example A] Extract information about the season from coupon codes
find(): searches for the specified substring
starting from the beginning of the string and
returns the index of its first occurrence.
dc_code[0: dc_code.find('SALE')]

0 1 2 3 4 5 6 7 8 9 10 11 12
dc_code= S U M M E R S A L E _ 2 5
-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Example B: len()
[Example B] Check the discount rates of the coupon
len() : function that evaluates the length of the sequence
dc_code[11:len(dc_code)
dc_code[11:13]

0 1 2 3 4 5 6 7 8 9 10 11 12
dc_code= S U M M E R S A L E _ 2 5
-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Example B: Concise Syntax dc_code[11:]
dc_code[-2:]

0 1 2 3 4 5 6 7 8 9 10 11 12
dc_code= S U M M E R S A L E _ 2 5
-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

dc_code[:6]
dc_code[:-7]

If we want to include either end of a string, we can omit one of the end
index number in the string[n:n] syntax
String Methods
'SALE' in dc_code
• in- operator checks if the substring 'SALE' exists within the string
dc_code.

dc_code.rfind('25')
• rfind() method searches for the last occurrence of the substring '25'
in dc_code and returns the index of the start of the last occurrence,
or -1 if the substring is not found.

dc_code.replace('25', '30')
• replace() method replaces all occurrences of the substring 25 in
dc_code with the substring 30. It returns a new string with the
replacement.
Summary
Various operations can be performed on strings to manipulate or extract
information.
• Indexing: Accessing individual characters within a string using square
brackets [] and the zero-based index.
• Slicing: Extracting a string portion using the [start:stop:step] syntax.
• Length: Determine the length of a string using the len() function.
• String methods: Built-in methods provide functionality such as
searching, replacing, converting cases, splitting, and more.
Arithmetic Operators
in Python

© Faculty of Management
Python Arithmetic Operators
Operator Definition Example Result
+ Addition 7+4 11
- Subtraction 7-4 3
* Multiplication 7*4 28
/ Division 7/4 1.75
// Integer division operator 7//4 1
% Remainder operator 7%4 3
Square (multiply the same
** 2**3 8
number several times)
Example: Python as a Calculator
Generate a program to:
1) Take two integers from users
2) Conduct multiplication (*)
3) Print the result as follows

input the number: 30


input the number: 40

num1*num2 1200
Calculator Program: Type Error
num1=input("input the number: ")
num2=input("input the number: ") • input () returns a string
• For calculations, the inputs need to
print("num1*num2", num1*num2) be converted from strings to numbers

Run
input the number: 30
input the number: 40
Traceback (most recent call last):
File "<ipython-input-1-82842ffdc628>"
<module>
print("num1*num2", num1*num2)
TypeError: can’t multiply sequence by non-int of type ‘str’
Convert String to Number
num1=input("input the number: ")
num2=input("input the number: ")

• int() function: convert a string to an int data type.


• int means integer
• float() function converts a string to a float data type.
• float means real or floating point

num1=int(input("input the number: "))


num2=int(input("input the number: "))
Successful Calculator Program
Generate a program to conduct multiplication
num1=int(input("input the number: "))
num2=int(input("input the number: "))

print("num1*num2", num1*num2)

Run

input the number: 30


input the number: 40

num1*num2 1200
Rule-Based Decisions:
Conditional Statements

© Faculty of Management
Control Flow
The control flow refers to the order in which statements and
instructions are executed in a program.

• Conditional Statement (if, else, and elif)


To Do List

• Loop Statement (for-loop and while-loop)


Conditional Statements
Conditional statements in Python are used to execute different blocks
of code based on the evaluation of certain conditions.

• if-statement: executes a block of code if a certain condition is true.


• if-else statement: executes a block of code if a certain condition is
true and a different block of code if the condition is false.
• if-elif-else statement: tests multiple conditions and executes
different code blocks based on the first condition that evaluates the
true. The elif part allows you to check additional conditions.
if-Statement
The if-statement is used to perform a specific action or execute a block
of code if a given condition evaluates to true.
if Condition: True!
statements Code
Block

• The condition is an expression that results in either true or false. It can involve
comparison operators (e.g., <, >, ==, !=, etc.), logical operators (e.g., as and, or,
not), and other Boolean expressions.
• The code block consists of one or more statements that are indented under the
if-statement. These statements are executed only if the condition is true.
Example: if-statement
Print a message indicating a special discount for new customers.

# Prompt user tenure input


user_tenure=int(input("Enter the user's tenure(in days): "))

# Check if the user's tenure is less than or equal to 7


if (user_tenure<=7):
print("New customers: Special discount!")
Comparison Operators
Comparison operators are used to compare two values or expressions and
return a Boolean value (True or False) based on the comparison result.
user_tenure<=7
Operator What is Compared
== if the value on both sides of the operator are equal
!= if the value on both sides of the operator are not equal
> if the value on the left side is greater than on the right side
< if the value on the left side is less than on the right side
>= if the value on the left side is greater than or equal to the right side
<= if the value on the left side is less than or equal to the right side
Logical Operators
Logical operators are used to combine or modify the evaluation of
Boolean expressions.
user_tenure<=7 and num_order>0
user_tenure<=7 or num_order>0
not user_tenure>7
Operator Description
and returns true if both conditions on its left and right sides are true
or returns true if at least one of the conditions on its left and right sides is true
not returns true if the condition is false, and false if the condition is true.
Rule-Based Decisions:
Handling Multiple
Conditional Statements

© Faculty of Management
if-else Statement
The if-else statement in Python is used to handle binary conditions.
if Condition: False!
Statements_1

else :
Statements_2

When the condition of the if statement


is not satisfied, the flow goes to else.
Example: if-else statement
Send a message to both new and existing customers.
• New customers, with a user tenure of a week or less, will receive a special
discount message.
• Existing customers will be informed about an ongoing sale.
# Prompt user tenure input
user_tenure=int(input("Enter the user's tenure(in days): "))

# Check if the user's tenure is less than or equal to 7


if user_tenure <= 7:
print("New customers: Special discount!")
else:
print("Our summer sale has started!")
if-elif-else Statement
Multiple conditions
if Condition:
Code block The first condition
always starts with if.
elif Condition:
Code block From the second
condition, we use elif.
elif Condition:
Code block

else: Fallback option


Code block
Example: if-elif-else statement
Based on the chosen membership status, display the corresponding
discount rate.
Gold: 20% Silver: 10%
mem_status=input("Choose your membership status: gold or silver.").lower()

# Print the discount rate based on membership status


if mem_status=='gold':
print("You will receive a 20% discount coupon!")
elif mem_status=='silver':
print("You will receive a 10% discount coupon!")
else:
print("Sorry, please try again!")
Nested Conditions
The code should first ask whether the user is a registered member on the website (Y/N).
# Prompt the user to indicate whether they are a registered member on the website
mem_yn = input("Are you a registered member on our website? Y/N \n").upper()
# Determine the discount rate based on the user's registration status
if mem_yn == "N":
print("Register on our website! You will get an additional discount!")
else: if Condition:
Statements_1
elif Condition:
Statements_ 2
else:
Statements_3
Nested Conditions Process
Nested conditionals
if Condition:
Statements_a

else :
if Condition:
Statements_b
else :
Statements_c

Nested if-else statement


Summary
Conditional statements allow decision-making based on conditions
or rules.
• if statement executes code if a condition is true.
• if-else statement executes one block of code if a condition is
true, another block if false.
• if-elif-else statement evaluates multiple conditions, executing
different blocks of code based on each condition.
• Nested conditions are conditional statements within other
conditional statements that allow for complex decision-making.

You might also like