2. Specify a Variable Type
Casting in python is therefore done using constructor functions:
• int() - constructs an integer number from an integer literal, a float
literal (by rounding down to the previous whole number), or a string
literal (providing the string represents a whole number)
• float() - constructs a float number from an integer literal, a float literal
or a string literal (providing the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including
strings, integer literals and float literals
3. Multiline Strings
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.""“
print(a)
5. Python Collections (Arrays)
There are four collection data types in the Python programming language:
• List [] is a collection which is ordered and changeable. Allows duplicate members.
• Tuple () is a collection which is ordered and unchangeable. Allows duplicate
members.
• Set {} is a collection which is unordered and unindexed. No duplicate members.
• Dictionary {} is a collection which is unordered, changeable and indexed. No
duplicate members.
9. Dictionary
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
x = thisdict["model"]
thisdict["year"] = 2018
print(len(thisdict))
thisdict["color"] = "red“
thisdict.pop("model")
del thisdict["model"]
mydict = thisdict.copy()
for x in thisdict:
print(x) #key
print(thisdict[x]) #value
for x in thisdict.values():
print(x)
for _key , _value in thisdict.items():
print(_key,_value)
if "model" in thisdict:
print("Yes, keys in the dictionary")
10. IF Statement
a= Ture
b=True
If (a and b) :
print (“aaaaaaaaaaaaaaa”)
elif (a or b) :
print (“bbbbbbbbbbbbb”)
elif not(a and b) :
print (“cccccccccccccccc”)
else
print(“ddddddddddddd”)
11. For Statement
for i in range(13):
for j in range(13):
print(str(i)+" X "+str(j)+" = "+str(i*j))
print("=========================")
12. Python Functions
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
def my_func():
print("Hello from a function")
my_func()
def my_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_function(fruits)
def my_function(country = "Norway"):
print("I am from " + country)
my_function("India")
my_function()
my_function("Brazil")
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
13. Python Functions
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result
print("nnRecursion Example Results")
tri_recursion(6)
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
14. Python Classes and Objects
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
15. Python Inheritance
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
x = Student("Mike", "Olsen", 2019)
x.welcome()
16. Iterable
Lists, tuples, dictionaries, and sets are all iterable objects.
mytuple = ("apple", "banana", "cherry")
myit = iter(mytuple)
print(next(myit))
print(next(myit))
print(next(myit))
18. Python JSON
import json
# some JSON:
x = '{ "name":"John", "age":30, "city":"New York"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])
19. convert it into a JSON string
import json
# a Python object (dict):
x = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)
20. Python Try Except
try:
f = open("demofile.txt")
f.write("Lorum Ipsum")
except:
print("Something went wrong when writing to the file")
finally:
f.close()
22. File Handling
f = open("demofile.txt", "rt")
print(f.read()) #read All Lines
for one_Line in f:
print(one_Line)
f.close()
############################
f1 = open("demofile2.txt", "a")
f1.write("Now content!")
f1.close()
############################
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
os.rmdir("myfolder")
24. Python MySQL
Download a free MySQL database at
https://dev.mysql.com/downloads/mysql/5.5.html
Download and install "MySQL Connector":
python -m pip install mysql-connector
28. INSERT INTO Statement
• INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
• INSERT INTO table_name
VALUES (value1, value2, value3, ...);
29. SQL SELECT Statement
• SELECT column1, column2, ...
FROM table_name;
• SELECT * FROM table_name;
• SELECT DISTINCT column1, column2, ...
FROM table_name;
• SELECT COUNT(DISTINCT Country) FROM Customers;
30. SQL WHERE Clause
• SELECT column1, column2, ...
FROM table_name
WHERE condition;
• SELECT * FROM Customers
WHERE Country='Mexico’;
• SELECT * FROM Customers
WHERE CustomerID=1;
32. SQL AND, OR and NOT Operators
• SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
• SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;
• SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
33. SQL AND, OR and NOT Operators
• SELECT * FROM Customers
WHERE Country='Germany' AND City='Berlin';
• SELECT * FROM Customers
WHERE City='Berlin' OR City='München';
• SELECT * FROM Customers
WHERE NOT Country='Germany';
34. Combining AND, OR and NOT
• SELECT * FROM Customers
WHERE Country='Germany' AND (City='Berlin' OR City='München’);
• SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';
35. SQL ORDER BY Keyword
• SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
• SELECT * FROM Customers
ORDER BY Country;
• SELECT * FROM Customers
ORDER BY Country DESC;
• SELECT * FROM Customers
ORDER BY Country, CustomerName;
• SELECT * FROM Customers
ORDER BY Country ASC, CustomerName DESC;
36. UPDATE Statement
• UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
• UPDATE Customers
SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
WHERE CustomerID = 1;
• UPDATE Customers
SET ContactName='Juan'
WHERE Country='Mexico';
37. DELETE Statement
• DELETE FROM table_name;
• DELETE FROM table_name WHERE condition;
• DELETE FROM Customers WHERE CustomerName='Alfreds
Futterkiste';
38. MIN() and MAX() Functions
• SELECT MIN(column_name)
FROM table_name
WHERE condition;
• SELECT MAX(column_name)
FROM table_name
WHERE condition;
• SELECT MIN(Price) AS SmallestPrice
FROM Products;
• SELECT MAX(Price) AS LargestPrice
FROM Products;
39. COUNT(), AVG() and SUM()
• SELECT COUNT(ProductID)
FROM Products;
• SELECT AVG(Price)
FROM Products;
• SELECT SUM(Quantity)
FROM OrderDetails;
40. LIKE Operator
wildcards for LIKE operator:
• % The percent sign represents zero, one, or multiple characters
• _ The underscore represents a single character
• SELECT column1, column2, ...
FROM table_name
WHERE column LIKE pattern;
• SELECT * FROM Customers
WHERE City LIKE 'ber%';
• SELECT * FROM Customers WHERE City LIKE '%es%’;
• SELECT * FROM Customers WHERE City LIKE '_ondon';
41. IN Operator
• SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);
• SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);
• SELECT * FROM Customers
WHERE Country IN ('Germany', 'France', 'UK’);
• SELECT * FROM Customers
WHERE Country IN (SELECT Country FROM Suppliers);
42. BETWEEN Operator
• SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
• SELECT * FROM Products
WHERE Price BETWEEN 10 AND 20;
• SELECT * FROM Products
WHERE Price NOT BETWEEN 10 AND 20;
46. Python MySQL Select From
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
47. Python MySQL Update From
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "UPDATE customers SET address = %s WHERE address = %s"
val = ("Valley 345", "Canyon 123")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")