You are on page 1of 8

Module No 1: Basics of Python

Numbers in python
Here are some common operations with numbers in Python:
1. Arithmetic Operations:
pythonCopy code
a = 5
b = 3

# Addition
c = a + b
print("Addition: ", c)

# Subtraction
d = a - b
print("Subtraction: ", d)

# Multiplication
e = a * b
print("Multiplication: ", e)

# Division
f = a / b
print("Division: ", f)

# Modulo (remainder)
g = a % b
print("Modulo: ", g)

# Exponentiation
h = a ** b
print("Exponentiation: ", h)
2. Comparison Operations:
pythonCopy code
a = 5
b = 3

# Equality
print(a == b) # False

# Inequality
print(a != b) # True

# Greater than
print(a > b) # True

# Less than
print(a < b) # False

# Greater than or equal to


print(a >= b) # True

# Less than or equal to


print(a <= b) # False
3. Type Conversion:
pythonCopy code
a = 5
b = "3"
# Integer to string
c = str(a)
print(c)

# String to integer
d = int(b)
print(d)

# Float to integer
e = int(3.14)
print(e)

# Integer to float
f = float(a)
print(f)
4. Built-in Math Functions:
pythonCopy code
import math

a = 3.14

# Absolute value
print(abs(a)) # 3.14

# Round to nearest integer


print(round(a)) # 3

# Ceiling (smallest integer greater than or equal to a)


print(math.ceil(a)) # 4

# Floor (largest integer less than or equal to a)


print(math.floor(a)) # 3

# Square root
print(math.sqrt(a)) # 1.77245385091 (approximately)
These are some of the basic operations you can perform with numbers in Python. There are many
other mathematical functions available in Python's math module, and you can also use external
libraries like NumPy for more advanced numerical operations.

Basic and built in functions in python

Python provides a rich set of built-in functions that are available for use without the need for
importing any external libraries. Here are some basic and commonly used built-in functions in
Python:
1. print(): Used to display output on the console.
pythonCopy code
print("Hello, world!")
2. input(): Used to get input from the user via the console.
pythonCopy code
name = input("Enter your name: ")
print("Hello, " + name)
3. len(): Used to get the length of a string, list, or other iterable.
pythonCopy code
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print("Length of the list: ", length)
4. type(): Used to get the type of an object.
pythonCopy code
x = 5
y = 3.14
z = "hello"
print(type(x)) # <class 'int'>
print(type(y)) # <class 'float'>
print(type(z)) # <class 'str'>
5. int(), float(), str(): Used for type conversion between integers, floats, and strings.
pythonCopy code
a = "5"
b = "3.14"
c = 10

int_a = int(a)
float_b = float(b)
str_c = str(c)

print(int_a) # 5
print(float_b) # 3.14
print(str_c) # '10'
6. range(): Used to generate a sequence of numbers.
pythonCopy code
for i in range(1, 6): # generates numbers from 1 to 5
print(i)
7. max() and min(): Used to find the maximum and minimum values from a sequence of
values.
pythonCopy code
numbers = [3, 7, 1, 9, 4, 5]
max_num = max(numbers)
min_num = min(numbers)
print("Maximum number: ", max_num)
print("Minimum number: ", min_num)
8. sum(): Used to find the sum of a sequence of numbers.
pythonCopy code
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print("Sum of numbers: ", total)
9. abs(): Used to get the absolute value of a number.
pythonCopy code
x = -5
y = 3.14
print(abs(x)) # 5
print(abs(y)) # 3.14
10. round(): Used to round a number to a specified number of decimal places.
pythonCopy code
a = 3.14159
b = 2.71828
print(round(a, 2)) # 3.14
print(round(b, 3)) # 2.718
These are just a few examples of the many built-in functions that Python provides. Python's
extensive standard library includes a wide variety of functions for various tasks, and you can also
import external libraries to access even more functionality.
Number formats

In Python, numbers can be represented in different formats, including integers, floating-point


numbers, and complex numbers. Here are some commonly used number formats in Python:
1. Integer: Integers are whole numbers without any decimal or fractional parts. They can be
represented using the int data type in Python. For example:
pythonCopy code
a = 5
b = -3
c = 0
2. Floating-point: Floating-point numbers are numbers with a decimal or fractional part. They
can be represented using the float data type in Python. For example:
pythonCopy code
x = 3.14
y = -2.5
z = 0.0
3. Complex: Complex numbers are numbers that have both a real and imaginary part. They can
be represented using the complex data type in Python. The imaginary part is denoted by
the suffix j or J. For example:
pythonCopy code
p = 2 + 3j
q = -1.5j
r = complex(4, -2)
4. Binary, Octal, and Hexadecimal: In addition to decimal representation, Python also allows
numbers to be represented in binary, octal, and hexadecimal formats using prefixes: 0b for
binary, 0o for octal, and 0x for hexadecimal. For example:
pythonCopy code
binary_num = 0b10101 # Binary representation of 21
octal_num = 0o35 # Octal representation of 29
hexadecimal_num = 0x1F # Hexadecimal representation of 31
Python also provides built-in functions for converting between different number formats, such as
bin() for binary, oct() for octal, and hex() for hexadecimal.
pythonCopy code
num = 42
binary = bin(num)
octal = oct(num)
hexadecimal = hex(num)

print(binary) # '0b101010'
print(octal) # '0o52'
print(hexadecimal) # '0x2a'
These are some of the common number formats in Python. Understanding and using different
number formats can be helpful in various programming tasks, such as working with binary data,
performing numerical computations, or dealing with complex numbers.
String
In Python, a string is a sequence of characters enclosed within single quotes (' '), double quotes ("
"), or triple quotes (''' ''', """ """). Strings are one of the basic data types in Python and are used to
represent text data. Here are some examples of working with strings in Python:
1. Creating a string:
pythonCopy code
# Using single quotes
str1 = 'Hello, world!'

# Using double quotes


str2 = "Python is awesome!"

# Using triple quotes for multiline strings


str3 = '''This is a
multiline string
in Python'''

# Using triple quotes for docstrings (used for documentation)


str4 = """This is a
docstring"""
2. Accessing characters in a string:
pythonCopy code
# Using indexing
print(str1[0]) # 'H'
print(str2[7]) # 'i'

# Using negative indexing


print(str1[-1]) # '!'
print(str2[-2]) # 'e'

# Using slicing
print(str1[0:5]) # 'Hello'
print(str2[7:]) # 'is awesome!'
3. String concatenation:
pythonCopy code
# Using '+' operator
str3 = str1 + " " + str2
print(str3) # 'Hello, world! Python is awesome!'
4. String methods: Python provides a rich set of built-in methods for strings to perform various
operations, such as manipulating, formatting, and searching for strings. Here are some
examples:
pythonCopy code
# Length of a string
print(len(str1)) # 13

# Converting to lowercase and uppercase


print(str1.lower()) # 'hello, world!'
print(str2.upper()) # 'PYTHON IS AWESOME!'

# Splitting a string
words = str1.split(',') # ['Hello', ' world!']

# Checking for substring


print('world' in str1) # True

# Replacing a substring
new_str1 = str1.replace('world', 'Python')
print(new_str1) # 'Hello, Python!'
5. String formatting: Python allows formatting strings using different methods, such as using %
operator, format() method, and f-strings (formatted string literals). Here's an example
using f-strings:
pythonCopy code
name = 'Alice'
age = 25
print(f"My name is {name} and I'm {age} years old.")
# Output: "My name is Alice and I'm 25 years old."
These are some of the basic operations that can be performed on strings in Python. Strings are
widely used for tasks such as input/output, data manipulation, text processing, and more in Python
programming.

Quotes:

In Python, quotes are used to denote strings. There are three types of quotes that can be used to
create strings: single quotes (' '), double quotes (" "), and triple quotes (''' ''', """ """). Here's a brief
overview of each type of quotes:
1. Single quotes (' '): Strings enclosed within single quotes represent a sequence of characters.
For example:
pythonCopy code
str1 = 'Hello, world!'
2. Double quotes (" "): Strings enclosed within double quotes also represent a sequence of
characters. Double quotes can be used interchangeably with single quotes to create strings.
For example:
pythonCopy code
str2 = "Python is awesome!"
3. Triple quotes (''' ''' or """ """): Triple quotes are used to create multiline strings or docstrings
(used for documentation). Triple quotes can span multiple lines and can contain line breaks
and other special characters. For example:
pythonCopy code
str3 = '''This is a
multiline string
in Python'''
pythonCopy code
str4 = """This is a
docstring"""
It's important to note that the choice of quotes to use for strings is mostly a matter of personal
preference or specific requirements of the codebase or project. All three types of quotes are
equivalent in Python and can be used interchangeably to create strings. However, if a string contains
a quote character within it, the other type of quote can be used to avoid escaping the inner quotes
with backslashes (\). For example:
pythonCopy code
str5 = "He said, 'Hello!'" # Using double quotes to avoid escaping inner
single quotes
str6 = 'She said, "Hi!"' # Using single quotes to avoid escaping inner
double quotes
In addition to these basic uses of quotes for strings, quotes are also used in other contexts in Python,
such as for defining dictionary keys or for denoting sets of values in list comprehensions, among
others. Understanding the usage of different types of quotes in Python is essential for working with
strings and other data types effectively.

File input output functions:

File input/output (I/O) functions in Python are used to read data from and write data to files on the
disk. Python provides built-in functions to perform file I/O operations, allowing you to read data
from files, write data to files, create new files, delete files, and perform other file-related operations.
Here are some commonly used file I/O functions in Python:
1. Opening a file: The open() function is used to open a file for reading, writing, or
appending. It takes two arguments: the filename and the mode in which the file should be
opened. The mode can be 'r' for reading, 'w' for writing, or 'a' for appending. For
example:
pythonCopy code
# Opening a file for reading
file1 = open('file.txt', 'r')

# Opening a file for writing


file2 = open('new_file.txt', 'w')

# Opening a file for appending


file3 = open('data.txt', 'a')
2. Reading from a file: The read() method is used to read the contents of a file. It can be
used on a file object created using the open() function. For example:
pythonCopy code
# Reading the entire contents of a file
content = file1.read()
print(content)

# Reading a specific number of characters from a file


content = file1.read(10) # Read the first 10 characters from the file
print(content)
3. Writing to a file: The write() method is used to write data to a file. It can be used on a
file object created using the open() function with mode 'w' or 'a'. For example:
pythonCopy code
# Writing data to a file
file2.write('This is a new file.\n')
file2.write('It contains some data.\n')
4. Closing a file: The close() method is used to close a file after reading or writing data. It
should be called on a file object created using the open() function. For example:
pythonCopy code
# Closing a file after reading
file1.close()

# Closing a file after writing


file2.close()
5. Checking if a file is closed: The closed attribute can be used to check if a file is closed or
not. It returns True if the file is closed and False otherwise. For example:
pythonCopy code
if file1.closed:
print("File is closed.")
else:
print("File is still open.")
6. Other file I/O functions: Python also provides other file I/O functions, such as
readline() for reading a single line from a file, writelines() for writing multiple
lines to a file, seek() for changing the file position, and tell() for getting the current
file position, among others.
It's important to properly handle file I/O operations, including opening, reading, writing, and
closing files, to ensure efficient and error-free file handling in Python programs. Additionally, it's
recommended to use the with statement for file I/O, which automatically takes care of closing the
file, even if an exception occurs during file operations. Here's an example:
pythonCopy code
with open('file.txt', 'r') as file:
content = file.read()
print(content)
# File is automatically closed when the block is exited
This ensures that the file is properly closed after use, even if an exception occurs within the with
block

You might also like