Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

SNAKE GAME 2023-24

About Python
Python is a General Purpose object-oriented programming language, which means that it
can model real-world entities. It is also dynamically-typed because it carries out type-checking at
runtime.
It does so to make sure that the type of construct matches what we expect it to be.
The distinctive feature of Python is that it is an interpreted language.
The Python IDLE (Integrated Development Environment) executes instructions one line
at a time. This also lets us use it as a calculator.
Features
a. Easy- Python is very easy to learn and understand; any beginner can learn Python
easily. When writing code in Python, you need fewer lines of code compared to languages like
Java.
b. Interpreted - It is interpreted(executed) line by line. This makes it easy to test and
debug.
c. Object-Oriented -The Python programming language supports classes and objects and
hence it is object-oriented.
d. Free and Open Source - The language and its source code are available to the public
for free; there is no need to buy a costly license.
e. Portable - Since Python is open-source, you can run it on Windows, Mac, Linux or
any other platform. Your programs will work without any need to change it for every machine.
f. GUI Programming - You can use it to develop a GUI (Graphical User Interface). One
way to do this is through Tkinter.
g. Large Python Library Python provides you with a large standard library.
Applications of Python
 Build a website using Python
 Develop a game in Python
 Perform Computer Vision (Facilities like face-detection and color-detection)
 Implement Machine Learning (Give a computer the ability to learn)
 Enable Robotics with Python
 Perform Web Scraping (Harvest data from websites)
 Perform Data Analysis using Python
 Automate a web browser
 Perform Scripting in Python
 Perform Scientific Computing using Python
 Build Artificial Intelligence
Tokens
In a passage of text, individual words and punctuation marks are called tokens or lexical
units or lexical elements. The smallest individual unit in a program is known as Tokens. Python
has following tokens:
Keywords
Keywords are the reserved words and have special meaning for python interpreter. Every
keyword is assigned specific work and it can be used only for that purpose.
Identifiers
Are the names given to different parts of program like variables, objects, classes, functions
etc. Identifier forming rules of Python are :
1
SNAKE GAME 2023-24
 Is an arbitrarily long sequence of letters and digits
 The first character must be letter or underscore
 Upper and lower case are different
 The digits 0-9 are allowed except for first character
 It must not be a keyword
 No special characters are allowed other than underscore is allowed.
 Space not allowed
Literal
Literals are data items that have a fixed value. Python supports several kinds of literals:

o String Literal
o Numeric Literals
o Boolean Literals
o Special Literals – None
String Literal is a collection of character(s) enclosed in a double or single quotes. It can be
either Single line strings or Multiline Strings
Numeric literals in Python can belong to any of the following numerical types:
Integer Literals: it contain at least one digit and must not contain decimal point. It may
contain (+) or (-) sign.
Floating point Literals: Also known as real literals. Real literals are numbers having
fractional parts.
Complex number Literals: Complex number in python is made up of two floating
Boolean literals in Python is used to represent one of the two Boolean values i.e. True or False
Python has one Special literal, which is None. It indicates absence of value. In other languages
it is knows as NULL.
Operators
Type ofOperators Symbols

Arithmetic +, -, *, /, %, **,//

Relational >, <, >=, <=, ==,!=

Logical and,or

Identity is, is not

Assignment =

Membership in, notin

Arithmetic Assignment +=, -=, *=, /=, %=, **=,//=

Bitwise &, ^, |, <<,>>


Punctuators

2
SNAKE GAME 2023-24
Punctuators are symbols that are used in programming languages to organize sentence
structure, and indicate the rhythm and emphasis of expressions, statements, and program
structure. Common punctuators are: „ “ # $ @ []{}=:;(),.
Data Types
Data Type specifies which type of value a variable can store. type() function is used to
determine a variable's type in Python.
Data Types in Python - Number String Boolean List Tuple Set Dictionary
Number In Python:
It is used to store numeric values
Python has three numeric types:
 Integers
 Floating point numbers
 Complex numbers
(i)Integers
Integers or int are positive or negative numbers with no decimal point. Integers in Python
3 are of unlimited size.
(ii)Floating point numbers
It is a positive or negative real numbers with a decimal point.e.g.

(iii)Complex numbers
Complex numbers are combination of a real and imaginary part.Complex numbers are in
the form ofX+Yj, where X is a real part and Y is imaginary part.
String In Python
A string is a sequence of characters. In python we can create string using single (' ') or
double quotes (" ").Both are same in python.
Boolean In Python
It is used to store two possible values either true or false
List In Python
List are collections of items and each item has its own index value.
Tuple In Python
List and tuple, both are same except,a list is mutable python objects and tuple is
immutable Python objects. Immutable Python objects mean you cannot modify the contents of a
tuple once it is assigned.
Set In Python
It is an unordered collection of unique and immutable (which cannot be modified)items.
Dictionary In Python
It is an unordered collection of items and each item consist of a key and a value.
Expression:
It is a valid combination of operators,literals and variable.

Arithmatic expression :- e.g. c=a+b

Relational expression :- e.g. x>y

Logical expression :- a or b
3
SNAKE GAME 2023-24
String expression :- c=“comp”+”sc”
Type Conversion:
The process of converting the value of one data type (integer, string, float, etc.) to
anotherdata type is called type conversion.Python has two types of type conversion.

 Implicit Type Conversion


 Explicit Type Conversion
Implicit Type Conversion:
In Implicit type conversion, Python automatically converts one data type to another data
type. This process doesn't need any user involvement.
Explicit Type Conversion:
In Explicit Type Conversion, users convert the data type of an object to requireddata
type. We use the predefined functions like int(),float(),str() etc. e.g.
Control Flow Statements
Control statements are used to control the flow of execution depending upon the specified
condition/logic. There are three types of control statements.

1. Decision Making Statements


2. Iteration Statements (Loops)
3. Jump Statements (break, continue, pass)
Decision making
Decision making statement used to control the flow of execution of program depending
upon condition. (if) if statement in Python is of many forms:

 if without false statement


 if with else
 if with elif
 Nested if
Looping
To carry out repetition of statements Python provide 2 loop statements
Conditional loop (while)
Counting loop (for)
Jump Statements

Jump statements are used to transfer the program's control from one location to another.
Means these are used to alter the flow of a loop like - to skip a part of a loop or terminate a loop

There are three types of jump statements used in python.

1. break

2. continue

3. pass

4
SNAKE GAME 2023-24

About Database
Data:
In simple words data can be facts related to any object in consideration. For example your
name, age, height, weight, etc are some data related to you. A picture,image , file , pdfetc can
also be considered data.
What is a Database?
Database is a systematic collection of data. Databases support storage and manipulation
of data. Databases make data management easy. Let's discuss few examples.

An online telephone directory would definitely use database to store data pertaining to
people, phone numbers, other contact details, etc.
Why do we need database
To manage large chunks of data: if size of data increases into thousands of records, it will
simply create a problem to manage.Database can manage large amount of data.

Accuracy: Through validation rule in database, data accuracy can be maintained.

Ease of updating data: With the database, we can flexibly update the data according to
our convenience. Moreover, multiple people can also edit data at same time.

Security of data: With databases we have security groups and privileges to restrict access.

Data integrity: In databases, we can be assured of accuracy and consistency of data due to
the built in integrity checks and access controls.

Advantages of Database System

● Databases reduce Redundancy: It removes duplication of data because data are kept at
one place and all the application refers to the centrally maintained database.

● Database controls Inconsistency: When two copies of the same data do not agree to each
other, then it is called Inconsistency. By controlling redundancy, the inconsistency is also
controlled.

● Database facilitates Sharing of Data; Data stored in the database can be shared among
several users.

● Database ensures Security: Data are protected against accidental or intentional disclosure
to unauthorized person or unauthorized modification.

● Database maintains Integrity: It enforces certain integrity rules to insure the validity or
correctness of data. For ex. A date can’t be like 31/31/2000.

● Database enforce standards:

5
SNAKE GAME 2023-24
What is a Database Management System (DBMS)?
Database Management System (DBMS) is a collection of programs which enables its
users to access database, manipulate data, reporting / representation of data.
It also helps to control access to the database.
Types of DBMS
Let's see how the DBMS family got evolved with the time. Following diagram shows the
evolution of DBMS categories.
There are 4 major types of DBMS.
Hierarchical DBMS
In a Hierarchical database, model data is organized in a tree-like structure. Data is Stored
Hierarchically (top down or bottom up) format. Data is represented using a parent-child
relationship. In Hierarchical DBMS parent may have many children, but children have only one
parent.
Network Model
The network database model allows each child to have multiple parents. It helps you to
address the need to model more complex relationships like as the orders/parts many-to-many
relationship. In this model, entities are organized in a graph which can be accessed through
several paths.
Relational model
Relational DBMS is the most widely used DBMS model because it is one of the easiest.
This model is based on normalizing data in the rows and columns of the tables. Relational model
stored in fixed structures and manipulated using SQL.
Object-Oriented Model
In Object-oriented Model data stored in the form of objects. The structure which is called
classes which display data within it. It defines a database as a collection of objects which stores
both data members values and operations.
What is Relational Model
The relational model represents the database as a collection of relations. A relation is
nothing but a table of values. Every row in the table represents a collection of related data values.
These rows in the table denote a real-world entity or relationship.

The table name and column names are helpful to interpret the meaning of values in each
row. The data are represented as a set of relations. In the relational model, data are stored as
tables. However, the physical storage of the data is independent of the way the data are logically
organized.

Relational Model Concepts


Attribute: Each column in a Table. Attributes are the properties which define a
relation. e.g., Student_Rollno, NAME,etc.
Tables – In the Relational model the, relations are saved in the table format. It is stored
along with its entities. A table has two properties rows and columns. Rows represent records and
columns represent attributes.
Tuple – It is nothing but a single row of a table, which contains a single record.
Relation Schema: A relation schema represents the name of the relation with its
attributes.
6
SNAKE GAME 2023-24
Degree: The total number of attributes which in the relation is called the degree of the
relation.
Cardinality: Total number of rows present in the Table.
Column: The column represents the set of values for a specific attribute.
Relation instance – Relation instance is a finite set of tuples in the RDBMS system.
Relation instances never have duplicate tuples.
Relation key - Every row has one, two or multiple attributes, which is called relation
key.
Attribute domain – Every attribute has some pre-defined value and scope which is
known as attribute domain
Domain :It is a collection of values from which the value is derived for a column.
What are Keys?
A DBMS key is an attribute or set of an attribute which helps you to identify a row(tuple)
in a relation(table). They allow you to find the relation between two tables. Keys help you
uniquely identify a row in a table by a combination of one or more columns in that table.
Why we need a Key?
Here, are reasons for using Keys in the DBMS system.
Keys help you to identify any row of data in a table. In a real-world application, a table
could contain thousands of records. Moreover, the records could be duplicated. Keys ensure that
you can uniquely identify a table record despite these challenges.
Allows you to establish a relationship between and identify the relation between tables
Help you to enforce identity and integrity in the relationship.
What is a Primary Key?
PRIMARY KEY is a column or group of columns in a table that uniquely identify every
row in that table. The Primary Key can't be a duplicate meaning the same value can't appear
more than once in the table. A table cannot have more than one primary key.
Rules for defining Primary key:
Two rows can't have the same primary key value
It must for every row to have a primary key value.
The primary key field cannot be null.
The value in a primary key column can never be modified or updated if any foreign key
refers to that primary key.
What is the Alternate key?
ALTERNATE KEYS is a column or group of columns in a table that uniquely identify
every row in that table. A table can have multiple choices for a primary key but only one can be
set as the primary key. All the keys which are not primary key are called an Alternate Key.
What is a Candidate Key?
CANDIDATE KEY is a set of attributes that uniquely identify tuples in a table.
Candidate Key is a super key with no repeated attributes. The Primary key should be selected
from the candidate keys. Every table must have at least a single candidate key. A table can have
multiple candidate keys but only a single primary key.
Properties of Candidate key:
It must contain unique values
Candidate key may have multiple attributes
Must not contain null values
7
SNAKE GAME 2023-24
It should contain minimum fields to ensure uniqueness
Uniquely identify each record in a table
What is the Foreign key?
FOREIGN KEY is a column that creates a relationship between two tables. The purpose
of Foreign keys is to maintain data integrity and allow navigation between two different
instances of an entity. It acts as a cross-reference between two tables as it references the primary
key of another table.
SQL
SQL is an acronym of Structured Query Language. It is a standard language developed
and used for accessing and modifying relational databases.
The SQL language was originally developed at the IBM research laboratory in San José
in the early 70s.
SQL is being used by many database management systems. Some of them are:
MySQL, PostgreSQL, Oracle, SQLite, Microsoft SQL Server
Features of SQL:
1. Retrieve data from database
2. Insert data in database
3. Update data in database
4. Create new database
5. Create new tables in database
6. Create views in database

Advantages of using SQL,


1. Easy to use: Commands are very easy to use & learn
2. Portable: it is compatible with other databases.
3. Handle large volume of data
4. Reliable: Well defined commands always provide desirable results without ambiguity.
5. Provide data abstraction (security of data); provides greater degree of abstraction as
compared to other procedural language.
6. Easily linked with HLL(High level languages)
7. Case insensitive

Data Definition Language

DDL commands are used for creating databases and tables. It contains necessary
statements for creating, manipulating, altering and deleting tables.
1. CREATE (create database and table)
2. ALTER (alter table)
3. DROP (delete table)

Data Manipulation Language:


DML commands are used for manipulating Data.
1. SELECT (view data from table)
2. INSERT (insert data in table)
3. UPDATE (update data in table)

8
SNAKE GAME 2023-24
4. DELETE (delete data from table)

SQL commands:
Getting listings of databases;
mysql> SHOW DATABASES;
Creating a database-
mysql> CREATE database <databasename>;
mysql> CREATE database myschool;
Deleting a database
mysql> DROP database <databasename>;
mysql> DROP database myschool;
After we have created the database we use the USE statement to change the current
mysql> USE <database name>;
mysql> USE myschool;
Getting listings of tables in database(myschool)
mysql> SHOW TABLES;

The command DESCRIBE is used to view the structure of a table.


mysql> DESCRIBE <tablename>;
mysql> DESCRIBE student;
To remove a table (DROP)
mysql> drop table <tablename>;
mysql> drop table student;
Creating a table (CREATE)
mysql> CREATE TABLE student (lastname varchar(15),
Firstname varchar(15),
City varchar(20),
Class char(2));
Insert data in Table (INSERT)
To insert new rows into an existing table use the INSERT command:
mysql>INSERT INTO student values(‘Mohamed’,’Rashid’,’Adirampattinam’,’xii’);

INSERT command can also be used to take or derive values from one table and place
them in another by using it with a query. To do this, simply replace the VALUES clause with an
appropriate query as follows:

mysql>INSERT INTO newstudent SELECT * FROM student WHERE class=4;

View data from Table (SELECT)


With the SELECT command we can retrieve (or see) previously inserted rows:
mysql> SELECT * FROM student;

A general form of SELECT is:


SELECT what to select(field name) FROM table(s)
WHERE condition that the data must satisfy;

9
SNAKE GAME 2023-24
Conditions can be set with help of following operators:
Comparison operators are: < ;<= ; = ; != or <> ; >= ; >
Logical operators are:AND ; OR ; NOT
Comparison operator for special value NULL: IS
Selecting rows by using the WHERE clause in the SELECT command
mysql> SELECT * FROM student WHERE class=“4";
Selecting specific columns(Projection) by listing their names
mysql> SELECT first_name, class FROM student;
Update data in Table (UPDATE)
To modify or update entries in the table use the UPDATE command
mysql> UPDATE student SET class=“V" WHERE firstname=“freya";
All columns will be updated with same value
mysql> UPDATE student SET class=“V";
Delete data from Table
Deleting selected rows from a table using the DELETE command
mysql> DELETE FROM student WHERE firstname=“amar";
Eliminating Redundant Data: (with Keyword DISTINCT)
DISTINCT keyword eliminates duplicate rows from the result of a SELECT statement.
mysql> SELECT DISTINCT city FROM Student
mysql> SELECT DISTINCT city FROM Student WHERE class=4
BETWEEN - to access data in specified range
mysql> SELECT * FROM Student WHERE class between 4 and 6;
IN- operator allows us to easily test if the expression is in the list of values.
mysql> SELECT * FROM Student WHERE class in (4,5,6);
Pattern Matching – LIKE Operator
A string pattern can be used in SQL using the following wild card
%Represents a substring in any length
_Represents a single character
A pattern is case sensitive and can be used with LIKE operator.

mysql> SELECT * FROM Student WHERE Name LIKE ‘A%’;

mysql> SELECT * FROM Student WHERE Name LIKE ‘%Singh%’;

mysql> SELECT Name, City FROM Student WHERE Class>=8 AND Name LIKE
‘%Kumar%’ ;

Altering Table

The SQL ALTER TABLE command is used to add, delete or modify columns in an
existing table ALTER TABLE command is also used to add and drop various constraints on an
existing table. Syntax

ALTER TABLE command to add a New Column in an existing table is as follows.

ALTER TABLE table_name ADD column_namedatatype;

10
SNAKE GAME 2023-24
ALTER TABLE employee ADD (tel_number integer);

ALTER TABLE command to DROP COLUMN in an existing table is as follows.

ALTER TABLE table_name DROP COLUMN column_name;

ALTER TABLE employee DROP grade;

ALTER TABLE command to change the DATA TYPE of a column in a table is as follows.

ALTER TABLE table_name MODIFY COLUMN column_namedatatype;

ALTER TABLE employee MODIFY( Job char(30) );

ALTER TABLE command to change name of one column:

ALTER TABLE table_name CHANGE old_columnnew_columndatatype;

ALTER TABLE employee CHANGE First_NameFNamevarchar(30);

Ordering Query Result – ORDER BY Clause

A query result can be orders in ascending (A-Z) or descending (Z-A) order as per any
column. Default is Ascending order.

mysql> SELECT * FROM Student ORDER BY class;

mysql> SELECT * FROM Student ORDER BY City;

To get descending order use DESC key word.

mysql> SELECT * FROM Student ORDER BY class DESC;

mysql> SELECT * FROM Student ORDER BY City DESC;


mysql> SELECT Name, Fname, City FROM Student Where Name LIKE ‘R%’ ORDER
BY Class;
GROUP BY:
Sometimes it is required to apply a Select query in a group of records instead of the
whole table.
The GROUP BY clause combines all those records that have identical values in a
particular field or a group of fields. This grouping results into one summary record per group.
The GROUP BY Clause is used to group rows with the same values.
The GROUP BY Clause is used together with the SQL SELECT statement.
The SELECT statement used in the GROUP BY clause can only be used to contain
column names, aggregate functions, constants and expressions.

The HAVING clause is used to restrict the results returned by the GROUP BY clause.

11
SNAKE GAME 2023-24
Aggregate Functions
Name Purpose
SUM() Returns the sum of the given column.
MIN() Returns the minimum value in the given column.
MAX() Returns the maximum value in the given column.
AVG() Returns the Average value of the given column.
COUNT() Returns the total number of values/ records as per given column.

Aggregate Functions & Conditions

You may use any condition on group, if required. HAVING <condition> clause is used to
apply a condition on a group.

mysql> Select Job,Sum(Pay) from EMP Group By Job HAVING Sum(Pay)>=8000;

mysql> Select Job, Sum(Pay) from EMP Group By Job HAVING Avg(Pay)>=7000;

mysql> Select Job, Sum(Pay) from EMP Group By Job HAVING Count(*)>=5;

mysql> Select Job, Min(Pay),Max(Pay), Avg(Pay) from EMP Group By Job HAVING
Sum(Pay)>=8000;

mysql> Select Job, Sum(Pay) from EMP Where City=‘Jaipur’

Joins: equi-join and natural join

Cross Join (Cartesian product)

It return all possible concatenation of all rows from both table i.e. one row of First table
is joined with all the rows of second table.

Equi-join

The join, in which columns are compared for equality is called Equi-Join. A non-equijoin
specifies condition with non-equality operator. In equi-join we put(*) in the select list therefore
the common column will appear twice in the output.

Natural Join

The JOIN in which only one of the identical columns exists is called Natural Join. It is
similar to Equi-join except that duplicate columns are eliminated in Natural join that would
otherwise appear in Equi-Join.

12

You might also like