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

Python Notes

Uploaded by

Navnath
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Python Notes

Uploaded by

Navnath
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Python Notes

 Variables in python:
1. Tupel:
In Python, a tuple is an ordered collection of elements, enclosed in parentheses and separated by
commas. Tuples are similar to lists, but the main difference is that tuples are immutable,
meaning their elements cannot be modified once they are assigned.
Here's an example of a tuple in Python:
my_tuple = (1, 2, 3, "four", 5.6)
In this example, my_tuple is a tuple that contains five elements: the integers 1, 2, and 3, the
string "four," and the float 5.6.

You can access individual elements in a tuple using indexing, similar to lists:
print(my_tuple[0]) # Output: 1
print(my_tuple[3]) # Output: four

Tuples can also be sliced to retrieve a subset of elements:


print(my_tuple[1:4]) # Output: (2, 3, 'four')

Since tuples are immutable, you cannot modify their elements or assign new values to them
directly. However, you can concatenate or combine tuples to create new tuples:
new_tuple = my_tuple + (6, 7)
print(new_tuple) # Output: (1, 2, 3, 'four', 5.6, 6, 7)
Tuples are commonly used when you have a collection of related values that should not be
modified, such as coordinates, database records, or multiple return values from a function.

It's worth noting that when creating a tuple with only one element, you need to include a trailing
comma to differentiate it from an expression enclosed in parentheses. For example:
single_element_tuple = (1,)
Without the trailing comma, (1) would be interpreted as an arithmetic expression.

2. List-
In Python, a list is an ordered collection of elements enclosed in square brackets and separated
by commas. Lists are versatile and mutable, meaning you can modify their elements after they
are created. Here's an example of a list in Python:
my_list = [1, 2, 3, "four", 5.6]

In this example, my_list is a list that contains five elements: the integers 1, 2, and 3, the string
"four," and the float 5.6.

You can access individual elements in a list using indexing, starting from 0:
print(my_list[0]) # Output: 1
print(my_list[3]) # Output: four

You can also use negative indexing to access elements from the end of the list:
print(my_list[-1]) # Output: 5.6
print(my_list[-2]) # Output: four

Lists support slicing, which allows you to retrieve a subset of elements:


print(my_list[1:4]) # Output: [2, 3, 'four']

Lists are mutable, so you can modify individual elements or assign new values to them:
my_list[0] = 10
print(my_list) # Output: [10, 2, 3, 'four', 5.6]

my_list.append("six")
print(my_list) # Output: [10, 2, 3, 'four', 5.6, 'six']

In the example above, we changed the value of the first element to 10 and added a new element,
"six," to the end of the list using the append() method.
Lists can contain elements of different types, such as integers, strings, floats, or even other lists.
They are commonly used to store collections of related data or when you need a dynamic
collection that can be modified.
It's important to note that lists are mutable, meaning they can be changed in place. This is
different from tuples, which are immutable
 Built in Function
In Python, built-in functions are pre-defined functions that are available for immediate use without the need
for additional import statements. These functions are part of the Python programming language itself and
provide a wide range of functionalities. Here are some examples of commonly used built-in functions in
Python:
1. print() : Used to display output on the console or terminal. It takes one or more arguments and prints
them to the standard output.
2. len() : Returns the number of items in an object. It can be used with strings, lists, tuples, dictionaries,
and other iterable objects.
3. input() : Allows the user to input data from the keyboard. It reads a line of text as a string and can be
used to prompt the user for information.
4. type() : Returns the type of an object. It is often used for type checking and to determine the class of an
object.
5. range() : Generates a sequence of numbers within a specified range. It is commonly used in loops to
iterate a specific number of times.
6. int() , float() , str() , bool() : These functions convert values to different data types. int() converts
a value to an integer, float() converts it to a floating-point number, str() converts it to a string, and
bool() converts it to a boolean value.
7. sum() : Returns the sum of all elements in an iterable, such as a list or tuple.

8. max() , min() : Return the maximum and minimum values, respectively, from a sequence or a set of
arguments.
9. abs() : Returns the absolute value of a number. It can be used with integers or floating-point numbers.

10. round() : Rounds a number to a specified precision or the nearest whole number.
These are just a few examples of the many built-in functions available in Python. They provide essential
functionality that can be used to perform various operations, manipulate data, interact with the user, and
more. Python's built-in functions are part of its standard library and are readily accessible for use in your
programs.

11. enumerate():
The enumerate() function in Python is a built-in function that allows you to iterate over a sequence (such
as a list, tuple, or string) while keeping track of the index position and the corresponding value of each
element. It returns an iterator that generates pairs of index-value tuples. Here's the general syntax of
enumerate():
enumerate(sequence, start=0)

The sequence parameter represents the iterable object you want to iterate over, while the optional start
parameter specifies the starting index (by default, it is set to 0).
Here's an example that demonstrates the usage of enumerate():

fruits = ['apple', 'banana', 'orange']

for index, fruit in enumerate(fruits):


print(index, fruit)

Output:
0 apple
1 banana
2 orange

In this example, the enumerate() function is used within a for loop to iterate over the fruits list. In
each iteration, it generates a tuple containing the index and the corresponding value of the current
element. The variables index and fruit are used to unpack the tuple, allowing us to access both the
index and value within the loop body.
By default, enumerate() starts the index from 0, but you can specify a different starting value using the
start parameter. For instance:

fruits = ['apple', 'banana', 'orange']

for index, fruit in enumerate(fruits, start=1):


print(index, fruit)

Output:
1 apple
2 banana
3 orange

In this modified example, the start parameter is set to 1, so the index starts from 1 instead of 0.
The enumerate() function is useful when you need to keep track of both the index and value while
iterating over a sequence. It eliminates the need for maintaining a separate counter variable and
provides a concise way to iterate and access elements in a loop.
Loops

1. For loop
Example-
game=[[0, 0, 0],
[0, 0, 0],
[0, 0, 0],] --------variable declaration

print (type(game)) -------- syntax to check data variable type

for row in game:


print(row) -------------syntax of for loop

# output:
<class 'list'>
[0, 0, 0]
[0, 0, 0]
[0, 0, 0]

Function

In Python, a function is a block of reusable code that performs a specific task. It allows you to organize and
modularize your code by encapsulating a set of instructions. Functions accept input values, called arguments or
parameters, perform a series of operations, and may return a value as an output. Here's the general syntax of a
function in Python:

def function_name(parameter1, parameter2, ...):

# Function body - code to be executed

# Operations and statements

return value # Optional return statement

Let's break down the components of a function:


def: The def keyword is used to define a function in Python.

function_name: This is the name given to the function. It should be descriptive and follow Python's naming
conventions.

(parameter1, parameter2, ...): These are optional parameters or arguments that the function can accept. They
act as placeholders for the values that will be passed into the function when it is called. Parameters are separated by
commas.

:: A colon is used to indicate the start of the function's body.

Function body: This is where you write the code that defines the behavior of the function. It consists of one or more
statements and operations to be executed.

return: This keyword is used to specify the value that the function will return as its output. It is optional, and a
function may or may not have a return statement. If no return statement is present, the function will return None by
default.

Here's an example of a simple function that calculates the square of a number:

def square(num):

result = num ** 2

return result

In this example, the square() function takes a single parameter num and calculates the square of the number by
raising it to the power of 2. The result is then returned using the return statement.

To use a function, you need to call it by its name and provide any required arguments. Here's an example of calling
the square() function:

result = square(5)

print(result) # Output: 25

In this case, the square() function is called with the argument 5. The returned value, 25, is assigned to the variable
result and then printed.

Functions can have multiple parameters, default values for parameters, and perform complex operations. They are an
essential part of writing clean, organized, and reusable code in Python.

You might also like