Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

introduction to python

The document provides an introduction to Python, highlighting its ease of use, readability, and versatility as a programming language. It covers essential concepts such as the Python interpreter, data types, variables, expressions, conditions, functions, and string manipulation. Additionally, it discusses the advantages of Python, including extensive libraries, open-source nature, and user-friendly syntax.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

introduction to python

The document provides an introduction to Python, highlighting its ease of use, readability, and versatility as a programming language. It covers essential concepts such as the Python interpreter, data types, variables, expressions, conditions, functions, and string manipulation. Additionally, it discusses the advantages of Python, including extensive libraries, open-source nature, and user-friendly syntax.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

INTRODUCTION

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.

we need to have an interpreter to interpret and run our programs.

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/.

 Program: codes and following code after starting the interpreter

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.

 “Parentheses” are the round brackets () used in programming to group things


together. For example, in Python, when you use the print function, you put the
message inside parentheses, like this: print("Hello, world!") In this case, "Hello,
world!" is inside the parentheses.

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”

 name = "sweety" # name is a “string”

4|Page
Python variables are case-sensitive, meaning that “myVariable” and “myvariable” are
considered different variables.

Expressions: An expression in Python is a combination of values, variables, operators, and


function calls that can be evaluated to produce a result. For example:
1. Simple Expressions:
o 5 + 3 (This adds 5 and 3 and gives the result 8)

o x * 2 (This multiplies the value of x by 2)

2. More Complex Expressions:


o a * b + c (This multiplies a and b, then adds c to the result)

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:

if, elif (else if), and else statements together-

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

#Driver program to test the above function

Here's an overview of functions in Python:


1. Defining a Function
To define a function, use the def keyword followed by the function name and parentheses
containing any parameters. A colon (:) marks the start of the function body.
2. Calling a Function
Once a function is defined, you can call it by using the function name and passing the
appropriate arguments.

7|Page
1. Def

2. calling

 def: The keyword used to define a function.


 greet: The name of the function.
 name: The parameter, which acts as a placeholder for the value passed into the
function when it is called.
 print(f"Hello, {name}!"): This is the body of the function. It prints a greeting
message using the name parameter.
 greet("sweety") = sweety is the argument passed to the function when calling it.
The function then prints a greeting message using the provided name.
3. Function Parameters
Functions can take parameters (also called arguments), which are values passed to the
function when it is called.

 def add(a, b):


"""
This function takes two numbers, adds them, and returns the result.
"""
 return a + b
# Calling the function and storing the result
 result = add(24, 7)
 print(result)
# Output: 31
4. Returning Values
A function can return a value using the return statement. This allows the function to output a
result that can be stored or used elsewhere.

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"):

"""

Greets the person by name, defaulting to 'Guest' if no name is provided.

"""

 print(f"Hello, {name}!")

# Calling the function

 greet()

# Output: Hello, sony!

 greet("sweety")

# Output: Hello, 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

7. Lambda Functions (Anonymous Functions)


Lambda functions are small, anonymous functions defined using the lambda keyword. They
can be used for simple operations in a concise way.

8. Function Scope and Local vs Global Variables


 Local variables are defined within a function and can only be accessed inside that
function.
 Global variables are defined outside any function and can be accessed throughout the
program.

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):

"""

This function computes the factorial of a number using recursion.

"""

 if n == 0:
 return 24
 else:
 return n * factorial(n - 1)

# Calling the function

 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.

Recap of Numeric Data Types in Python:


 int (Integer): Whole numbers, both positive and negative (e.g., 10, -200, 0).
 float (Floating-point number): Real numbers, including decimals and scientific
notation (e.g., 3.14, -2.5, 1.23e4).
 complex (Complex number): Numbers with both real and imaginary parts,
represented as a + bj (e.g., 2 + 3j, -1 + 5j).

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.

In Python, the escape sequence “\n” represents a newline character, which is


used to insert a line break in text:
Python provides several built-in sequence types:
1. String
2. List
3. Tuple
Let's explore each of these sequence types in detail:

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).

So here num’s starts from 0,1,2,3 = h,e,l,l….etc and words 0:5 =


hello;
 Characteristics:
 Ordered.
 Immutable.
 Can contain letters, digits, symbols.
 Common operations:
 Indexing (my_string[0] returns 's')

15 | P a g e
 Slicing (my_string[0:5] returns 'sweety')
 Concatenation ("Hello" + " World!" results in "sweety sweet!")
Best examples:

Accessing elements of String


In Python, indexing allows you to access individual characters in a string. Strings are ordered
sequences of characters, so each character has an index that represents its position. Python
uses zero-based indexing, which means the first character in a string is accessed with index 0,
the second character with index 1, and so on.
e.g. -1 refers to the last character, -2 refers to the second last character and so on.
You can access characters in a string by specifying the index in square brackets [].
 Positive Indexing: Starts from the left, where 0 is the index of the first character.
 Negative Indexing: Starts from the right, where -1 is the index of the last character, -2
for the second last character, and so on.

Example of Negative Indexing:

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.

Example of both Indexing and 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.

In this example, s holds the value “sweety” and is defined as a string.


Table of Content
Creating string
Accessing characters in python string
String immutability
Deleting a string
Updating a string
Common string methods
Concatenating and repeating strings
Formatting strings
1. Creating a String
Strings can be created using either single (‘) or double (“) quotes.

a. Multi-line Strings
If we need a string to span multiple lines then we can use triple quotes (”’ or “””).
Python

2. Accessing characters in Python String


19 | P a g e
Strings in Python are sequences of characters, so we can access individual characters
using indexing. Strings are indexed starting from 0 and -1 from end. This allows us to
retrieve specific characters from the string.

Python String syntax indexing

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:

Time complexity: O(n) where n is the length of the string ‘text’


Auxiliary space: O(1)

25 | P a g e
Function Name Description

Captalize() Converts the first character of the string to a capital (uppercase) letter

Casefold() Implements caseless string matching

Center() Pad the string with the specified character.

Count() Returns the number of occurrences of a substring in the string.

Encode() Encodes strings with the specified encoded scheme

 Endswitch()  Returns “True” if a string ends with the given suffix

Expandtabs() Specifies the amount of space to be substituted with the “\t” symbol in the string

 Find()  Returns the lowest index of the substring if it is found

Format() Formats the string for printing it to console

Format_map() Formats specified values in a string using a dictionary

Index() Returns the position of the first occurrence of a substring in a string

Isalnum() Checks whether all the characters in a given string is alphanumeric or not

Isalpha() Returns “True” if all characters in the string are alphabets

Isdecimal() Returns true if all characters in a string are decimal

Isdigit() Returns “True” if all characters in the string are digits

26 | P a g e
Function Name Description

Isidemtifier() Check whether a string is a valid identifier or not

Islower(0 Checks if all characters in the string are lowercase

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

Istitle() Returns “True” if the string is a title cased string

Issupper() Checks if all characters in the string are uppercase

 Join()  Returns a concatenated String

Ljust() Left aligns the string according to the width specified

 Lower()  Converts all uppercase characters in a string into lowercase

Lstrip() Returns the string with leading characters removed

Marketrans() Returns a translation table

Partition() Splits the string at the first occurrence of the separator

 Replace()  Replaces all occurrences of a substring with another substring

Rfind() Returns the highest index of the substring

27 | P a g e
Function Name Description

Rindex() Returns the highest index of the substring inside the string

Rjust() Right aligns the string according to the width specified

Rpartition() Split the given string into three parts

Rsplit() Split the string from the right by the specified separator

Rstrip() Removes trailing characters

 Splitlines()  Split the lines at line boundaries

 Startsswith()  Returns “True” if a string starts with the given prefix

 Strip()  Returns the string with both leading and trailing characters

Swapcase() Converts all uppercase characters to lowercase and vice versa

Title() Convert string to title case

Translate() Modify string according to given translation mappings

 Upper()  Converts all lowercase characters in a string into uppercase

Zfill() Returns a copy of the string with ‘0’ characters padded to the left side of the string

 String capitalize() Method in Python:


The capitalize() method in Python is a string method used to convert the first character of a
string to uppercase and the rest of the string to lowercase. It is particularly useful for
normalizing text data, such as ensuring consistent capitalization for names or titles.

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.

 Python String casefold() Method

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.

So here numbers starts from 0,1,2,3 = 24,7,5, sweety….etc


29 | P a g e
 Characteristics:
 Ordered.
 Mutable.
 Can contain elements of mixed data types.
 Common operations:
 Indexing (my_list[2] returns 5)
 Slicing (my_list[1:4] returns [7, 5, 'sweety'])
 Appending (my_list.append(6))
Lists in Python can be created by just placing the sequence inside the square brackets[].

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.

Accessing Elements of a List Using Indexing


Positive Indexing:
 Lists in Python are zero-indexed, meaning the first element is at index 0, the second
at index 1, and so on.

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.

o -3 refers to the third last item, and so on.

Using Indexing to Access Specific Elements:


You can access any element in the list by specifying its index in square brackets [].

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:

 start: The starting index (inclusive).


 end: The ending index (exclusive).
 step: The step to skip items (optional).

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:

 Indexing (my_tuple[3] returns 'hello')


 Slicing (my_tuple[1:4] returns (2, 3, 'hello'))
 Concatenation ((1, 2) + (3, 4) results in (1, 2, 3, 4))

35 | P a g e
Key Differences:

Feature String List Tuple

Mutability Immutable Mutable Immutable

Syntax 'Hello' or "Hello" [1, 2, 3] (1, 2, 3)

Faster due to Slower than tuple (due to Faster than list (due to
Performance
immutability mutability) immutability)

Collection of items that may


Use case Text data Collection of constant items
change

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.

Summary of Python's Built-in Data Types:

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

You might also like