introduction to python
introduction to python
TO
PYTHON
Python is a popular programming language that is easy to use and can be used for
many different tasks.
Python was created to be easy to read, and its simple rules make it possible for
programmers to write code in fewer lines.
Python is a programming language that lets you work quickly and integrate systems
more efficiently.
There are two major Python versions: “Python 2” and “Python 3”. Both are quite
different.
Python programming –
Interpreter: Finding: before start with python and its programming, the major thing
that require is interpreter.
There are certain online interpreters like “geeksforgeeks”, “programiz” etc…. that can be
used to run Python programs without installing an interpreter.
Eg:
Windows: There are several free programs available to run Python scripts, such as IDLE
(Integrated Development Environment), which comes with the Python software you can
download from http://python.org/.
1|Page
analyze the script line –
# indicates that his statement is ignored by the interpreter and serves as
documentation for our code.
Print() is used to print or display something on the screen(console),
This function automatically moves to a new line after printing the message (unlike in C). In
Python 2, "print" is a keyword, so you don't need parentheses. But in Python 3, "print" is a
function, so you must use parentheses when using it.
Features: You can run the program directly from the source code. Python first turns the
code into a special form called bytecode, which is then translated into the computer's
language to run. There's no need to worry about connecting or loading libraries and other
technical details. (Interpreted)
“Bytecode” is a set of instructions that acts as a bridge between source code and
machine execution. It's a compiled version of the original Python script, which is
saved with a “[.pyc]” extension.
Executed on multiple operating system platforms, free and open source, closer to
English language, focus more on solving the problem than on the syntax.
The Python Standard Library is very large and includes many useful tools. This is
called the "batteries included" philosophy. It provides help for tasks like regular
expressions, creating documentation, testing, working with databases, web
browsers, emails, HTML, audio files, security, graphical interfaces, and more. In
addition to the standard library, there are other great libraries, like the Python
Imaging Library, which makes it easy to work with images.
Advantages:
o Extensive support libraries(NumPy for numerical calculations, Pandas for data
analytics etc)
o Open source and community development
o Versatile, Easy to read, learn and write
o User-friendly data structures
2|Page
o High-level language
o Dynamically typed language(No need to mention data type based on the value
assigned, it takes data type)
o Object-oriented language
o Portable and Interactive
3|Page
BASICS
Let’s get into setup and intro - deep
Install “python3.5” the setup and in the start menu type IDLE.IDLE, you can think it as a
Python's IDE to run the Python Scripts.
Python programs are not compiled, rather they are interpreted. Now, let us move to writing a
python code and running it. Please make sure that python is installed on the system you are
working on.
Python files are stored with the extension ".py". Open a text editor and save a file with the
name "hello.py". Open it and write the following code:
Open command prompt and move to the directory where the file is stored by using the 'cd'
command and then run the file by writing the file name as a command.
Drive into variables in python: In Python, you don't need to declare variables
beforehand; you can use them directly. Also, variables in Python are case-sensitive, meaning
"myVariable" and "myvariable" would be treated as different variables, just like in most other
programming languages.
For example, you can create a variable and assign it a value like this:
x = 5 # x is an “integer”
4|Page
Python variables are case-sensitive, meaning that “myVariable” and “myvariable” are
considered different variables.
In Python, an expression always results in a value, which can then be assigned to a variable,
printed, or used in another calculation.
Conditions in Python are used to check if certain conditions are true or false, and to execute
specific code based on that. These are usually written using if, elif (else if), and else
statements.
if statement:
5|Page
elif statement:
else statements:
Comparison operators:
6|Page
Conditions are often based on comparison operators like:
== (equal to)
!= (not equal to)
> (greater than)
< (less than)
>= (greater than or equal to)
<= (less than or equal to)
In Python, functions are a block of reusable code that performs a specific task. Functions help
organize code, make it more modular, and avoid repetition. They can take input parameters,
perform operations, and return a result.
Function for checking the divisibility
Notice the indentation after function declaration
and if and else statements
7|Page
1. Def
2. calling
8|Page
5. Default Parameters
You can assign default values to parameters. If no argument is provided for that parameter,
the default value will be used.
def greet(name="sony"):
"""
"""
print(f"Hello, {name}!")
greet()
greet("sweety")
6. Variable-Length Arguments
Functions can accept a variable number of arguments using *args for non-keyword arguments
and **kwargs for keyword arguments.
*args
9|Page
**kwargs
10 | P a g e
9. Recursion
A function can call itself, which is called recursion. This is useful for tasks like calculating
factorials or traversing data structures like trees.
def factorial(n):
"""
"""
if n == 0:
return 24
else:
return n * factorial(n - 1)
result = factorial(7)
print(result)
# Output: 120960
10. Docstrings
Functions can have docstrings (documentation strings) to describe their behavior, which helps
in understanding the code and for documentation tools.
11 | P a g e
11. Function Annotations
Python allows you to add optional type annotations to specify the expected types of the
parameters and the return value.
So, python is a very simplified and less cumbersome language to code in. This
easiness of python is itself promoting its wide use.
12 | P a g e
Data Types
Into data types: python- In Python, data types define the type of data a variable can hold.
Each data type supports a set of operations that can be performed on that data. Since
everything is an object in Python, these data types are implemented as classes, and variables
are instances (objects) of these classes.
In Python, the numeric data types represent different kinds of numbers, which can be
classified into three main types: integers, floats, and complex numbers. These data types
are defined as classes in Python: int, float, and complex
Let's dive deeper into each of these numeric types and understand their characteristics:
Integers (int)
Definition: Integers represent whole numbers without any fractional or
decimal parts.
Range: In Python, integers can be of any length (limited only by the memory
available), unlike in some other languages where integer size is fixed.
Example: Positive numbers, negative numbers, and zero.
Floating-Point Numbers (float)
Definition: A float represents real numbers, which can contain a fractional
part. Floats are numbers that are written with a decimal point or are expressed
using scientific notation.
Scientific Notation: In scientific notation, e or E is used to indicate powers of
10. For example, 1e3 represents 1×103=10001 \times 10^3 = 1000.
Precision: Floats have limited precision due to how computers represent real
numbers.
13 | P a g e
Complex Numbers (complex)
Definition: Complex numbers are numbers that have a real part and an
imaginary part. In Python, they are represented by the complex class and
written in the form a + bj, where a is the real part and b is the imaginary part,
and j is the imaginary unit (i.e., the square root of -1).
Example: 2 + 3j is a complex number where 2 is the real part and 3 is the
imaginary part.
Determining the Data Type using type()
In Python, you can use the built-in function type() to determine the type of a
variable or value. This function returns the class type of the object.
14 | P a g e
In Python, a sequence is an ordered collection of elements, where each element is
identified by its position or index. Sequences are a fundamental concept in Python and allow
you to store multiple values in an organized manner. These sequences can hold values of the
same or different data types.
1. String (str)
Definition: A string is a sequence of characters. In Python, strings are immutable,
meaning once created, the elements of a string cannot be changed.
Representation: Strings are enclosed in single quotes (') or double quotes (").
Indexing: You can access characters in a string using an index. Indices start at 0 for
the first character and can also be accessed using negative indices (starting from -1 for
the last character).
15 | P a g e
Slicing (my_string[0:5] returns 'sweety')
Concatenation ("Hello" + " World!" results in "sweety sweet!")
Best examples:
16 | P a g e
Indexing with Slicing
You can also access a range of characters from a string using slicing. Slicing allows you to
extract a substring from a string by specifying a start index, an end index, and an optional
step.
SYNTAX
start: The starting index (inclusive).
end: The ending index (exclusive).
step: The step between each character.
A. Indexing: You can access individual characters in a string by using square brackets
and specifying the index.
Positive indexes start from 0 (left to right).
Negative indexes start from -1 (right to left).
B. Slicing: You can extract a part of the string (substring) by specifying the start, end,
and step in slicing.
General example:
17 | P a g e
18 | P a g e
Python string
A string is a sequence of characters. Python treats anything inside quotes as a string. This
includes letters, numbers, and symbols. Python has no character data type so single character
is a string of length 1.
a. Multi-line Strings
If we need a string to span multiple lines then we can use triple quotes (”’ or “””).
Python
Note: Accessing an index out of range will cause an IndexError. Only integers are allowed
as indices and using a float or other types will result in a TypeError.
a. Access string with Negative Indexing
Python allows negative address references to access characters from back of the String, e.g. -
1 refers to the last character, -2 refers to the second last character, and so on.
Python
b. String Slicing
Slicing is a way to extract portion of a string by specifying the start and end indexes. The
syntax for slicing is string[start:end], where start starting index and end is stopping index
(excluded).
20 | P a g e
1:4 = to write letters required,
here we see “wee”
:3 = to write prefix letters from 3
3: = to write suffix letters from 3
:: -1 = to write reverse letters
:: 1 / 0:12 = to write full word
3. String Immutability
Strings in Python are immutable. This means that they cannot be changed after they are
created. If we need to manipulate strings then we can use methods like concatenation,
slicing, or formatting to create new strings based on the original.
LOOK THE DIFF and concept -
4. Deleting a String
In Python, it is not possible to delete individual characters from a string since strings are
immutable. However, we can delete an entire string variable using the “del” keyword.
Note: After deleting the string using del and if we try to access s then it will result in
a NameError because the variable no longer exists.
5. Updating a String
To update a part of a string we need to create a new string since strings are immutable.
21 | P a g e
Explanation:
For s1, the original string s is sliced from index 1 to end of string and then
concatenate “H” to create a new string s1.
For s2, we can created a new string s2 and used replace() method to replace
‘geeks’ with ‘GeeksforGeeks’.
6. Common String methods
Python provides a various built-in method to manipulate strings. Below are some of the most
useful methods.
len(): The len() function returns the total number of characters in a string.
No.of letters
a. upper() and lower(): upper() method converts all characters to uppercase. lower()
method converts all characters to lowercase.
b. strip() and replace(): strip() removes leading and trailing whitespace from the string
and replace(old, new) replaces all occurrences of a specified substring with another.
string methods, python String methods.
22 | P a g e
7. Concatenating and Repeating Strings
We can concatenate strings using + operator and repeat them using * operator.
Strings can be combined by using + operator.
* operator:
8. Formatting Strings
Python provides several ways to include variables inside strings.
a. Using f-strings
The simplest and most preferred way to format strings is by using f-strings.
23 | P a g e
Using in for String Membership Testing
The in keyword checks if a particular substring is present in a string
24 | P a g e
Python String Methods
Python string methods is a collection of in-built Python functions that operates on lists.
Note: Every string method in Python does not change the original string instead returns a
new string with the changed attributes.
Python provides a rich set of “built-in string functions” that allow you to manipulate,
search, modify, and perform various operations on strings. These functions make it easy to
handle and work with string data in Python.
Method Description
Converts all characters in the string to
lower()
lowercase.
Converts all characters in the string to
upper()
uppercase.
Converts the first letter of each word in the string to
title()
uppercase.
Swaps the case of all characters in the
swapcase()
string.
Converts the first character of the string to uppercase and the rest to
capitalize()
lowercase.
EXAMPLE:
25 | P a g e
Function Name Description
Captalize() Converts the first character of the string to a capital (uppercase) letter
Expandtabs() Specifies the amount of space to be substituted with the “\t” symbol in the string
Isalnum() Checks whether all the characters in a given string is alphanumeric or not
26 | P a g e
Function Name Description
Isnumeric() Returns “True” if all characters in the string are numeric characters
Isprintable() Returns “True” if all characters in the string are printable or the string is empty
Isspace() Returns “True” if all characters in the string are whitespace characters
27 | P a g e
Function Name Description
Rindex() Returns the highest index of the substring inside the string
Rsplit() Split the string from the right by the specified separator
Strip() Returns the string with both leading and trailing characters
Zfill() Returns a copy of the string with ‘0’ characters padded to the left side of the string
28 | P a g e
Syntax
“string.capitalize()”
Parameters
The capitalize() method does not take any parameters.
Return Value
It returns a new string where the first character is uppercase and the rest are lowercase. If the
string is empty, it returns an empty string.
In this example, capitalize() method converts the first character “h” to uppercase
and change the rest of characters to lowercase.
2. List (list)
Definition: A list is an ordered, mutable collection of elements. Lists can store
elements of different data types, such as integers, strings, or other lists.
Representation: Lists are enclosed in square brackets ([]), and elements are separated
by commas.
Mutable: Lists are mutable, meaning you can change, add, or remove elements after
the list has been created.
In Python, lists are ordered collections of items, and you can access the elements of a list
using indexing. Similar to strings, lists in Python also support both positive and negative
indexing.
Negative Indexing:
Negative indexing starts from the end of the list.
o -1 refers to the last item.
30 | P a g e
o -2 refers to the second last item.
List Slicing:
You can also extract a range of elements from a list using slicing, similar to how it's done
with strings. The syntax for slicing is:
Key Points:
1. Positive Indexing: Starts from 0 and increases as you move rightward through the
list.
o Example: my_list[0] refers to the first element.
2. Negative Indexing: Starts from -1 for the last element and moves leftward through
the list.
o Example: my_list[-1] refers to the last element, and my_list[-2] refers to the
second last element.
3. Slicing: You can extract a portion of the list using slicing with the syntax
my_list[start:end:step].
31 | P a g e
General example:
32 | P a g e
Python lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks) that is
used to store an ordered collection of items. We can store all types of items (including
another list) in a list. A list may contain mixed type of items, this is possible because a list
mainly stores references at contiguous locations and actual items maybe stored at different
locations.
Table of Content
Creating a List
Creating a List with Repeated Elements
Accessing List Elements
Adding Elements into List
Updating Elements into List
Removing Elements from List
Iterating Over Lists
Nested Lists and Multidimensional Lists
1. Creating a List
Here are some common methods to create a list:
Using Square Brackets
Using the list() Constructor
We can also create a list by passing an iterable (like a string, tuple, or another list) to
the list() function.
2. Creating a List with Repeated Elements
We can create a list with repeated elements using the multiplication operator.
3. Accessing List Elements
Elements in a list can be accessed using indexing. Python indexes start at 0,
so a[0] will access the first element, while negative indexing allows us to access
elements from the end of the list. Like index -1 represents the last elements of list.
4. Adding Elements into List
We can add elements to a list using the following methods:
append(): Adds an element at the end of the list.
extend(): Adds multiple elements to the end of the list.
insert(): Adds an element at a specific position.
5. Updating Elements into List
We can change the value of an element by accessing it using its index.
6. Removing Elements from List
We can remove elements from a list using:
remove(): Removes the first occurrence of an element.
pop(): Removes the element at a specific index or the last element if no index is
specified.
del statement: Deletes an element at a specified index.
7. Iterating Over Lists
33 | P a g e
We can iterate the Lists easily by using a for loop or other iteration methods. Iterating
over lists is useful when we want to do some operation on each item or access specific
items based on certain conditions. Let’s take an example to iterate over the list
using for loop.
8. Nested Lists and Multidimensional Lists
A nested list is a list within another list, which is useful for representing matrices or
tables. We can access nested elements by chaining indexes.
34 | P a g e
3. Tuple (tuple)
Definition: A tuple is an ordered, immutable collection of elements. Like lists, tuples
can store elements of different data types, but unlike lists, they cannot be changed
once created.
Representation: Tuples are enclosed in parentheses (()), and elements are separated
by commas.
Immutable: Once a tuple is created, its contents cannot be altered. This makes tuples
faster and more memory-efficient than lists when you don't need to modify the
sequence.
Characteristics:
Ordered.
Immutable.
Can contain elements of mixed data types.
Common operations:
35 | P a g e
Key Differences:
Faster due to Slower than tuple (due to Faster than list (due to
Performance
immutability mutability) immutability)
These sequence types form the basis for storing and manipulating collections of data in
Python. Lists and strings are the most commonly used, while tuples are used when
immutability is required for performance or safety reasons.
These are the fundamental data types in Python, and you can perform various operations on
each of them (e.g., arithmetic operations, indexing, slicing, etc.).
36 | P a g e
37 | P a g e