Phyton
Phyton
Variables
• (LauchSchool) are used to store
information to be referenced and
manipulated in a computer
program. Think of it as a
container where you can put
some kinds of stuff, and in
programming, those kinds of
Drawbacks
stuff are information or data.
• it's not a speed demon – Python does not • also provide a way of labeling
deliver exceptional performance; data with a descriptive name, so
• in some cases it may be resistant to some our programs can be understood
simpler testing techniques – this may more clearly by the reader and
mean that debugging Python code can be ourselves.
more difficult than with other languages; • as containers that hold
fortunately, making mistakes is also information. Can store data of
harder in Python. different types, and different
types can do different things.
• is a named location reserved to
Literal store values in the memory.
• A variable is created or
• Python Institute (2021) is data whose initialized automatically when
values are determined by the literal itself. you assign a value to it for the
• Ambrose, T. (2019), A literal is an idea first time.
of expressing a non-changing value in a
computer program’s source code. It is Identifier
literally the value itself.
• Unique name of a variable
• Python Institute (2021), Literals can be of
• A legal identifier name must be a non-
almost any type in a programming
empty sequence of characters, must
language, some examples of these types
begin with the underscore(_), or a letter,
are:
and it cannot be a Python keyword. The
o Integer literals. Example (123)
first character may be followed by
o String literals. Example
underscores, letters, and digits.
("Hello")
Identifiers in Python are case-sensitive.
o Boolean literals. Example
(True/False)
Rules to follow when giving name to
a variable:
• the name of the variable must be
composed of upper-case or lower-case
letters, digits, and the character _
(underscore)
• the name of the variable must begin with
a letter;
• the underscore character is a letter; Output
• upper- and lower-case letters are treated
as different (a little differently than in the
real world - Alice and ALICE are the
same first names, but in Python, they are
two different variable names, and
consequently, two different variables);
Variable Scope
• the name of the variable must not be any
of Python's reserved words • According to Marshal (nd.), Scope
refers to the visibility of variables. In
Keywords other words, which parts of your
• or (more precisely) reserved keywords. program can see or use it.
• They are reserved because you mustn't • Normally, every variable has a global
use them as names: neither for your scope. Once defined, every part of your
variables, nor functions nor any other program can access a variable.
named entities you want to create. • in Python, you can declare a variable
locally or globally.
Casting
Local variable
• Specifying the data type of a variable
- the scope of this variable is just visible within a
part of a program, for example, within a
function.
Global variables
• Variables created outside of a function
• Global variables can be used by
Get the Type everyone, both inside of functions and
outside.
• get the data type of a variable with the
type() function.
Function x = memoryview(bytes(5)) memoryview
Sequence Types: list, tuple, range • are the ones whose meaning is dictated
by their position, e.g., the second
Mapping Type: dict argument is outputted after the first, the
Set Types: set, frozenset third is outputted after the second, etc.
•
Boolean Type: bool
Keyword arguments
Binary Types: bytes, bytearray, memoryview
• are the ones whose meaning is not
dictated by their location, but by a
Example Data Type special word (keyword) used to identify
them.
x = "Hello World" str
•
x = 20 int
Concatenation Operator
x = 20.5 float
• The + (plus) sign, when applied to two
x = 1j complex strings, becomes a concatenation
x = ["apple", "banana", "cherry"] list operator
x = b"Hello" bytes
x = bytearray(5) bytearray
Arithmetic Operator If Statement
• consists of a boolean expression
followed by one or more statements.
• contains a logical expression using
which data is compared and a decision is
made based on the result of the
comparison.
Syntax:
if (condition):
Comparison Operator Statement(s)
Else Statement
• can be combined with an if statement.
• contains the block of code that executes
if the conditional expression in the if
statement resolves to 0 or a FALSE
value.
• else keyword catches anything which
Logical Operator isn't caught by the preceding conditions.
Syntax:
if condition:
True Statements
else:
False statements
Assignment Operator
Elif Statement
• allows you to check multiple
expressions for TRUE and execute a
block of code as soon as one of the
conditions evaluates to TRUE.
• The elif keyword is pythons way of
saying "if the previous conditions were
not true, then try this condition".
Syntax:
if condition:
True Statements
elif condition: more like an iterator method as found in
True Statements other object-orientated programming
else: languages.
False statements • we can execute a set of statements, once
for each item in a list, tuple, set etc.
Problem No. 2
Create a program that will allow the user to The first number shall be duplicated according
input two numbers. Your code for the input must to the value of the second number.
be on a single line. A third number shall be created by multiplying
Display the first number duplicated according to the value of the second number to 6.
the value of the second number. A maximum of two (2) variables shall be used in
Minimum and maximum of two (2) lines of this problem
codes are allowed in this problem.
Display the sum of all three numbers using f- Your separator characters shall be duplicated
strings. Follow the format of the output below: twice.
The sum of all three numbers are sum., where Use the given code below. You can only modify
sum is the sum of all three numbers. the print() statement.
Answer:
separator = input("Input separator char
acter/s: ")
num1, num2 = int(input("Enter First Num ending = input("Input ending character/
ber: ")), int(input("Enter second Numbe s: ")
r: ")) print("I","love","Python")
num1 = int(str(num1) * num2)
num1 += num2 + num2 * 6
print(f"The sum of all three numbers ar Answer:
e {num1}.")
separator = input("Input separator char
acter/s: ")
Problem No. 4
ending = input("Input ending character/
Create a program that will allow the user to s: ")
print("I","love","Python",sep=separator
input two numbers.
*2,end=ending)
The first number must be an integer, and the
second number must be a float. Ensure that the Activity 2 (Conditional Statement
data types are correct upon inputting.
and Loops)
Display the first number as a float with two
decimal places and the second number as an Problem No. 1
integer. Use the String modulo operator. Follow Create a program that allows the user to input a
the format of the output below: character that will be used in the program and a
First Number: num1, Second Number: num2, number for determining the maximum peak of
where num1 is the first number and num2 is the the triangle.
second number. The input statements must be in a single line,
ensuring one is for a character and the other is
Do the same display using f-strings. Ensure that
the program shall encounter no errors. for a number.
Problem No. 5 # # # # # # # # # # # # # #
Create a program that will determine the height # ### ### ### ### ### # ### ### # #
of a pyramid based on the number of blocks # # # # # # # # # # # # #
inputted by the user
# ### ### # ### ### # ### ### ###
The pyramid's layer contains one block more
than the layer above.
Note: the number 8 shows all the LED lights on.
The height of the pyramid is measured by the
Your code has to display any non-negative
number of fully-completed layers. If a layer does
integer number entered by the user.
not have a sufficient number of blocks and
cannot complete the next layer, it is not counted Tip: using a 2-dimensional list containing
in the height of the pyramid. patterns of all ten digits may be very helpful.
Answer:
Limitation:
num = int(input("Enter a number: "))
height = ctr = 1 Only positive numbers are valid as input. If the
while True:
input was invalid, please ask for input again.
num-=ctr
ctr+=1 Answer:
if num >= ctr:
height+=1
continue nums =[
break ["###"," #","###","###","# #","###","#
print(f"The height of the pyramid is {h ##","###","###","###"],
eight}." ["# #"," #"," #"," #","# #","# ","
# "," #","# #","# #"],
["# #"," #","###","###","###","###","#
Activity 3 (Strings) ##"," #","###","###"],
["# #"," #","# "," #"," #"," #","#
Problem No. 1 #"," #","# #"," #"],
["###"," #","###","###"," #","###","#
You've surely seen a seven-segment display. ##"," #","###","###"],
]
It's a device (sometimes electronic, sometimes num = input("Enter a number: ")
mechanical) designed to present one decimal while num.isnumeric() is False:
digit using a subset of seven segments. If you num = input("Invalid Input. Enter a
still don't know what it is, refer to the following number: ")
Wikipedia article (Links to an external site.) for i in range(5):
for x in num:
Your task is to write a program that is able to print(nums[i][int(x)],end=" ")
simulate the work of a seven-display device, print()
although you're going to use single LEDs instead
of segments
Each digit is constructed from 13 LEDs (some
lit, some dark, of course) - that's how we
Problem No. 2
imagine it:
Now, create a program that will simulate Caesar if x in "ABCDEFGHIJKLMNOPQRSTUV
Cipher. WXYZ":
newMessage += chr(ord(x) +
First, ask the user if they want to encrypt or shift if ord(x) + shift < 91 else ord(x
decrypt a message. ) + shift - 26)
continue
Then ask the user what is the number of shifts newMessage += x
they want to use. They may only select from 1 to else: # Decipher
for x in message:
25 since 26 will just revert the original shifting
if x in "ABCDEFGHIJKLMNOPQRSTUV
of the alphabet. WXYZ":
newMessage += chr(ord(x) -
Then ask the message to be encrypted/decrypted.
shift if ord(x) - shift > 64 else ord(x
Depending on the first input by the user whether ) - shift + 26)
continue
to encrypt or decrypt the message, perform the
newMessage += x
shifting on the letters from the input message print(f"Output: {newMessage}")
and display the output in all capital letters.
Limitation: Problem No. 3
o d3.update(item)
o colDict = dict(colors)
Quiz 3 (Collections)
o 666666
• What is the output of the following
snippet?
o Error
o var.count(2)
• Complete the code by supplying the
correct statement to replace the
comment.