Python by Jas
Python by Jas
Introduction:
History:
Python was developed in the late 1980s by Guido van Rossum at the
National Research Institute for Mathematics and Computer Science in the
Netherlands. Its design philosophy emphasizes code readability, and its
syntax allows programmers to express concepts in fewer lines of code than
would be possible in languages such as C++ or Java.
Debugging:
Statements:
Expressions:
Order of operations:
Modulus operator:
String operations:
The input function is used to read data from the user. It prompts the user
for input and returns the entered value as a string.
Comments:
Comments are lines of code that are ignored by the interpreter. In Python,
comments are indicated using the pound symbol (#).
Conditional execution:
if x > 0:
print("x is positive")
In this example, the code block that contains the print statement will only
be executed if the value of x is greater than 0.
Alternative execution:
Copy code
if x > 0:
print("x is positive")
else:
Chained conditionals:
Copy code
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
In this example, the first code block will be executed if x is greater than 0,
the second code block will be executed if x is less than 0, and the third code
block will be executed if x is equal to 0.
Nested conditionals:
if x > 0:
if y > 0:
else:
In this example, the code block that contains the first print statement will
be executed if x is greater than 0 and y is also greater than 0. The code
block that contains the second print statement will be executed if x is
greater than 0 but y is not, and the code block that contains the third print
statement will be executed if x is not greater than 0.
Catching exceptions:
Copy code
try:
x=1/0
except ZeroDivisionError:
In this example, the code block that contains the division operation will be
executed, and if a ZeroDivision
Unit 3-function and iteration
A function call is an expression that executes a function. In Python, you can call a
function by writing the name of the function followed by parentheses containing any
required arguments. For example:
In this example, the greet function is defined to take one argument, name. When we
call the function with the argument "Alice", the function prints out "Hello, Alice".
Next, let's talk about built-in functions. Python comes with a number of functions
built into the interpreter, which are always available for you to use. Some examples
of built-in functions include len for getting the length of a list, print for printing to
the console, and abs for taking the absolute value of a number.
Type conversion functions allow you to convert values from one type to another. For
example, you can use the int function to convert a string or a floating-point number
to an integer. You can also use the str function to convert a value to a string, or the
float function to convert a value to a floating-point number.
Math functions allow you to perform mathematical operations in your code. Python's
math module includes functions for performing operations such as calculating
trigonometric values, taking the square root of a number, and rounding numbers to
the nearest integer.
Random numbers can be generated using the random module. The random module
includes functions for generating random values, such as random integers, floating-
point numbers, and values from a specified range.
You can add new functions to your code by using the def keyword, followed by the
name of the function and any required arguments. For example:
def greet(name):
To use a function, you first need to define it. This is done using the def keyword,
followed by the name of the function and any required arguments. For example:
def greet(name):
Once a function is defined, you can call it by writing the name of the function
followed by parentheses containing any required arguments. For example:
greet("Alice")
The flow of execution in a Python program refers to the order in which the
interpreter executes the instructions in your code. When a function is called, the flow
of execution jumps to the function definition and starts executing the instructions in
the function, one by one. When the function is finished, the flow of execution returns
to the point where the function was called.
Parameters are values that are passed to a function when it is called, while arguments
are the actual values that are passed to the function. For example, in the function
definition def greet(name), name is a parameter. When the function is called with
greet("Alice"), "Alice" is the argument being passed to the function.
A fruitful function is a function that returns a value when it is called. For example:
result = add(3, 4)
print(result) # prints 7
A void function is a function that does not return a value when it is called. For
example:
def greet(name):
x=5
print(x) # Output: 5
x = 10
print(x) # Output: 10
The while statement: The while statement is used to repeatedly execute a block of
code as long as a certain condition is true. The syntax for a while loop is as follows:
while condition:
# code to be executed
Copy code
x=1
print(x)
x += 1
Infinite loops: An infinite loop is a loop that runs indefinitely because the loop
condition is always true. Here is an example of an infinite loop:
while True:
print("Hello, world!")
To prevent an infinite loop, you must include some code within the loop that will
eventually cause the loop condition to become false.
Finishing iterations with continue: The continue statement is used to skip the rest of
the current iteration and move on to the next iteration of the loop. For example:
for x in range(1, 11):
if x % 2 == 0:
continue
print(x)
This for loop will print only the odd numbers between 1 and 10.
Definite loops using for : A definite loop is a loop that iterates over a specific
sequence or range of values. In Python, the for loop is used to perform definite
loops. The syntax for a for loop is as follows:
# code to be executed
print(x)
Loop patterns: There are many different patterns that you can use with loops in
Python. Some common patterns include:
• Counting loops: Loops that are used to count the number of iterations that
have occurred.
• Summing loops: Loops that are used to sum the values of a sequence or range
of numbers.
• Maximum and minimum loops: Loops that are used to find the maximum or
minimum value in a sequence or range of numbers.
Counting and summing loops: To count the number of iterations in a loop, you can
use a counter variable that is incremented each time the loop iterates. To sum the
values of a sequence or range of numbers, you can use a variable to store the sum
and add each value to the sum as the loop iterates. Here is an example of a loop that
counts the number of iterations and sums the values of a range of numbers:
count = 0
sum = 0
sum += x
print("Count:", count)
print("Sum:", sum)
To find the maximum value in a sequence or range of numbers in Python, you can
use a loop to compare each value to the current maximum value. Here is an example
of a loop that finds the maximum value in a range of numbers:
if x > max_value:
max_value = x
to find the minimum value in a sequence or range of numbers, you can use a similar
loop, but replace the > operator with the < operator and initialize the min_value
variable to the highest possible float value. Here is an example of a loop that finds
the minimum value in a range of numbers:
if x < min_value:
min_value = x
s = "Hello, world!"
print(len(s)) # Output: 13
You can traverse through a string using a loop. Here is an example of a for loop that
iterates through a string and prints each character:
s = "Hello, world!"
for c in s:
print(c)
You can also use string slices to access a substring of a string. The syntax for a string
slice is s[start:end], where start is the index of the first character in the slice and end
is the index of the character after the last character in the slice. For example:
s = "Hello, world!"
Strings are immutable, which means that you cannot modify a string in place. If you
want to modify a string, you must create a new string.
Looping and counting: You can use a loop to count the number of occurrences of a
specific character in a string. Here is an example of a loop that counts the number of
vowels in a string:
s = "Hello, world!"
vowel_count = 0
for c in s:
if c in 'aeiouAEIOU':
vowel_count += 1
s = "Hello, world!"
String comparison: You can use the == operator to test if two strings are equal. For
example:
s1 = "Hello, world!"
s2 = "Hello, world!"
s3 = "Goodbye, world!"
print(s1 == s2) # Output: True
print(s1 == s3) # Output: False
String methods: Python provides a number of built-in methods for working with
strings. Some common string methods include:
• s.lower(): Returns a copy of the string with all uppercase characters converted
to lowercase.
• s.upper(): Returns a copy of the string with all lowercase characters converted
to uppercase.
• s.strip(): Returns a copy of the string with leading and trailing whitespace
removed.
• s.isalpha(): Returns True if the string consists only of alphabetic characters
and False otherwise.
• s.isdigit(): Returns True if the string consists only of digits and False
otherwise.
• Parsing strings: You can use string methods and slicing to parse a string and
extract specific information from it. For example, you can use the split()
method to split a string into a list of substrings based on a delimiter:
• s = "Hello, world!"
• words = s.split()
• print(words) # Output: ['Hello,', 'world!']
• The format() operator: The format() operator is a powerful tool for formatting
strings in Python. It allows you to embed placeholders in a string and then
replace them with values. The syntax for the format() operator is
"{}".format(value). For example:
• name = "John"
• age = 30
• s = "My name is {} and I am {} years old.".format(name, age)
• Opening files: To open a file in Python, you can use the open() function. The
open() function takes two arguments: the file name and the mode. The mode
specifies how the file should be opened (e.g. for reading, writing, etc.). Here is
an example of how to open a file for reading:
• f = open('myfile.txt', 'r')
• Text files and lines: A text file is a file that contains plain text (i.e. no
formatting). In Python, you can read a text file line by line using a for loop.
Here is an example of how to read a text file line by line:
• f = open('myfile.txt', 'r')
• for line in f:
• print(line)
• f.close()
• Reading files: To read the entire contents of a file at once, you can use the
read() method. The read() method returns a string containing the entire
contents of the file. Here is an example of how to read the entire contents of a
file:
• f = open('myfile.txt', 'r')
• contents = f.read()
• print(contents)
• f.close()
• Searching through a file: To search for a specific string in a file, you can use
the in operator and a for loop. Here is an example of how to search for a
specific string in a file:
• f = open('myfile.txt', 'r')
• search_string = "Hello, world!"
• for line in f:
• if search_string in line:
• print("Found string:", line)
• f.close()
• Letting the user choose the file name: To let the user choose the file name,
you can use the input() function to prompt the user for a file name. Here is an
example of how to let the user choose the file name:
• f.close()
• Using try, except, and open: It is good practice to use the try and except
statements when working with files in Python, to handle situations where the
file may not exist or may not be accessible. The open() function can throw an
exception if there is an error opening the file. Here is an example of how to
use try , except, and open:
• try:
• f = open('myfile.txt', 'r')
• for line in f:
• print(line)
• f.close()
• except:
• Writing files in Python: To write to a file in Python, you can use the write()
method. The write() method takes a string as an argument and writes it to the
file. Here is an example of how to write to a file:
• f = open('myfile.txt', 'w')
• f.write("Hello, world!\n")
• f.write("This is a test.\n")
• f.close()
• Note: When you open a file in write mode (using the 'w' mode), the contents of the file are overwritten. If you want to append to the
end of a file instead of overwriting it, you can use the 'a' mode.
Unit5-: Collections: Arrrays, Lists, Dictionaries and
Tuples
In Python, an array is a collection of elements that are stored in a contiguous block of
memory. The elements in an array can be of any data type, including numbers,
strings, and objects.
There are several ways to represent an array in Python. The most basic way is to use a
Python list. For example:
my_array = [1, 2, 3, 4, 5]
This creates an array of integers with five elements. To access a specific element in
the array, you can use an index:
print(my_array[0]) # prints 1
print(my_array[1]) # prints 2
You can also modify the elements in the array by assigning new values to them using
an index:
my_array[0] = 10
print(my_array[0]) # prints 10
There are many basic operations you can perform on an array, such as appending an
element to the end of the array, inserting an element at a specific index, and
removing an element from the array. Here are a few examples:
my_array = [1, 2, 3, 4, 5]
my_list = [1, 2, 3, 4, 5]
To access a specific element in a list, you can use an index. Python uses zero-based indexing, so
the first element in the list has an index of 0.
print(my_list[0]) # prints 1
print(my_list[1]) # prints 2
You can also modify elements in a list by assigning new values to them using an index:
my_list[0] = 10
print(my_list[0]) # prints 10
print(element)
There are many operations you can perform on lists, such as concatenating two lists, repeating a
list, and sorting a list. Here are a few examples:
Copy code
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# repeat a list
list4 = list1 * 3
# sort a list
list5 = [3, 2, 1]
list5.sort()
You can also create a new list from a portion of an existing list using list slicing. For example:
my_list = [1, 2, 3, 4, 5]
# create a new list from the second element to the fourth element (indexes 1 to 3)
new_list = my_list[1:4]
There are many methods available for lists, such as append , insert , and remove . Here are a few
examples:
Copy code
my_list = [1, 2, 3, 4, 5]
# append an element to the end of the list
my_list.append(6)
my_list.insert(2, 7)
my_list.remove(4)
To delete an element from a list, you can use the del statement:
my_list = [1, 2, 3, 4, 5]
del my_list[2]
You can pass a list as an argument to a function just like any other object. For example:
def print_list(my_list):
print(element)
my_list = [1, 2, 3, 4, 5]
print_list(my_list) # prints 1, 2, 3, 4, 5
You can also modify a list within a function by using an index or one of the list methods. For
example:
def modify_list(my_list):
my_list[0] = 10
my_list.append(6)
my_list = [1, 2, 3, 4, 5]
modify_list(my_list)
You can convert a list to a string by using the join method of the string class. For example:
string = ''.join(my_list)
You can also split a string into a list of substrings using the split method of the string class. For
example:
You can use the split method to parse lines of text in a file. For example:
In Python, objects are values that can be assigned to variables or elements in a data structure.
When you assign an object to a variable, the variable refers to the object. For example:
x = [1, 2, 3]
y=x
y[0] = 10
print(x[0]) # prints 10
In this example, y is an alias for the object referred to by x, so when we modify the object using y,
the changes are also visible when we access the object through x .
When you pass a list to a function as an argument, the function can modify the elements of the
list. For example:
def modify_list(my_list):
my_list[0] = 10
my_list.append(6)
my_list = [1, 2, 3, 4, 5]
modify_list(my_list)
This is because lists are mutable objects and are passed by reference in Python, so the function is
able to modify the original list.
Dictionary
A dictionary is a collection of key-value pairs. It is an unordered data structure that
stores data in a key-value format, with the keys being used to access the associated
values. Dictionaries are often used to store data that needs to be quickly retrieved by
a unique identifier.
my_dict = {}
my_dict['name'] = 'John'
my_dict['age'] = 30
my_dict['age'] = 31
print(my_dict['age']) # Output: 31
if 'name' in my_dict:
You can also loop over the key-value pairs in a dictionary using a for loop. Here is an
example:
print(key, value)
Output:
name John
age 31
To save a dictionary to a file, you can use the json module to convert the dictionary
to a JSON string, and then write the string to a file. Here is an example:
import json
f.write(json_str)
To read a dictionary from a file, you can use the json module to read the JSON string
from the file and then convert it back to a dictionary. Here is an example:
json_str = f.read()
my_dict = json.loads(json_str)
For advanced text parsing in Python, you can use regular expressions to search for
patterns in strings. The re module provides a variety of functions for working with
regular expressions in Python. Here is an example of how to use regular expressions
to search for a pattern in a string:
import re
if result:
print(result.group())
In Python, tuples are immutable sequences, typically used to store collections of
items that are not going to be modified. Because they are immutable, you can't add,
remove, or change the values of any element in a tuple once it is created.
You can compare tuples using the standard comparison operators <, > , == , !=, <=, and
>=. Tuples are compared element-wise, so the first elements of the tuples are
compared first, then the second elements, and so on. If all the elements are equal,
the tuples are considered equal. If any element is different, the tuples are considered
different.
You can also use tuple assignment to assign multiple variables at the same time. For
example:
(x, y) = (1, 2)
print(x) # prints 1
print(y) # prints 2
You can use tuples as keys in dictionaries, because they are immutable. For example:
You can also use multiple assignment with dictionaries to assign multiple variables at
the same time. For example:
d = {'a': 1, 'b': 2}
a, b = d['a'], d['b']
print(a) # prints 1
print(b) # prints 2
In Python, strings, lists, and tuples are all examples of sequences. A sequence is an
ordered collection of items, where each item has a specific position (also known as
an index) within the sequence. You can access the items of a sequence by their index,
and you can iterate over the items of a sequence using a for loop.
For example:
for item in l:
print(item)
# Output:
#1
#2
#3
#4
Unit 6-regular expressions and object oriented
programming
Character matching in regular expressions refers to the use of special characters to
match specific types of characters in a string. For example, the "." character is a
wildcard that matches any character, while the "\d" character class matches any digit.
Extracting data using regular expressions involves using special characters and
patterns to search for and extract specific pieces of data from a larger string.
For example, if you want to match a literal "." character in a regular expression, you
would use the escape character to escape it, like this: ".". This tells the regular
expression engine to treat the "." character as a literal character rather than a special
wildcard character.
Starting with programs: A good way to start learning programming is to write simple
programs that perform a specific task. As you gain more experience, you can build
on your knowledge and tackle more complex projects.
Classes as types: In Python, a class is a template for creating objects. When you
create an object from a class, the object is said to be an instance of the class. Classes
are also used to define the data type of an object, just like built-in types like int and
str.
Object lifecycle: An object goes through a series of stages during its lifetime. These
stages include creation, manipulation, and destruction.
Tkinter is a Python library for creating graphical user interfaces (GUIs). It provides a
number of different widgets, such as buttons, labels, and text boxes, that you can use
to build your GUI. Some common Tkinter widgets include:
• Button: A button widget that the user can click to perform an action.
• Canvas: A widget for drawing graphics.
• Checkbutton: A button that can be selected or deselected.
• Entry: A widget for entering text.
• Frame: A container for other widgets.
• Label: A widget for displaying text or an image.
• Listbox: A widget for displaying a list of items.
• Menubutton: A button that displays a menu when clicked.
• Menu: A menu widget that can be added to a menubutton or other widget.
• Message: A widget for displaying text with word wrapping.
• Radiobutton: A button that can be selected or deselected, and is part of a
group of mutually exclusive buttons.
• Scale: A widget for selecting a value from a range of values.
• Scrollbar: A widget for scrolling through a list or other widget.
• Text: A widget for displaying and editing multiple lines of text.
• Toplevel: A widget for creating a new window.
• Spinbox: A widget for selecting a value from a fixed set of values.
• PanedWindow: A widget for dividing the window into panes, each containing
a separate widget.
• LabelFrame: A widget that acts as a container for other widgets, with a label
displayed above or to the left of the widgets.
Standard attributes:
Most Tkinter widgets have a number of standard attributes that you can use to
customize their appearance and behavior. These attributes include things like the
widget's size, font, and color.
Geometry Management:
Geometry management is the process of determining the size and position of
widgets within a GUI. Tkinter provides three different geometry managers: pack, grid,
and place.
What is a database?:
Database concepts:
There are several key concepts that are important to understand when working with
databases. These include:
SQLite is a popular database system that is lightweight and easy to use. The
Database Browser for SQLite is a tool that allows you to create and manage SQLite
databases.
Structured Query Language (SQL) is a programming language used to manage data stored in
relational database management systems (RDBMS). Some common SQL commands include:
Data modeling is the process of designing a database to store and organize data in a way that is
efficient and easy to use. When creating a data model, you need to consider the types of data
you need to store, the relationships between different pieces of data, and the ways in which the
data will be accessed and queried.
In a database with multiple tables, you can use SQL commands to query the data in different
tables and combine the results. This is known as a join. There are several types of joins, including
inner joins, outer joins, and cross joins.
Constraints are rules that define the allowed values for fields in a database table. Some common
types of constraints include:
To retrieve a record from a database table, you can use the SELECT statement. To insert a new
record into a table, you can use the INSERT statement.
To store a friend relationship in a database, you can create a table that contains two fields: one
for the person's ID and one for their friend's ID. You can then use these fields to store the
relationship between the two people.
• Primary keys: a primary key is a field or set of fields that uniquely identifies each record in
a table
• Foreign keys: a foreign key is a field in one table that refers to the primary key of another
table
• Candidate keys: a candidate key is a field or set of fields that could be used as a primary
key, but is not used because a different field or set of fields is chosen as the primary key
To retrieve data from multiple tables in a database using Python, you can use the JOIN clause in a
SELECT statement. The JOIN clause allows you to specify how the tables should be related, and
how the data from the tables should be combined.
There are several different types of JOINs that you can use, including INNER JOIN, OUTER
JOIN, and CROSS JOIN. You can also specify additional conditions in the ON clause to further
refine the results of the join.
Inner Join:
An inner join returns only the rows that satisfy the join condition. It combines rows
from two or more tables based on a related column between them.
Outer Join:
An outer join returns all rows from both tables, whether they satisfy the join
condition or not. There are three types of outer joins:
• Left outer join: returns all rows from the left table, and any matching rows
from the right table. If there is no match, NULL values are returned for the
right table.
• Right outer join: returns all rows from the right table, and any matching rows
from the left table. If there is no match, NULL values are returned for the left
table.
• Full outer join: returns all rows from both tables, and NULL values for any rows
that do not have a match in the other table.
• Cross Join:
• A cross join returns the Cartesian product of two tables. This means it returns
every possible combination of rows from the two tables.
Unit 8-visualizing data
Data Visualization:
Data visualization is the process of creating visual representations of data. This can be done using
graphs, charts, plots, and other types of visualizations. Data visualization is a powerful way to
communicate data and insights, and can help to uncover patterns and trends that may not be
immediately apparent in raw data.
Python is a popular language for data analysis and data visualization. There are several libraries
available for creating visualizations in Python, including Matplotlib and Seaborn.
Matplotlib:
Matplotlib is a widely used library for creating static, animated, and interactive visualizations in
Python. It provides a high-level interface for drawing various types of plots, including line plots,
bar plots, scatter plots, and more.
Seaborn:
Seaborn is a library built on top of Matplotlib that provides a higher-level interface for creating
statistical plots. It is particularly useful for visualizing statistical relationships in large datasets.
Line Charts:
A line chart is a graph that displays data as a series of connected points. Line charts are often
used to visualize trends over time, or to compare multiple datasets.
Bar Graphs:
A bar graph is a graph that displays data using horizontal or vertical bars. Bar graphs are often
used to compare multiple datasets or to show changes over time.
Histogram:
A histogram is a graph that displays the distribution of a dataset by dividing the data into bins
and showing the frequency of data points within each bin. Histograms are useful for
understanding the shape of a dataset and identifying patterns and trends.
Scatter Plots:
A scatter plot is a graph that displays data as a series of points, with the position of each point
determined by the values of two variables. Scatter plots are often used to visualize the
relationship between two variables, and can be used to identify patterns and correlations in the
data.