0% found this document useful (0 votes)
19 views

1.5 Python Built-In Functions

Python Built-in functions
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

1.5 Python Built-In Functions

Python Built-in functions
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

PYTHON PROGRAMMING WITH

WEB FRAMEWORKS – CSE304


This presentation contains the
concepts related to Basic Python
functions
Quotation in Python
• Python accepts single ('), double (") and triple ('''
or """) quotes to denote string literals, as long as
the same type of quote starts and ends the string.
• The triple quotes can be used to span the string
across multiple lines. For example, all the following
are legal:
word = 'word'
sentence = "This is a sentence."
paragraph = """This is a
paragraph. It is made up of
multiple lines and sentences."""
2
Multiple Statements on a Single Line
• The semicolon ( ; ) allows multiple statements on
the single line given that neither statement starts a
new code block. Here is a sample snip using the
semicolon:
x = 'foo'; print(x)

3
Assigning Values to Variables
• Python variables do not have to be explicitly declared to
reserve memory space. The declaration happens
automatically when you assign a value to a variable. The
equal sign (=) is used to assign values to variables.
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
print counter
print miles
print name

4
Multiple Assignment
• You can also assign a single value to several
variables simultaneously. For example:
a = b = c = 1
a, b, c = 1, 2, "john"

5
Python functions (built-in)
• A function is a block of organized, reusable
code that is used to perform a single, related
action.
• In Python a function is some reusable code
that takes arguments(s) as input does some
computation and then returns a result or
results
• Functions provides better modularity for
your application and a high degree of code
reusing.
6
Python functions (built-in)
• Python provides many built-in functions. that you can call in
your programs. When you call a function, you can include any
arguments that are used by the function.
• Some of popular Python built-in functions:
– print()
– input()
– int()
– float()
– round()
– min()
– max()
– abs()
– sqrt()
– eval()
7
Buit-in-Functions
• Python provides many built-in functions for numbers,
including:
• Mathematical functions: round(), pow(), abs(), etc.
• type() to get the type.
• Type conversion functions: int(), float(), str(), bool(),
etc.
• Base radix conversion functions: hex(), bin(), oct().

8
Built-in Functions and Operators for Strings
• You can operate on strings using:
• built-in functions such as len();
• Operators such as in
(contains), + (concatenation), * (repetition),
indexing [i] and [-i], and slicing [m:n:step].

9
Function / Examples
Usage Description
Operator s = 'Hello'
len() len(str) Length len(s) ⇒ 5
in substr in str Contain? 'ell' in s ⇒ True
Return bool of 'he' in s ⇒ False
either True or False

+ str + str1 Concatenation s + '!' ⇒ 'Hello!'


+= str += str1
* str * count Repetition s * 2 ⇒ 'HelloHello'
*= str *= count
[i] str[i] Indexing to get a s[1] ⇒ 'e'
[-i] str[-i] character. s[-4] ⇒ 'e'
The front index
begins at 0;
back index begins at -
1 (=len(str)-1).

[m:n:step] str[m:n:step] Slicing to get a s[1:3] ⇒ 'el'


[m:n] str[m:n] substring. s[1:-2] ⇒ 'el'
[m:] str[m:] From s[3:] ⇒ 'lo'
[:n] str[:n] index m (included) s[:-2] ⇒ 'Hel'
[:] str[:] to n (excluded) s[:] ⇒ 'Hello'
with step size. s[0:5:2] ⇒ 'Hlo'
The defaults 10
String-Specific Member Functions
• Python supports strings via a built-in class called str
• The commonly-used member functions are as follows, supposing
that s is a str object:
• str.strip(), str.rstrip(), str.lstrip(): strip the leading and trailing
whitespaces, the right (trailing) whitespaces; and the left (leading)
whitespaces, respectively.
• str.upper(), str.lower(): Return a uppercase/lowercase counterpart,
respectively.
• str.isupper(), str.islower(): Check if the string is uppercase/lowercase,
respectively.
• str.find(key_str):
• str.index(key_str):
• str.startswith(key_str):
• str.endswith(key_str):
• str.split(delimiter_str), delimiter_str.join(strings_list): 11
Round()
• >>> x = 1.23456
• >>> type(x)
• <type 'float'>
• >>> round(x)
• >>> type(round(x))
• <class 'int'>
• >>> round(x) 1.0
• >>> type(round(x))
• <type 'float'> >>> round(x, 1)
• # Round to 1 decimal place 1.2 >>> round(x, 2) # Round to 2
decimal places 1.23 >>> round(x, 8) # No change - not for
formatting 1.23456
12
print()
• print() function receives arguments and prints the
values
• The syntax of the print() function
print(data[, sep=' '][, end='\n'])
• Example
• print(19.99)
O/P 19.99
• print("Price:", 19.99)
O/P Price: 19.99
• print(1, 2, 3, 4)
O/P 1234
13
input()
• The input() function can take argument that prompts the user to enter
data.
• When the user makes that entry and presses the Enter key, the entry
is returned by the function so it can be saved in a variable.
• Note: When you use the input() function, remember that all entries
are returned as strings.
• input ([prompt])

• Code that gets string input from the user


first_name = input ("Enter your first name: ")
print ("Hello, " + first_name + “!")

O/P
Enter your first name: Mike
Hello, Mike!
14
input()
• Another way to get input from the user
print ("What is your first name? ")
first_name = input ()
print ("Hello, " + first_name + "!")

O/P
What is your first name?
Mike
Hello, Mike!

15
int(), float
• The int() and float() functions convert the data
argument, which is typically a str value, to int or float
values.
• Syntax: int (data)
– Converts the data argument to the int type and returns
the int value.
• Syntax: float (data)
– Converts the data argument to the float type and
returns the float value.

16
int(), float - Example
• Examples:
quantity = input("Enter the quantity: ")
quantity = int(quantity)

price = input("Enter the price: ")


price = float(price)

You can use chaining to get the float value in one


statement
price = float(input("Enter the price: "))

17
round()
• The round() function rounds a numeric value to the
specified number of digits.
• Syntax: round (number [, digits] )
– Rounds the number argument to the number of
decimal digits in the digits argument. If no digits are
specified, it rounds the number to the nearest integer.
miles_driven = 150
gallons_used = 5.875
mpg = miles_driven / gallons_used
mpg = round (mpg, 2)

18
min(), max()
• The max() function allows you to find the highest
number in given range.
• The min() function does the opposite, providing you
with the lowest number in a defined range.

19
lower (), upper ()
• lower () Converts uppercase letters to lowercase
without changing the string itself.
• upper () Converts lowercase letters to uppercase
without changing the string itself.

20
abs()
• The abs() method in Python can be used to convert a
floating-point number or an integer into an absolute
value.
• This is especially useful when you want to know the
difference between two values.

21
sqrt()
• sqrt() function is an inbuilt function in Python
programming language that returns the square root of
any number.
• It returns the square root of the number passed in the
parameter.

22
eval()
• Python eval() function is used to parse an expression
string as python expression and then execute it.
• Example:
• eval(“1+2”) returns 3.

23

You might also like