Q. What is Python?
Ans. Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
It is used for:
web development (server-side),
software development,
mathematics,
system scripting.
Q. What can Python do?
Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software
development.
Q. Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
Python can be treated in a procedural way, an object-oriented way or a functional
way.
Creating a Comment
Comments starts with a #, and Python will ignore them:
Example:
#This is a comment
print("Hello, World!")
Variables
Variables are containers for storing data values.
Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.
Example 1:
x=5
y = "John"
print(x)
print(y)
Example 2:
x=4 # x is of type int
x = "Sally" # x is now of type str
Single or Double Quotes?
String variables can be declared either by using single or double quotes:
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Rules for Python variables:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-
9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
A variable name cannot be any of the Python keywords.
Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line:
Example:
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
DATA TYPES
Python has the following built-in data types:
1. Numeric Types
(i) Integers (int): Whole numbers, e.g., 1, 2, 3, etc.
(ii)Floating Point Numbers (float): Decimal numbers, e.g., 3.14, -0.5, etc.
(iii)Complex Numbers (complex): Numbers with real and imaginary parts, e.g., 3 + 4j.
2. Text Type
String (str): A sequence of characters, e.g., "hello", 'hello', etc.
3. Sequence Types
(i)List: An ordered collection of items, e.g., [1, 2, 3], ["a", "b", "c"], etc.
(ii)Tuple: An ordered, immutable collection of items, e.g., (1, 2, 3), ("a", "b", "c"), etc.
4. Mapping Type
(i) Dictionary (dict): An unordered collection of key-value pairs.
e.g., {"name": "John", "age": 30}, etc.
5. Set Types: An unordered collection of unique items, e.g., {1, 2, 3}, {"a", "b", "c"}, etc.
6. Boolean Type: A logical value that can be either True or False.
7. Binary Types
Python has the following data types built-in by default, in these categories:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the
string.
Example:
Get the characters from position 2(included) to position 5 (excluded),
the first character has index 0.
b = "Hello, World!"
print(b[2:5]) # Output will be: llo
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5]) # Output will be: Hello
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:]) # Output will be: llo, World!
Negative Indexing
The Sequence of negative Indexing
-12 -11 -10 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
H e l l o , W o r l d !
Get the characters From: "o" in "World!" (position -5) To, but not included: "d" in "World!"
(position -2):
b = "Hello, World!"
print(b[-5:-2])
Upper Case
The upper() method returns the string in upper case:
a = "Hello, World!"
print([Link]())
Lower Case
The lower() method returns the string in lower case:
a = "Hello, World!"
print([Link]())
Remove Whitespace
The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print([Link]()) # returns "Hello,World!"
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
a = "Hello"
b = "World"
c=a+b
print(c) # returns "HelloWorld"
To add a space between them, add a " ":
a = "Hello"
b = "World"
c=a+""+b
print(c) # returns "Hello World"
Boolean Values
In programming you often need to know if an expression is True or False.
Example:
print(10 > 9) # returns True
print(10 == 9) # returns True
print(10 < 9) # returns False
Python Arithmetic Operators
Operator Name Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Python Assignment Operators:
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
^= x ^= 3 x=x^3
x=3
:= print(x := 3)
print(x)
List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary.
Lists are created using square brackets:
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
Allow Duplicates: Since lists are indexed, lists can have items with the same value:
thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])
This example returns the items from "cherry" to the end:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
This example returns the items from "orange" (-4) to, but NOT including "mango" (-1):
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
Check if "apple" is present in the list:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Change the values "banana" and "cherry" with the values "blackcurrant" and
"watermelon":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
[Link]("orange")
print(thislist)
Remove "banana":
thislist = ["apple", "banana", "cherry"]
[Link]("banana")
print(thislist)
Print all items in the list, one by one:
for x in thislist:
print(x)
Print all items by referring to their index number:
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i]) #The iterable created in the example above is [0, 1, 2].
Sort the list alphabetically:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
[Link]()
print(thislist)
Join two list:
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the
current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Tuple
Tuples are used to store multiple items in a single variable. A tuple is a collection which is
ordered and unchangeable, and allow duplicate values. Tuples are written with round
brackets.
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Return the third, fourth, and fifth item:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)
Join two tuples:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)
tuple3 = tuple1 + tuple2
print(tuple3)
Set
Sets are used to store multiple items in a single variable. A set is a collection which
is unordered, unchangeable*, and unindexed. It do not allow duplicate values.
* Note: Set items are unchangeable, but you can remove items and add new items.
Create a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Loop through the set, and print the values:
for x in thisset:
print(x)
Add Items
Once a set is created, you cannot change its items, but you can add new items.
To add one item to a set use the add() method.
[Link]("orange")
print(thisset)
Remove Item: Remove "banana" by using the remove() method:
thisset = {"apple", "banana", "cherry"}
[Link]("banana")
print(thisset)
Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Dictionary
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Print the "brand" value of the dictionary:
print(thisdict["brand"])
The del keyword removes the item with the specified key name:
del thisdict["model"]
print(thisdict)
The del keyword can also delete the dictionary completely:
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.
Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])