










Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
These notes provide a foundational introduction to python programming, covering key concepts such as data types, operators, and control flow. The history of python, its dynamic nature, and contrasts it with c programming. It also delves into various data types, including integers, floats, strings, lists, tuples, dictionaries, sets, and bytearrays, providing examples for each. The notes further explain the concept of mutable and immutable data types and illustrate how to use operators in python.
Typology: Study notes
1 / 18
This page cannot be seen from the preview
Don't miss anything!
History of python
Python is a popular programming language. It was created by Guido van Rossum, and released in 1991 at research center CWI (Centrum Wiskunde & Informatica) Netherland.
What is python?
Python is a very popular programming language - Mostly users and developers use python to develop a technology or to create games and applications etc. because it is simple and easy to learn that is why python is a very popular language. Python is a general purpose programming language – general purpose means python works on multiple domains like it is use to create games, application, graphics, web development etc. and other domains also. Python is a high level programming language – python is a high level programming language because it uses maximum English words or English language and don't care too much about syntax and commas. Python is an interpreted programming language – Because python contains by default interpreter, so that Python code is executed line by line by the Python interpreter during runtime, without the need for a separate run or compilation step. Python is a dynamic programming language – because in c, c++, java we have to declare the variable or data type of the variable for ex: Int a = 10; (here we have to declare data type of a variable, that a is an integer )
but in python a = 10, we use simple syntax, no need to declare any variable and if you want to check the data type of any variable you can use type function. for ex: a = 10 type (a) Output: int So, Python is a dynamically typed language. It doesn‟t know about the type of the variable until the code is run. So declaration is of no use. What it does is, It stores that value at some memory location and then binds that variable name to that memory container. And makes the contents of the container accessible through that variable name. So the data type does not matter. As it will get to know the type of the value at run-time.
Why python?
Simple and easy to learn, easy to read, easy to maintain. Platform independent – Linux, macOS, Windows and mobile devices. Free & open source
Rich library support – tensor flow, Numpy. Embeddable & Extensible – python is embedded because python is higher level than other common languages and fast, and keep your code understandable, the code you will write will be more concise or short. Also python is highly extensible with C, C++, Java code, python can be written in any language like C, C++, java etc. Portable – python is highly portable because python code can be run on different operating systems and platforms also on different devices. Robust – error handling, exception handling.
Where python is used?
Web frameworks and application – Node.js, asp.net, django, angular.js, all these are web frameworks used to develop a software‟s and applications. GUI based desktop applications – (GUI) Graphical User Interface. Features of windows that make the applications easy to use like menus (menu) give detailed list of option, dialog box created by GUI. Graphic design, Image processing, Games etc. Machine Learning, Artificial Intelligence and Neural Network. Data Science and Data visualization. IOT/IOE Database development
Variable A variable is a name attached to a value which can be changed and later used in a code.
Variable rules with examples No need to declare variables in python. Because in c, c++, java we have to declare the variable. for ex: Int a = 10; (here we have to declare data type of a variable, that a is an integer ) but in python a = 10, we use simple syntax, no need to declare any variable and if you want to check the data type of any variable you can use type function. For ex: a = 10 type (a) Output: int Value of a variable can be changed. For ex: a = 10 b = 20 a+b 30 a = 20 a+b 40
assert It^ is^ used^ for debugging
for It^ is^ used^ to create Loop
or It^ is^ a^ Logical Operator
break Break^ out^ a Loop
from
To import specific parts of a module
pass
pass is used when the user doesn‟t want any code to execute
class It^ is^ used^ to define a class
global
It is used to declare a global variable
raise
raise is used to raise exceptions or errors.
continue
Skip the next iteration of a loop
if
To create a Conditional Statement
return
return is used to end the execution
def
It is used to define the Function
import It^ is^ used^ to import a module
True
Represents an expression that will result in true.
del It^ is^ used^ to delete an object
is
It is used to test if two variables are equal
try Try^ is^ used^ to handle errors
elif
Conditional statements, same as else-if
in
To check if a value is present in a Tuple, List, etc.
while
While Loop is used to execute a block of statements
else
It is used in a conditional statement
lambda
Used to create an anonymous function
with
with statement is used in exception handling
except
try-except is used to handle these errors
None It^ represents^ a null value
yield
yield keyword is used to create a generator function
In Python, bitwise operators are used to perform bitwise calculations on integers. The integers are first converted into binary and then operations are performed on each bit or corresponding pair of bits, hence the name bitwise operators. The result is then returned in decimal format. Python bitwise operators work only on integers.
For ex: 5 & 6 Binary of 5: 101 Binary of 6: 110 100 Output: 4
For ex: a = 10 = 1010 (Binary) b = 4 = 0100 (Binary) a & b = 1010 & 0100 = 0000 = 0 (Decimal)
For ex: 5 | 6 Binary of 5: 101 Binary of 6: 110 111 Output: 7
For ex: a = 10 = 1010 (Binary) b = 4 = 0100 (Binary) a | b = 1010 | 0100 = 1110
= 14 (Decimal)
is 0, if both the input is different than output is 1) For ex: 5 ^ 6 Binary of 5: 101 Binary of 6: 110 011 Output: 7
For ex: a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary) a ^ b = 1010 ^ 0100 = 1110 = 14 (Decimal)
For ex:
Shifts the bits of the number to the right and fills 0 on voids left ( fills 1 in the case of a negative number) as a result. Example 1: a = 10 = 0000 1010 (Binary) a >> 1 = 0000 0101 = 5
Example 2: a = - 10 = 0000 1010 (Binary of 10) = 1111 0101 (1‟s complement)
= 1111 0110 (2‟s complement) a >> 1 = 1 111 1011 (shift right one times) = 0000 0100 (1‟s complement)
= 0000 0 101 (2‟s complement) = - 5
Shifts the bits of the number to the left and fills 0 on voids right as a result. Similar effect as of multiplying the number with some power of two.
Example 1: a = 5 = 0000 0101 (Binary) a << 1 = 0000 1010 = 10 (1 time shift left) a << 2 = 0001 0100 = 20 (2 times shift left)
Example 2: b = - 10 = 1111 0110 (Binary of - 10 after 1‟s and 2‟s) b << 1 = 1110 1100 = - 20 (1 time shift left) (after 1‟s and 2‟s result is - 20) b << 2 = 1101 1000 = - 40 (2 times shift left) (after 1‟s and 2‟s result is - 40)
Python offers two membership operators „in‟ or „not in‟ to check or validate the membership of a value. It tests for membership in a sequence, such as strings, lists, or tuples.
„in‟ or „not in‟ operator: The „in‟ or „not in‟ operator is used to check if a character/ substring/ element exists in a sequence or not. Evaluate to True if it finds the specified element in a sequence otherwise false.
For example: „in‟ operator
'G' in 'GeeksforGeeks' # Checking 'G' in String Output: True
'g' in 'GeeksforGeeks' #Checking 'g' in string since Python is case-sensitive, returns False Output: False
'Geeks' in ['Geeks', 'For‟, „Geeks'] #Checking 'Geeks' in list of strings Output: True
10 in [10000,1000,100,10] #Checking 10 in list of integers Output: True
dict1={1:'Geeks', 2:'For', 3:'Geeks'} # Checking 3 in keys of dictionary 3 in dict Output: True
For ex: „not in‟ operator
x = 24 y = 20 list = [10, 20, 30, 40, 50]
if (x not in list): print("x is NOT present in given list") else: print("x is present in given list")
if (y in list): print("y is present in given list") else: print("y is NOT present in given list")
Output x is NOT present in given list y is present in given list
In c, c++, java to create a blocks we use pair of curly braces {}. The beginning of the block is denoted by an open curly brace '{' and the end is denoted by a closing curly brace '}'.
For example:
#include <stdio.h> int main() { int n = 1; { int n = 2; printf("%d \n ", n); } printf("%d \n ", n); } Block is a collection of code. In python to create a blocks we use indentation with the help of „spacebar‟ (press spacebar 4 times) or „Tab‟ key. White space is used for indentation in python. In python execution takes place from the first column. Without given 1 column space, 2 column spaces etc. you have to write the statement otherwise it will give indentation error. For ex:
1 column space gives indentation error
Before write any statement no space will be given, No need to give 1 column space or 2 column space etc., hence no error, you will get the output
Python uses indentation to define blocks of code. Each code block starts with an indentation and
ends when the indentation level returns to a previous level.
if True : print ( "This is inside a code block." ) print ( "This is outside the code block." )
If Statements
In if statements or other conditional statements, code blocks define the lines of code to execute when
conditions evaluate to True. age = 20 if age >= 18 : print ( "Adult" ) # This is a code block else : print ( "Minor" ) # This is another code block
Functions
Every Python function uses a code block to contain its operations.
def greet (): print ( "Hello, welcome!" ) # Function's code block
Loops
For loops execute code blocks as long as there are items in a sequence to iterate over. While
loops execute code blocks as long as a specified condition is true. for i in range ( 5 ): print (i) # Loop's code block
Two types of data types in python:
Mutable Data type: This can be change after creation. For ex: List, Set, Dictionary and Byte array. Mutable data type contains different data. For ex: list = [2, 2.5, „Ram‟, 100, „a‟].
Immutable Data type: This cannot be change after creation. For ex: Numbers, Strings, Tuples, Boolean, Range, Bytes, None Type. Immutable data type contains same type of data, only numbers or only characters. For ex: number = 10 or x = „varun‟ etc.
Python Data types with examples:
Python is a dynamic language so we do not need to declare the data type of any variable in python,
but if you want to check the data type of any variable you can use type function type().
type(), Type function is use to check the data type of any variable.
Python has several built-in (by default) data types, including numeric types (int, float, complex),
string (str), boolean (bool), and collection types (list, tuple, dict, set) etc.
Numeric Data Type/ Number Data Type Text Data Type Boolean Data Type Sequence Data Type Mapping Data Type Set Data Type Binary Data Type None Type
1. Numeric Data Type/ Number Data Type: int float complex 2. Text Data Type: str 3. Boolean Data Type: Boolean means true or false. bool 4. Sequence Data Type: List tuple range 5. Mapping Data Type: dict 6. Set Data Type: set 7. Binary Data Type: bytes bytearray
separated by commas. It is mutable data type, which can be change after creation. It contains different
data. For ex:
list1 = [100, 200, 300] type(list1) output: list print(list1) output: [100, 200, 300]
list can contains different data either string, integer or float values etc. for example:
list = [2, 2.5, “ram”, “sita”] list = [1, 2, 3, 3, 5, 4, 4, 6, 7] list = [„cheese‟, “milk”, “curd”]
It is mutable data type, which can be change after creation. Using append, append means to add
something. So you can add more no. of items in the list after creation because it is mutable data type.
For ex:
Food = ["eggs", "bread", "juice"] print(Food) output: [„eggs‟, „bread‟, „juice‟] Food.append(„chocolate‟) print(Food) output: [„eggs‟, „bread‟, „juice‟, „chocolate‟]
For ex: a = [5, 4, 3] a.append( 6 ) print(a) output: [5, 4, 3, 6]
brackets (). It is immutable data type, which cannot be change after creation. Contains different types of data. For example:
var = ("sun", "star", "moon") print(var) output: ("sun", "star", "moon") type(var) output: tuple It is immutable data type, which cannot be change after creation. you cannot add extra values after
creation in case of tuple. For ex:
a = (5, 4, 3) a.append( 6 ) print(a) output: error
tuple also contains different types of data either number, string or float values etc. For example:
T = (10, 20, 30) t = ("sun", "star", "moon") tup = (“ram”, 2, 3, “sita”, 2.5)
The key difference between tuples and lists is that while the tuples are immutable objects, lists are
mutable. This means that tuples cannot be changed while lists can be modified.
by 1 (by default), and stops before a specified number. It is immutable data type, which cannot be
change after creation.
Syntax range (start, stop, step )
Parameter Values
Parameter Description
start Optional. An integer number specifying at which position to start. Default is 0
stop Required. An integer number specifying at which position to stop (not included).
step Optional. An integer number specifying the incrementation. Default is 1
For ex: x = range( 6 ) for n in x: print(n) Output: 0 1 2 3 4 5 type(x) output: range
here „a‟ is key and 1 is value. A dictionary is a collection which is ordered, changeable and do not allow duplicates. Dictionaries are written with curly brackets {}, and have keys and values. It is mutable data type, which can be change after creation. Contains different data either string, integer or float values.
For ex: d = {"name": "varun", "age": 32, "city": "pune"} print(type(d)) output: <class 'dict'>
to check any particular key value: print (d[“city”]) output: pune print (d[“age”]) output: 32
For ex: n = range(0,5) print(type(n)) output: range(0, 5)