Introduction To Programming
Introduction To Programming
Step 1) To download and install Python, visit the official website of
Python https://www.python.org/downloads/ and choose your version. We
have chosen Python version 3.6.3
Step 2) Once the download is completed, run the .exe file to install Python. Now
click on Install Now.
2
Step 3) You can see Python installing at this point.
Step 4) When it finishes, you can see a screen that says the Setup was successful.
Now click on “Close”.
3
Step 2) Once the download is complete, run the exe for install PyCharm. The setup
wizard should have started. Click “Next”.
Step 3) On the next screen, Change the installation path if required. Click “Next”.
Step 4) On the next screen, you can create a desktop shortcut if you want and click
on “Next”.
4
Step 5) Choose the start menu folder. Keep selected JetBrains and click on
“Install”.
Step 7) Once installation finished, you should receive a message screen that
PyCharm is installed. If you want to go ahead and run it, click the “Run PyCharm
Community Edition” box first and click “Finish”.
Step 8) After you click on “Finish,” the Following screen will appear.
5
Script Mode
If you need to write a long piece of Python code or your Python script spans
multiple files, interactive mode is not recommended. Script mode is the way to
go in such cases. In script mode, You write your code in a text file then save it
with a .py extension which stands for "Python". Note that you can use any
text editor for this, including Sublime, Atom, notepad++, etc.
Interactive Mode
Interactive mode, also known as the REPL provides us with a quick way of
running blocks or a single line of Python code. The code executes via the
Python shell, which comes with Python installation. Interactive mode is handy
when you just want to execute basic Python commands or you are new to
Python programming and just want to get your hands dirty with this beautiful
language.
IDLE
IDLE is Python’s Integrated Development and Learning Environment.
IDLE has the following features:
coded in 100% pure Python, using the tkinter GUI toolkit
cross-platform: works mostly the same on Windows, Unix, and macOS
Python shell window (interactive interpreter) with colorizing of code input, output,
and error messages
multi-window text editor with multiple undo, Python colorizing, smart indent, call
tips, auto completion, and other features
search within any window, replace within editor windows, and search through
multiple files (grep)
debugger with persistent breakpoints, stepping, and viewing of global and local
namespaces
configuration, browsers, and other dialogs
Docstrings
Python docstrings are the string literals that appear right after the definition of
a function, method, class, or module. Let's take an example.
Example 1: Docstrings
def square(n):
'''Takes in a number n, returns the square of n'''
return n**2
Inside the triple quotation marks is the docstring of the function square() as it
appears right after its definition.
6
Abstraction
Abstraction in Python is a programming methodology in which details of the programming
codes are hidden away from the user, and only the essential things are displayed to the user.
Abstraction is concerned with ideas rather than events. It’s like a user running a program (Web
Browser) without seeing the background codes
Polymorphism
Polymorphism means existing in many forms. Variables, functions, and objects can exist in
multiple forms in Java and Python. There are two types of polymorphism which are run time
polymorphism and compile-time polymorphism. Run time can take a different form while the
application is running and compile-time can take a different form during compilation.
Encapsulation
This is a programming style where implementation details are hidden. It reduces software
development complexity greatly. With Encapsulation, only methods are exposed. The
programmer does not have to worry about implementation details but is only concerned with
the operations Encapsulation also ensures that your data is hidden from external modification.
Encapsulation is also known as Data-Hidden.
Encapsulation can be viewed as a shield that protects data from getting accessed by outside
code.
Inheritance
In Python, codes are written in objects or blocks if you are adopting OOP methodology. Objects
can interact with one another by using the properties of each block or extending the
functionalities of a block through inheritance. Inheritance ensures that codes are reused. The
properties of a class can be inherited and extended by other classes or functions. There are two
types of classes. One is the Parent or base class, and the other is the child class which can
inherit the properties of the parent class. Inheritance is a major pillar in Object-Oriented
programming.
Python Keywords
Python keywords are special reserved words that have specific meanings and
purposes and can’t be used for anything but those specific purposes. These
keywords are always available—you’ll never have to import them into your code.
List of keywords in python:
False class from or
None continue global pass
True def if raise
and del import return
as elif in try
assert else is while
async except lambda with
await finally nonlocal yield
break for not
7
Python str()
Python str() function returns the string version of the object. Parameters: object: The
object whose string representation is to be returned. encoding: Encoding of the given
object.
8
Simple if: If statements are control flow statements that help us to run a particular
code, but only when a certain condition is met or satisfied. A simple if only has one
condition to check.
if-else: The if-else statement evaluates the condition and will execute the body of if if
the test condition is True, but if the condition is False, then the body of else is executed.
9
if-elif-else: The if-elif-else statement is used to conditionally execute a statement or a
block of statements.
3. Repetition
A repetition statement is used to repeat a group(block) of programming instructions.
In Python, we generally have two loops/repetitive statements:
for loop
while loop
for loop: A for loop is used to iterate over a sequence that is either a list, tuple,
dictionary, or a set. We can execute a set of statements once for each item in a list, tuple,
or dictionary.
10
What are Classes and Objects?
Classes and objects are the two main aspects of object-oriented
programming.
Look at the following illustration to see the difference between class and
objects:
Class: Fruit
Objects: Apple, Banana, Mango
Another example:
Class: Car
Objects: Volvo, Audi, Toyota
A class describes the contents of the objects that belong to it: it describes
an aggregate of data fields (called instance variables), and defines the
operations (called methods).
Functions/Methods
Methods are functions that belongs to the class. a method is an action
which an object is able to perform.
A function is simply a “chunk” of code that you can use over and over
again, rather than writing it out multiple times. Functions enable
programmers to break down or decompose a problem into smaller chunks,
each of which performs a particular task.
11
Hello World: Create your First Python Program
Creating First Program
Step 1) Open PyCharm Editor. You can see the introductory screen for PyCharm. To
create a new project, click on “Create New Project”.
1. You can select the location where you want the project to be created. If you
don’t want to change location than keep it as it is but at least change the
name from “untitled” to something more meaningful, like “FirstProject”.
2. PyCharm should have found the Python interpreter you installed earlier.
3. Next Click the “Create” Button.
12
Step 3) Now Go up to the “File” menu and select “New”. Next, select “Python File”.
Step 4) A new pop up will appear. Now type the name of the file you want (Here we
give “HelloWorld”) and hit “OK”.
Step 6) Now Go up to the “Run” menu and select “Run” to run your program.
13
Step 7) You can see the output of your program at the bottom of the screen.
Syntax:
print(object(s))
Output:
Welcome to K2 CONCEPT
14
How to print blank lines
Sometimes you need to print one blank line in your Python program. Following is
an example to perform this task using Python print format.
Once the integer is declared as string, it can concatenate both “CSC” + str(“202”)=
“CSC202” in the output.
15
a="CSC"
b = 202
print(a+str(b))
Delete a variable
You can also delete Python variables using the command del “variable name”.
In the below example of Python delete variable, we deleted variable f, and when
we proceed to print it, we get error “variable name is not defined” which means
you have deleted the variable.
f = 11;
print(f)
del f
print(f)
Summary:
Variables are referred to “envelop” or “buckets” where information can be
maintained and referenced. Like any other programming language Python also uses
a variable to store the information. Variables can be declared by any name or even
alphabets like a, aa, abc, etc. Variables can be re-declared even after you have
declared them for once
16
Python constants can be understood as types of variables that hold the value which
can not be changed. Usually Python constants are referenced from other files. Python
define constant is declared in a new or separate file which contains functions,
modules, etc.
Types of variables in Python or Python variable types : Local & Global
Declare local variable when you want to use it for current function
Declare Global variable when you want to use the same variable for rest of the
program
To delete a variable, it uses keyword “del”.
Similarly, you can use other arithmetic operators like for multiplication(*), division
(/), substraction (-),modulus (%), exponential(**) etc.
num1 = 4
num2 = 5
print(num1 + num2)
Example: Here in example we get true or false based on the value of a and b
a = True
b = False
print(('a and b is', a and b))
print(('a or b is', a or b))
print(('not a is', not a))
Membership Operators
These operators test for membership in a sequence such as lists, strings or tuples.
There are two membership operators that are used in Python. (in, not in). It gives
the result based on the variable present in specified sequence or string
Example: For example here we check whether the value of x=4 and value of y=8 is
available in list or not, by using in and not in operators.
x=4
y=8
list = [1, 2, 3, 4, 5 ];
if ( x in list ):
print("Line 1 - x is available in the given list")
else:
print("Line 1 - x is not available in the given list")
if ( y not in list ):
print("Line 2 - y is not available in the given list")
else:
print("Line 2 - y is available in the given list")
18
Declare the value for x and y
Declare the value of list
Use the “in” operator in code with if statement to check the value of x existing in
the list and print the result accordingly
Use the “not in” operator in code with if statement to check the value of y exist in
the list and print the result accordingly
Run the code- When the code run it gives the desired output
Identity Operators
Identity Operators in Python are used to compare the memory location of two
objects. The two identity operators used in Python are (is, is not).
Operator is: It returns true if two variables point the same object and false
otherwise
Operator is not: It returns false if two variables point the same object and
true otherwise
Following operands are in decreasing order of precedence.
Operators in the same box evaluate left to right
x = 20
y = 20
if ( x is y ):
print("x & y SAME identity")
y=30
if ( x is not y ):
print("x & y have DIFFERENT identity")
19
Operator precedence
The operator precedence determines which operators need to be evaluated first.
To avoid ambiguity in values, precedence operators are necessary. Just like in
normal multiplication method, multiplication has a higher precedence than
addition. For example in 3+ 4*5, the answer is 23, to change the order of
precedence we use a parentheses (3+4)*5, now the answer is 35. Precedence
operator used in Python are (unary + – ~, **, * / %, + – , &) etc.
v=4
w=5
x=8
y=2
z=0
z = (v+w) * x / y;
print("Value of (v+w) * x/ y is ", z)
20
What is Python If Statement?
Python if Statement is used for decision-making operations. It contains a body of
code which runs only when the condition given in the if statement is true. If the
condition is false, then the optional else statement runs which contains some code
for the else condition.
When you want to justify one condition while the other condition is not true, then
you use Python if else statement.
Python if Statement Syntax:
if expression
Statement
else
Statement
main()
main()
21
Python Nested if Statement
Following example demonstrates nested if Statement Python
total = 100
#country = "US"
country = "AU"
if country == "US":
if total <= 50:
print("Shipping Cost is $50")
elif total <= 100:
print("Shipping Cost is $25")
elif total <= 150:
print("Shipping Costs $5")
else:
print("FREE")
if country == "AU":
if total <= 50:
print("Shipping Cost is $100")
else:
print("FREE")
Summary:
A conditional statement in Python is handled by if statements and we saw various
other ways we can use conditional statements like Python if else over here.
“if condition” – It is used when you need to print out the result when one of
the conditions is true or false.
“else condition”- it is used when you want to print out the statement when
your one condition fails to meet the requirement
“elif condition” – It is used when you have third possibility as the outcome.
You can use multiple elif conditions to check for 4th,5th,6th possibilities in your
code
We can use minimal code to execute conditional statements by declaring all
condition in single statement to run the code
Python If Statement can be nested
22
What is Loop?
Loops can execute a block of code number of times until a certain condition is met.
Their usage is fairly common in programming. Unlike other programming language
that have For Loop, while loop, dowhile, etc.
Example:
#Example file for working with loops
x=0
#define a while loop
# while(x <4):
# print x
# x = x+1
23
For Loop iterates with number declared in the range.
For example,
For Loop for x in range (2,7)
When this code is executed, it will print the number between 2 and 7 (2,3,4,5,6). In
this code, number 7 is not considered inside the range.
For Loops can also be used for a set of other things and not just number. We will
see thin in next section.
Output
Jan
Feb
Mar
April
May
June
Example:
#use a for loop over a collection
#Months = ["Jan","Feb","Mar","April","May","June"]
#for m in Months:
#print m
24
In this example, we declared the numbers from 10-20, but we want that our for
loop to terminate at number 15 and stop executing further. For that, we declare
break function by defining (x==15): break, so as soon as the code calls the number
15 it terminates the program Code Line 10 declare variable x between range (10,
20)
Output
11
12
13
14
16
17
18
19
Continue statement can be used in for loop when you want to fetch a specific value
from the list.
In our example, we have declared value 10-20, but between these numbers we only
want those number that are NOT divisible by 5 or in other words which don’t give
zero when divided by 5.
So, in our range (10,11, 12….19,20) only 3 numbers falls (10,15,20) that are divisible
by 5 and rest are not.
So except number 10,15 & 20 the “for loop” will not continue and print out those
number as output.
25
Example: Enumerate function is used for the numbering or indexing the members
in the list.
Suppose, we want to do numbering for our month ( Jan, Feb, Marc, ….June), so we
declare the variable i that enumerate the numbers while m will print the number of
month in list.
#use a for loop over a collection
Months = ["Jan","Feb","Mar","April","May","June"]
for i, m in enumerate (Months):
print(i,m)
26
OOPs in Python
OOPs in Python is a programming approach that focuses on using objects and
classes as same as other general programming languages. The objects can be any
real-world entities. Python allows developers to develop applications using the
OOPs approach with the major focus on code reusability. It is very easy to create
classes and objects in Python.
What is a Class?
A Class in Python is a logical grouping of data and functions. It gives the freedom to
create data structures that contains arbitrary content and hence easily accessible.
27
For example, for any bank employee who want to fetch the customer details online
would go to customer class, where all its attributes like transaction details,
withdrawal and deposit details, outstanding debt, etc. would be listed out.
Python Constructors
A constructor is a class function that instantiates an object to predefined values.
It begins with a double underscore (_). It __init__() method
What is Polymorphism?
Polymorphism can be defined as a condition that occurs in many different forms. It
is a concept in Python programming wherein an object defined in Python can be
used in different ways. It allows the programmer to define multiple methods in a
derived class, and it has the same name as present in the parent class. Such
scenarios support method overloading in Python.
In this Python Polymorphism tutorial, you will learn:
Polymorphism in Operators
An operator in Python helps perform mathematical and several other
programming tasks. For example, the ‘+’ operator helps in performing addition
between two integer types in Python, and in the same way, the same operator
helps in concatenating strings in Python programming.
Let us take an example of + (plus) operator in Python to display an application of
Polymorphism in Python as shown below:
Python Code:
p = 55
q = 77
r = 9.5
g1 = "K2"
g2 = "Concept!"
print("the sum of two numbers",p + q)
print("the data type of result is",type(p + q))
28
print("The sum of two numbers",q + r)
print("the data type of result is", type (q + r))
print("The concatenated string is", g1 + g2)
print("The data type of two strings",type(g1 + g2))
Output:
the sum of two numbers 132
the data type of result is <class 'int'>
29
Python Code:
mut_list = [1, 2, 3]
print("The list in Python",mut_list)
mut_list[0] = 'Gurru99'
mut_list
print("The list in Python after changing value",mut_list)
Output:
The list in Python [1, 2, 3]
The list in Python after changing value ['Gurru99', 2, 3]
As we can see in the above-given example, the mutable list in Python had values of
1,2,3. The first element of the mutable list is changed from 1 to K2Concept, and it
does not create a new object when a new value is initialized.
Here we can use the id method to utilize it. Following illustrates the use of the id
method for mutable objects as shown below: –
Python Code:
mut_list = [1, 2, 3]
print("The list in Python",mut_list)
print("the id of the list is ",id(mut_list))
mut_list[0] = 'Gurru99'
mut_list
print("The mut list in Python after changing value",mut_list)
print("the id of the list is post change in value",id(mut_list))
Output
The list in Python [1, 2, 3]
the id of the list is 139931568729600
The list in Python after changing value ['Gurru99', 2, 3]
the id of the list is post change in value 139931568729600
The following figure illustrates the mutable object in Python as shown below: –
Immutable objects in Python
Immutable objects in Python are objects wherein the instances do not change over
the period. Immutable instances of a specific type, once created, do not change,
and this can be verified using the id method of Python.
Let us take an example of integer type objects in Python that illustrates the
concept of immutable objects in Python as shown below: –
Python Code:
a=244
print("the number before change is",a)
print("the id of number before change is",id(a))
a=344
print("the number after change is",a)
print("the id of number after change is",id(a))
Output
the number before a change is 244
30
the id of number before change is 9796768
the number before change is 344
the id of number before change is 140032307887024
It could be seen above that there is change in “a.” Let’s study how the mechanism
works:
There is no change in the object’s value when the initialization of “a” with
344.
Instead, a new object is created and is bounded with “a.”
The other object assigned as 244 would no longer be accessible.
The above example utilized an integer object.
At a=244, a new object is created and referenced to “a” as shown below: –
Post using a=344, there is a new object referenced with “a”. The following diagram
represents the same: –
Therefore, whenever there is the assignment of a new value to the name of int type,
there is a change in the binding of the name with another object. The same
principle aligns with tuples, strings, float, and Boolean hence termed immutable.
31
What is Python Main Function?
Python main function is a starting point of any program. When the program is run,
the python interpreter runs the code sequentially. Main function is executed only
when it is run as a Python program. It will not run the main function if it is imported
as a module.
Example: Let us define a function by using the command ” def func1():” and call
the function. The output of the function will be “I am learning Python function”.
32
The function print func1() calls our def func1(): and print the command ” I am
learning Python function None.”
There are set of rules in Python to define a function.
Any args or input parameters should be placed within these parentheses
The function first statement can be an optional statement- docstring or the
documentation string of the function
The code within every function starts with a colon (:) and should be indented
(space)
The statement return (expression) exits a function, optionally passing back a
value to the caller. A return statement with no args is the same as return
None.
Significance of Indentation (Space) in Python
Before we get familiarize with Python functions, it is important that we understand
the indentation rule to declare Python functions and these rules are applicable to
other elements of Python as well like declaring conditions, loops or variable.
Python follows a particular style of indentation to define the code, since Python
functions don’t have any explicit begin or end like curly braces to indicate the
start and stop for the function, they have to rely on this indentation. Here we
take a simple example with “print” command. When we write “print” function right
below the def func 1 (): It will show an “indentation error: expected an indented
block“.
33
Now, when you add the indent (space) in front of “print” function, it should print as
expected.
At least, one indent is enough to make your code work successfully. But as a
best practice it is advisable to leave about 3-4 indent to call your function.
It is also necessary that while declaring indentation, you have to maintain the
same indent for the rest of your code. For example, in below screen shot when
we call another statement “still in func1” and when it is not declared right below
the first print statement it will show an indentation error “unindent does not
match any other indentation level.”
Now, when we apply same indentation for both the statements and align them in
the same line, it gives the expected output.
34
How Function Return Value?
Return command in Python specifies what value to give back to the caller of the
function.
Let’s understand this with the following example
Step 1) Here – we see when function is not “return”. For example, we want the
square of 4, and it should give answer “16” when the code is executed. Which it
gives when we simply use “print x*x” code, but when you call function “print
square” it gives “None” as an output. This is because when you call the function,
recursion does not happen and fall off the end of the function. Python returns
“None” for failing off the end of the function.
Step 2) To make this clearer we replace the print command with assignment
command. Let’s check the output.
35
When you run the command “print square (4)” it actually returns the value of the
object since we don’t have any specific function to run over here it returns “None”.
Step 3) Now, here we will see how to retrieve the output using “return” command.
When you use the “return” function and execute the code, it will give the output
“16.”
Step 4) Functions in Python are themselves an object, and an object has some
value. We will here see how Python treats an object. When you run the command
“print square” it returns the value of the object. Since we have not passed any
argument, we don’t have any specific function to run over here it returns a default
value (0x021B2D30) which is the location of the object. In practical Python
program, you probably won’t ever need to do this.
36
Arguments in Functions
The argument is a value that is passed to the function when it’s called.
In other words on the calling side, it is an argument and on the function side it is a
parameter.
Let see how Python Args works –
Step 1) Arguments are declared in the function definition. While calling the
function, you can pass the values for that args as shown below
Example: x has no default values. Default values of y=0. When we supply only one
argument while calling multiply function, Python assigns the supplied value to x
while keeping the value of y=0. Hence the multiply of x*y=0
Step 3) This time we will change the value to y=2 instead of the default value y=0,
and it will return the output as (4×2)=8.
37
Step 4) You can also change the order in which the arguments can be passed in
Python. Here we have reversed the order of the value x and y to x=4 and y=2.
Step 5) Multiple Arguments can also be passed as an array. Here in the example we
call the multiple args (1,2,3,4,5) by calling the (*args) function.
Example: We declared multiple args as number (1,2,3,4,5) when we call the (*args)
function; it prints out the output as (1,2,3,4,5)
38
Python abs()
Python abs() is a built-in function available with the standard library of python. It
returns the absolute value for the given number. Absolute value of a number is the
value without considering its sign. The number can be integer, floating point
number or complex number. If the given number is complex, then it will return its
magnitude.
Syntax:
abs(value)
Parameters: (value)
The input value to be given to abs() to get the absolute value. It can be an integer, a
float, or a complex number.
Return Value:
It will return the absolute value for the given number.
If the input is an integer, the return value also will be an integer.
If the input is a float, the return value will also be float.
If the input is a complex number, the return value will be the magnitude of
the input.
Examples:
Code Example 1: Integer and Float number
To get the absolute value of an integer and float number check this code:
# testing abs() for an integer and float
int_num = -25
float_num = -10.50
complex_num = (3+10j)
Round()
Round() is a built-in function available with python. It will return you a float
number that will be rounded to the decimal places which are given as input.
If the decimal places to be rounded are not specified, it is considered as 0, and it
will round to the nearest integer.
Syntax:
round(float_num, num_of_decimals)
Parameters
float_num: the float number to be rounded.
num_of_decimals: (optional) The number of decimals to be considered
while rounding. It is optional, and if not specified, it defaults to 0, and the
rounding is done to the nearest integer.
Description
The round() method takes two argument
the number to be rounded and
the decimal places it should consider while rounding.
The second argument is optional and defaults to 0 when not specified, and in such
case, it will round to the nearest integer, and the return type will also be an integer.
When the decimal places, i.e. the second argument, is present, it will round to the
number of places given. The return type will be a float.
If the number after the decimal place given
>=5 than + 1 will be added to the final value
<5 than the final value will return as it is up to the decimal places mentioned.
Return value
It will return an integer value if the num_of_decimals is not given and a float value
if the num_of_decimals is given. Please note the value will be rounded to +1 if the
40
value after the decimal point is >=5 else it will return the value as it is up to the
decimal places mentioned.
41
the sequence will be incremented by 2. If the step value is not given, the value for
step defaults to 1.
for i in range(3, 10, 2):
print(i, end =" ")
Output:
3579
So far, we have seen how range() function gives the incremented value for the stop
value given. Let us now try an example to get the decremented value in the range
given.
Incrementing the values in range using a positive step.
The parameter step in range() can be used to increment /decrement the values. By
default, it is a positive value 1. So it will always give incremented values.
The step value has to be positive incase you want to want incremented values as
ouput.
for i in range(1, 30, 5):
print(i, end =" ")
Output:
1 6 11 16 21 26
Reverse Range: Decrementing the values using negative step.
The parameter step with negative value in range() can be used to get decremented
values. In the example below the step value is negative so the output will be in
decremented from the range value given.
for i in range(15, 5, -1):
print(i, end =" ")
Output:
15 14 13 12 11 10 9 8 7 6
The start value is 15, the stop value is 5 and the step value is negative number i.e -1.
With above inputs range() function will decrement the value from 15 onwards till it
reaches the stop value , but here the difference is the last value will be stop + 1.
for i in range(len(arr_list)):
print(arr_list[i], end =" ")
Output:
MysqlMongodb PostgreSQL Firebase
In above example we have used len(arr_list) as the stop value. The for loop will
iterate till the stop value i.e the length of the array and that will be 4, as we have
four items in the arr_list. The start value will be 0 and step will be 1.So the values
will start from 0 and will stop at 3 i.e length of array -1 meaning 4 -1 = 3.
This module provides access to the mathematical functions defined by the C standard.
These functions cannot be used with complex numbers; use the functions of the same
name from the cmath module if you require support for complex numbers. The
distinction between functions which support complex numbers and those which don’t is
made since most users do not want to learn quite as much mathematics as required to
understand complex numbers. Receiving an exception instead of a complex result
allows earlier detection of the unexpected complex number used as a parameter, so
that the programmer can determine how and why it was generated in the first place.
The following functions are provided by this module. Except when explicitly noted
otherwise, all return values are floats.
math.ceil(x)
Return the ceiling of x, the smallest integer greater than or equal to x. If x is not a
float, delegates to x.__ceil__(), which should return an Integral value.
math.comb(n, k)
Return the number of ways to choose k items from n items without repetition and
without order.
Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates to zero when k > n.
Also called the binomial coefficient because it is equivalent to the coefficient of k-th term
in polynomial expansion of the expression (1 + x) ** n.
Raises TypeError if either of the arguments are not integers. Raises ValueError if either
of the arguments are negative.
math.copysign(x, y)
Return a float with the magnitude (absolute value) of x but the sign of y. On platforms
that support signed zeros, copysign(1.0, -0.0) returns -1.0.
math.fabs(x)
Return the absolute value of x.
43
math.factorial(x)
Return x factorial as an integer. Raises ValueError if x is not integral or is negative.
math.floor(x)
Return the floor of x, the largest integer less than or equal to x. If x is not a float,
delegates to x.__floor__(), which should return an Integral value.
math.gcd(*integers)
Return the greatest common divisor of the specified integer arguments. If any of the
arguments is nonzero, then the returned value is the largest positive integer that is a
divisor of all arguments. If all arguments are zero, then the returned value is 0. gcd()
without arguments returns 0.
math.isfinite(x)
Return True if x is neither an infinity nor a NaN, and False otherwise. (Note that 0.0 is
considered finite.)
math.isinf(x)
Return True if x is a positive or negative infinity, and False otherwise.
math.isnan(x)
Return True if x is a NaN (not a number), and False otherwise.
math.isqrt(n)
Return the integer square root of the nonnegative integer n. This is the floor of the exact
square root of n, or equivalently the greatest integer a such that a² ≤ n.
For some applications, it may be more convenient to have the least integer a such that
n ≤ a², or in other words the ceiling of the exact square root of n. For positive n, this can
be computed using a = 1 + isqrt(n - 1).
math.lcm(*integers)
Return the least common multiple of the specified integer arguments. If all arguments
are nonzero, then the returned value is the smallest positive integer that is a multiple of
all arguments. If any of the arguments is zero, then the returned value is 0. lcm() without
arguments returns 1.
math.perm(n, k=None)
Return the number of ways to choose k items from n items without repetition and with
order.
If k is not specified or is None, then k defaults to n and the function returns n!.
Raises TypeError if either of the arguments are not integers. Raises ValueError if either
of the arguments are negative.
math.log(x[, base])
With one argument, return the natural logarithm of x (to base e).
With two arguments, return the logarithm of x to the given base, calculated as
log(x)/log(base).
44
math.log1p(x)
Return the natural logarithm of 1+x (base e). The result is calculated in a way which is
accurate for x near zero.
math.log2(x)
Return the base-2 logarithm of x. This is usually more accurate than log(x, 2).
See also int.bit_length() returns the number of bits necessary to represent an integer in
binary, excluding the sign and leading zeros.
math.log10(x)
Return the base-10 logarithm of x. This is usually more accurate than log(x, 10).
math.pow(x, y)
Return x raised to the power y. Exceptional cases follow Annex ‘F’ of the C99 standard
as far as possible. In particular, pow(1.0, x) and pow(x, 0.0) always return 1.0, even
when x is a zero or a NaN. If both x and y are finite, x is negative, and y is not an integer
then pow(x, y) is undefined, and raises ValueError.
Unlike the built-in ** operator, math.pow() converts both its arguments to type float. Use
** or the built-in pow() function for computing exact integer powers.
math.sqrt(x)
Return the square root of x.
Trigonometric functions
math.acos(x)
Return the arc cosine of x, in radians. The result is between 0 and pi.
math.asin(x)
Return the arc sine of x, in radians. The result is between -pi/2 and pi/2.
math.atan(x)
Return the arc tangent of x, in radians. The result is between -pi/2 and pi/2.
math.cos(x)
Return the cosine of x radians.
math.sin(x)
Return the sine of x radians.
math.tan(x)
Return the tangent of x radians.
Angular conversion
math.degrees(x)
Convert angle x from radians to degrees.
math.radians(x)
Convert angle x from degrees to radians.
Hyperbolic functions
Hyperbolic functions are analogs of trigonometric functions that are based on
hyperbolas instead of circles.
math.acosh(x)
45
Return the inverse hyperbolic cosine of x.
math.asinh(x)
Return the inverse hyperbolic sine of x.
math.atanh(x)
Return the inverse hyperbolic tangent of x.
math.cosh(x)
Return the hyperbolic cosine of x.
math.sinh(x)
Return the hyperbolic sine of x.
math.tanh(x)
Return the hyperbolic tangent of x.
Constants
math.pi
The mathematical constant π = 3.141592…, to available precision.
math.e
The mathematical constant e = 2.718281…, to available precision.
math.nan
A floating-point “not a number” (NaN) value. Equivalent to the output of float('nan').
46