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

L2 Python Variables and Expression

.

Uploaded by

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

L2 Python Variables and Expression

.

Uploaded by

Franken Stein
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Python

Programming
Variables
Expression
Function
Objects and Python Interpreter
The Python interpreter is a program that runs on a

variables computer, just like an Internet browser or a text


editor.

When the interpreter encounters a line of code in a


program such as x = 4, the interpreter automatically
creates a new object to represent the value 4.
People on the bus

For each step, keep


track of the current
number of people by
answering in the
num_people box
People on the bus

For each step, keep


track of the current
number of people by
answering in the
num_people box
Objects and variables
Variables
● A program uses a variable to remember The statement age = 15 defines a variable named age
values as the program executes Example of creating a variable is :
instructions. age = 23
● A variable is used to remember a value
for later use.
Example of creating a variable is :
● A variable are containers for storing data
x=5
values.
y = "John"
print(x)
print(y)
Objects and variables
Variables Name Camel Case
Multi Words Variable Names Each word, except the
● Variable names with more than one word can be first, starts with a capital
difficult to read. letter.

● There are several techniques you can use to make Pascal Case
them more readable:
Each word starts with a
1. Camel Case
capital letter:
2. Pascal Case
3. Snake Case Snake Case
Each word is separated by
an underscore character
Objects and variables
Manipulating Variables
● Names are not permanently assigned
to objects.
● A name can be reassigned to another
object, and multiple names can refer
to the same object.
● The following animation illustrate:

● NOTE:
= means compute the value on the right, and then assign
that value into the variable on the left."
Each Python object has three defining
properties:
More on
1. Value: A value such as "20", "abcdef", or 55.
objects
2. Type: The type of the object, such as integer
or string.

3. Identity: A unique identifier that describes the


object.
Arithmetic
Expressions ● Arithmetic Expressions - is a combination of
numeric values, operators, and sometimes
parenthesis.
● The result of this type of expression is also a
numeric value.
● The operators used in these expressions are
arithmetic operators like addition, subtraction, etc.
● An operator is a symbol for a built-in language
calculation like+ for addition
● Constant Expressions - These are the expressions
that have constant values only.

Constant Example:
# Constant Expressions
Expressions x = 15 + 1.3

print(x)
Python Data Types
Data Types
Importance of
Python Data Types
• Variable Declaration
and Initialization
• Data Validation
• Memory Management
Python Functions
Strings
● A string is a sequence of characters.
Python Strings ● A character is simply a symbol.
● For example, the English language has 26
characters.
● Strings can be created by enclosing characters
inside a single quote or double-quotes
EXAMPLES:

Python
Comments
print() function
● prints the specified message to the screen, or

print () Function other standard output device.


str() function
str () Function ● The str() function converts the specified value into
a string.

input() Function input() function


● The input() function takes input from the user and
returns it.
int () Function int() function
- used to convert a value to an integer
data type.
- If you provide a floating-point number or
a numeric string as an argument to int(),
float () Function it will truncate the decimal part and return
the integer part.

float() function
- used to convert a value to a floating-point
number (a number with a decimal point).
Integer or float?
-10 15 // 2 100
1000
[1.5, 2.7, 4.3, 0.9]
1k
2.5e3
Assigning a Variable
Assigning a variable

● All three variables are initialized, with annual_mice initialized to 0.


● Later, the value of litter_size * yearly_litters (3 * 5, or 15) is assigned
to annual_mice, which is then printed.
● Next, 14 is assigned to litter_size, and 10 to yearly_litters, and their
product (14 * 10, or 140) is assigned to annual_mice, which is printed.
Laboratory Exercise Item #1
Laboratory Exercise
Item #2

Create a program that will


show the expected result
on Right using the input ()
function.

The age 49 and name


Sheldon should
vary depending on what
the user will input
Laboratory Exercise
Item #3
Write a Python program that calculates
Calculate and Display and displays the simple interest for a
the Simple Interest principal amount, interest rate, and time
period entered by the user.

The simple interest can be calculated


using the formula:

Simple Interest =
Principal Amount × Rate × Time /100
End of Slide
IF ELSE Laboratory Item #1

Creating a simple login program in Python involves taking a username and password
from the user and comparing them to predefined values

# Predefined username and password


correct_username = "user123"
correct_password = "password123"

# Get user input for username and password


username = input("Enter your username: ")
password = input("Enter your password: ")

# Check if the provided username and password match the predefined values
if username == correct_username and password == correct_password:
print("Login successful!") • We define a correct username and password. In a real application, these values
else: would be stored more securely, such as in a database.
print("Login failed. Please check your username and password.")
• We use the input() function to get the username and password from the user.

• We compare the entered username and password to the predefined correct values.

• If the entered values match the correct values, we print "Login successful." Otherwise,
we print "Login failed."

• Please note that this is a very basic example, and in real-world applications, you
should consider more secure and sophisticated methods for handling user
authentication and password storage, such as hashing and salting passwords, using
databases, and implementing session management. Additionally, it's important to
handle exceptions and implement security measures to protect against potential
attacks.
for in Laboratory Item #1

Create a simple text-based representation of a Christmas tree in Python by using loops


and print statements. Here's an example of how to create a basic Christmas tree

# Define the height of the tree


tree_height = 5

# Loop to create the tree


for i in range(1, tree_height + 1):
spaces = " " * (tree_height - i)
stars = "*" * (2 * i - 1)
print(spaces + stars)

# Create the tree trunk


trunk_height = 2 • We define the tree_height variable to set the height of the Christmas tree. You can
trunk_width = 3 adjust this value to change the tree's size.
for i in range(trunk_height):
spaces = " " * (tree_height - trunk_width // 2) • The first loop creates the layers of the tree using a combination of spaces and
trunk = "|" * trunk_width asterisks (*). The number of spaces and asterisks in each layer is determined by the
print(spaces + trunk) current i value in the loop.

• After creating the tree layers, we use a second loop to create the tree trunk. The trunk
is represented with vertical bars (|). You can adjust the trunk_height and trunk_width
to control the trunk's size.

• When you run this code, it will print a simple text-based Christmas tree to the console.
Feel free to modify and enhance it to create more complex and colorful trees with
ornaments or lights if you like.
Def function Laboratory Item #1

# Get the score from the user


score = float(input("Enter the score: "))

# Define the grading scale • # Get the score from the user
grading_scale = { • score = float(input("Enter the score: "))
'A': (90, 100),
'B': (80, 89), • # Define the grading scale
'C': (70, 79), • grading_scale = {
'D': (60, 69), • 'A': (90, 100),
'F': (0, 59) • 'B': (80, 89),
} • 'C': (70, 79),
• 'D': (60, 69),
# Determine the grade • 'F': (0, 59)
def compute_grade(score, grading_scale): • }
for grade, (min_score, max_score) in grading_scale.items():
if min_score <= score <= max_score: • # Determine the grade
return grade • def compute_grade(score, grading_scale):
return "Invalid Score" • for grade, (min_score, max_score) in grading_scale.items():
• if min_score <= score <= max_score:
# Calculate and print the grade • return grade
grade = compute_grade(score, grading_scale) • return "Invalid Score"
print(f"Grade: {grade}")
• # Calculate and print the grade
• grade = compute_grade(score, grading_scale)
• print(f"Grade: {grade}")

You might also like