3 Python Basics Part 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 71

Python Basics

Lesson 2
Outline:
1. Input/Print Function
2. Output Formatting
3. Import Function
4. String Operations
5. List Methods
6. Slicing
7. Operators and Basic Mathematical Function
8. Built-in Functions
Input/Output (I/O)

The purpose of a program is to get an input,


process it, optionally store it, and display the
results afterwards. Python has functions that
allow the programmer to get user input and
display messages.
Input Function

• The input() function takes input from the user


and returns it.
• To store a value, it can be assigned to a
variable using the syntax below.

<variable> = input(<message>)
Example:
value = input("Enter a value: ")
Input Function
Example:
number = input(“Enter a number: “)

Enter a number: 10
10

Note that the inputted value 10 is a string. You need to


convert this into a number. Use int() or float() functions.
Input Function

number = int(input("Enter a number: "))

the value must be compatible when in comes of


conversion
Print Function

• In order to display something,


the print() function can be used.

Example:
value = input("Enter a value: ")
print(value)
Output Formatting

Sometimes we would like to format our output to


make it look attractive. This can be done by
using the str.format() method. This method is
visible to any string object.
Output Formatting

For example:
x = 5; y = 10
print(“The value of x is {} and y is {}”.format(x,y))

Output:
The value of x is 5 and y is 10.

The curly braces {} are used as placeholders.


Output Formatting
Another example:
print(‘ I love {0} and {1} ‘ .format(‘bread’, ’butter’))
print( ‘ I love {1} and {0}’ .format(‘bread’, ’butter’))

Output:
I love bread and butter
I love butter and bread

The curly braces {} are used as placeholders. We can specify the


order in which they are printed by using numbers (tuple index).
Output Formatting
We can also use keyword arguments to format
the string.

print(‘Hello {name}, {adj}’.format(adj =


‘Handsome’, name = ‘John’))

Result:
Hello John, Handsome
Output Formatting

Another way to format:

Example:
x=5
y = 10
print(f“The value of x is {x} and y is {y}”)

Output: The value of x is 5 and y is 10


Output Formatting
Example:
x=5
y = 10
total = x + y
print(f"The sum of the two integer is {total}")

Output: The sum of the two integer is 15


Output Formatting
How input() works in Python
Example 1:

#Get input from user


inputString = input(“ ”)
print('The inputted String is:', inputString)
Or:
print(f“The inputted String is: {inputString}”)
How input() works in Python
Example 2:
#Taking two integers from users and adding
them.
#Taking num1 from user as int
num1 = input('Please Enter First Number:')
num1 = int(num1)
#Taking number 2 from user as int
num2 = input('Please Enter Second Number:')
num2 = int(num2)

addition = num1 + num2


print(addition)
How input() works in Python
Example 2:
#Taking two integers from users and adding them.

#Taking num1 from user as int


num1 = int(input('Please Enter First Number:'))

#Taking number 2 from user as int


num2 = int(input('Please Enter Second Number:'))

addition = num1 + num2


print(addition)
How input() works in Python
Example 3:
#Taking two integers from users and adding them.

#Taking num1 from user as float


num1 = float(input('Please Enter First Number:'))

#Taking number 2 from user as float


num2 = float(input('Please Enter Second Number:’))
addition = num1 + num2
#to round off float, use round() Function
print(round(addition,2))
Import in Python

• Definitions inside a module can be imported


to another module or the interactive
interpreter in Python.
• We use the import keyword to do this.
Example:
import math
print(math.pi)
Import in Python

import math

pi = math.pi
print(f"The value of pi is {pi}.")

result = math.factorial(5)
print(f"5 factorial: {result}")
Import in Python

import math

pi = math.pi
print("The value of pi is", pi)

result = math.factorial(5)
print("5 factorial: ", result)
Import in Python

• We can also import some specific attributes


and functions only, using the from keyword.

Example:
from math import pi
pi
Import in Python
Example:
from statistics import mean, median

numbers = [1, 2, 3, 4, 5]
average = mean(numbers)
middle = median(numbers)

print(f"The mean is: {average}")


print(f"The median is: {middle}")
Import in Python

Math Module:
https://docs.python.org/3/library/math.html
String Operations
String Operations

NOTE: Applicable on strings only.


String Operations

NOTE: Applicable on strings only.


String Operations

NOTE: Applicable on strings only.


String Operations

the strip() method is a string method that returns


a copy of the string with leading and trailing
whitespace removed.
String Operations

the upper() method is a string method that


returns a copy of the string with all characters
converted to uppercase.
String Operations

the lower() method is a string method that returns


a copy of the string with all characters converted
to lowercase.
String Operations

the capitalize() method is a string method that


returns a copy of the string with the first character
converted to uppercase and all other characters
converted to lowercase.
String Operations

the title() method is a string method that returns a


copy of the string with the first character of each
word capitalized and the remaining characters in
lowercase.
String Operations
String Operations
List Methods

List can be modified by adding or removing


a value.

Other methods can also be applied to


further manipulate its contents.
List Methods

inventory = [] # create a list

# Add a new item


inventory.append("screw")

# insert a new item at a specific index


inventory.insert(0, "hammer")
List Methods

inventory = [“hammer", “screw"]

# remove at specific index


inventory.pop(1)

# remove the first occurrence


inventory.remove(“hammer")
List Methods
inventory = [“hammer", “screw”]

# count total occurrences


count = inventory.count("hammer")
print(f"Occurrence: {count}")

# get index of first occurence


index = inventory.index("screw")
print(f"Index: {index}")

# get the total items in the list; using


len() function
print(len(inventory))
List Methods

inventory = [“hammer", “screw”]

# change value on specific index


inventory[1] = "screw driver"

# access value on specific index


print(inventory[1])
List Methods

inventory = [“hammer", “screw driver”]


more_items = ["pliers", "tie wire"]

# extend list with more items


inventory.extend(more_items)

# clear all contents


inventory.clear()
Slicing

What is Slicing?

A way to get values in an ordered sequence.

NOTE: Applicable on Strings, Lists, and Tuples only


Slicing
Slicing
Operators and
Basic
Mathematical
Function
What are operators in python?

• Operators are special symbols in Python that


carry out arithmetic or logical computation.
• The value that the operator operates on is
called the operand.

Example:
a=2+3
Output: 5
Arithmetic operators
Arithmetic operators are used to perform
mathematical operations like addition, subtraction,
multiplication, etc.
Arithmetic operators
Arithmetic operators
Note: we can also use this:
Example x = 15
y = 4 a = x + y
print(f"x + y = {a}")
print('x + y =',x+y)
# Output: x + y = 19

print('x - y =',x-y)
# Output: x - y = 11

print('x * y =',x*y)
# Output: x * y = 60
Arithmetic operators
Example x = 15
y = 4

print('x / y =',x/y)
# Output: x / y = 3.75

print('x // y =',x//y)
# Output: x // y = 3

print('x ** y =',x**y)
# Output: x ** y = 50625
Arithmetic operators
Increment

age = 5
age += 1 # increment
print(age)

Output: 6
Comparison operators
Comparison operators are used to compare values.
It returns either True or False according to the
condition.
Comparison operators
Comparison operators
Note: we can also use this:
Example x = 10
y = 12 a = x > y
print(f"x > y = {a}")
# Output: x > y is False
print('x > y is',x>y)

# Output: x < y is True


print('x < y is',x<y)

# Output: x == y is False
print('x == y is',x==y)
Comparison operators
Example x = 10
y = 12

# Output: x != y is True
print('x != y is',x!=y)

# Output: x >= y is False


print('x >= y is',x>=y)

# Output: x <= y is True


print('x <= y is',x<=y)
Assignment operators
Assignment operators are used in Python to assign
values to variables.
Assignment operators
Logical Operators in Python
Python logical operators are used to combine
conditional statements, allowing you to perform
operations based on multiple conditions.
Logical Operators in Python
Link for Operators in Python

https://www.geeksforgeeks.org/python-operators/
Sample Program
1.Compute the area of a triangle given
the length of its three sides: a,b,c
with formulas:
Sample Program NOTE:
In the str.format method, the
import math last placeholder has a value
of :0.2f, was used to format
a = int(input ('Side a: ')) the number of decimal places
b = int(input ('Side b: ')) to be displayed. It follows this
c = int(input ('Side c: ')) syntax:
{<index>:<format-specifier>}
s = (a + b + c) / 2
A = math.sqrt(s*(s-a) * (s-b) * (s-c))

print(f"The area of a triangle given the length of three


sides:\
\na = {a}\nb = {b}\nc = {c}\nis: {A:0.2f}")
Sample Program
2. Calculating the Area and Perimeter of a Rectangle
Sample Program

w = int(input ('Width: '))


l = int(input (‘Length: '))

A = w * l

print(f"The area of a rectangle is {A}")


Sample Program

w = int(input ('Width: '))


l = int(input ('Length: '))

P = 2 * (w + l)

print(f"The perimeter of a rectangle is


{P}")
Sample Program
w = int(input ('Width: '))
l = int(input ('Lenght: '))

A = w * l
P = 2 * (w + l)

print(f"Area of the rectangle: {A}\


\nPerimeter of a rectangle: {P}")
Built-in Functions

These are pre-loaded "commands" that


simplifies the work of any programmers.
Built-in Functions
Built-in Functions

NOTE: Used on strings that


are numeric in nature.
Built-in Functions
NOTE: Used on Strings,
Lists, Tuples, and Sets

NOTE: Used on Lists,


Tuples, and Sets containing
numeric values only.
THANK YOU
AND
GOD BLESS!

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy