Unit – 1
Introduction to Python
1.7 Common Python functions
Python functions
print(): Used to display output to the console.
print("Hello, World!") # Output: Hello, World!
2
Python functions
len(): Returns the length of a sequence (string, list, tuple, etc.).
text = "Python"
print(len(text)) # Output: 6
3
Python functions
input(): Allows the user to enter input from the console.
name = input("Enter your name: ")
print("Hello, " + name)
4
Python functions
type(): Returns the data type of a given object.
number = 42
print(type(number)) # Output: <class 'int'>
5
Python functions
int(), float(), str(): Convert values to integer, float, and string data types, respectively.
num_str = "42"
num_int = int(num_str)
print(num_int) # Output: 42
num_float = float(num_str)
print(num_float) # Output: 42.0
num_str = str(num_int)
print(num_str) # Output: "42"
6
Python functions
range(): Generates a sequence of numbers within a given range.
numbers = list(range(1, 6))
print(numbers) # Output: [1, 2, 3, 4, 5]
7
Python functions
sum(): Returns the sum of elements in an iterable.
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total) # Output: 15
8
Python functions
min(), max(): Returns the minimum and maximum element in an iterable,
respectively.
numbers = [5, 2, 8, 1, 9]
minimum = min(numbers)
maximum = max(numbers)
print(minimum) # Output: 1
print(maximum) # Output: 9
9
Python functions
sorted(): Returns a new sorted list from the elements of any iterable.
numbers = [5, 2, 8, 1, 9]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 2, 5, 8, 9]
10
Python functions
sum(): Returns the sum of elements in an iterable.
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total) # Output: 15
11
Python functions
The round() function is used to round a floating-point number to a specified number of decimal places (n).
It takes two arguments:
x: The number that you want to round.
n (optional): The number of decimal places to which you want to round x. If not specified, the number will be rounded
to the nearest integer.
Here are some examples of how the round() function works:
number = 3.14159
# Without specifying decimal places (n)
rounded_integer = round(number)
print(rounded_integer) # Output: 3
# Rounding to 2 decimal places
rounded_2_decimal_places = round(number, 2)
print(rounded_2_decimal_places) # Output: 3.14
# Rounding to 1 decimal place
rounded_1_decimal_place = round(number, 1)
print(rounded_1_decimal_place) # Output: 3.1
12
Thanks