SlideShare una empresa de Scribd logo
1 de 47
Python
Rafie Tarabay
eng_rafie@mans.edu.eg
mrafie@eg.ibm.com
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
Multiline Strings
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.""“
print(a)
Python Comparison/Assignment Operators
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.
List
thislist=["apple","banana","cherry","orange","kiwi","melon"]
print(thislist[1])
print(thislist[-1])
print(thislist[2:5])
print(thislist[:4])
print(thislist[2:])
thislist[1]="blackcurrant“
print(len(thislist))
forxinthislist:
print(x)
if"apple"inthislist:
print("Yes,'apple'isinthefruitslist")
thislist.append("orange")
thislist.insert(1,"orange")
thislist.remove("banana")
thislist.pop()
delthislist[0]
mylist=thislist.copy()
list3=thislist+mylist
SET (Un-Order List)
thisSET={"apple","banana","cherry","orange","kiwi","melon“}
print(thisSET[1])
print(thisSET[-1])
print(thisSET[2:5])
print(thisSET[:4])
print(thisSET[2:])
thisSET[1]="blackcurrant“
print(len(thisSET))
forxinthisSET:
print(x)
if"apple"inthisSET:
print("Yes,'apple'isinthefruitslist")
thisSET.append("orange")
thisSET.add("orange")
thisSET.insert(1,"orange")
thisSET.remove("banana")
thisSET.pop()
delthisSET[0]
mylist=thisSET.copy()
list3=thisSET+mylist
set3=set1.union(set2) #removeduplicate
Red means not valid
Tuple (Read-Only List)
thisTuple=("apple","banana","cherry","orange","kiwi","melon“)
print(thisTuple[1])
print(thisTuple[-1])
print(thisTuple[2:5])
print(thisTuple[:4])
print(thisTuple[2:])
thisTuple[1]="blackcurrant“
print(len(thisTuple))
forxin thisTuple:
print(x)
if"apple"in thisTuple:
print("Yes,'apple'isinthefruitstuple")
thisTuple.append("orange")
thisTuple.insert(1,"orange")
thisTuple.remove("banana")
thisTuple.pop()
del thisTuple[0]
mylist=thislist.copy()
tuple3 = tuple1 + tuple2
Red means not valid
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")
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”)
For Statement
for i in range(13):
for j in range(13):
print(str(i)+" X "+str(j)+" = "+str(i*j))
print("=========================")
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))
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")
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()
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()
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))
Python Iterators
class MyNumbers:
def __iter__(self):
self.a = 0
return self
def __next__(self):
self.a += 1
if self.a >100:
raise StopIteration
else:
return self.a
myclass = MyNumbers()
myiter = iter(myclass)
print(next(myiter))
print(next(myiter))
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"])
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)
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()
Python User Input
username = input("Enter username:")
print("Username is: " + username)
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")
Python Requests Module
import requests
x = requests.get('https://w3schools.com/python/demopage.htm')
print(x.text)
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
SQL Commands
Database Table
Here is a Sample DB table with name “Customers”
CREATE TABLE
• CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
• CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);
INSERT INTO Statement
• INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
• INSERT INTO table_name
VALUES (value1, value2, value3, ...);
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;
SQL WHERE Clause
• SELECT column1, column2, ...
FROM table_name
WHERE condition;
• SELECT * FROM Customers
WHERE Country='Mexico’;
• SELECT * FROM Customers
WHERE CustomerID=1;
Operators in The WHERE Clause
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;
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';
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';
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;
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';
DELETE Statement
• DELETE FROM table_name;
• DELETE FROM table_name WHERE condition;
• DELETE FROM Customers WHERE CustomerName='Alfreds
Futterkiste';
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;
COUNT(), AVG() and SUM()
• SELECT COUNT(ProductID)
FROM Products;
• SELECT AVG(Price)
FROM Products;
• SELECT SUM(Quantity)
FROM OrderDetails;
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';
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);
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;
Python MySQL
Handel DB from Python
Python Mysql Connection
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
mycursor.execute("SHOW DATABASES")
for x in mycursor:
print(x)
mycursor.execute("CREATE TABLE mydatabase .customers (name VARCHAR(255), address VARCHAR(255))")
Mysql Insert
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
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)
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")

Más contenido relacionado

La actualidad más candente

Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)
stasimus
 

La actualidad más candente (19)

Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)Introduction to Monads in Scala (2)
Introduction to Monads in Scala (2)
 
Python3 cheatsheet
Python3 cheatsheetPython3 cheatsheet
Python3 cheatsheet
 
Scala. Introduction to FP. Monads
Scala. Introduction to FP. MonadsScala. Introduction to FP. Monads
Scala. Introduction to FP. Monads
 
Array 31.8.2020 updated
Array 31.8.2020 updatedArray 31.8.2020 updated
Array 31.8.2020 updated
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
R Language Introduction
R Language IntroductionR Language Introduction
R Language Introduction
 
Data transformation-cheatsheet
Data transformation-cheatsheetData transformation-cheatsheet
Data transformation-cheatsheet
 
Basic Analysis using R
Basic Analysis using RBasic Analysis using R
Basic Analysis using R
 
Basic Analysis using Python
Basic Analysis using PythonBasic Analysis using Python
Basic Analysis using Python
 
Python_ 3 CheatSheet
Python_ 3 CheatSheetPython_ 3 CheatSheet
Python_ 3 CheatSheet
 
Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?Why async and functional programming in PHP7 suck and how to get overr it?
Why async and functional programming in PHP7 suck and how to get overr it?
 
C programming , array 2020
C programming , array 2020C programming , array 2020
C programming , array 2020
 
Mementopython3 english
Mementopython3 englishMementopython3 english
Mementopython3 english
 
Cheat sheet python3
Cheat sheet python3Cheat sheet python3
Cheat sheet python3
 
Oh, All the things you'll traverse
Oh, All the things you'll traverseOh, All the things you'll traverse
Oh, All the things you'll traverse
 
20170509 rand db_lesugent
20170509 rand db_lesugent20170509 rand db_lesugent
20170509 rand db_lesugent
 
Arrays in C language
Arrays in C languageArrays in C language
Arrays in C language
 
R learning by examples
R learning by examplesR learning by examples
R learning by examples
 
Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020Monoids, Monoids, Monoids - ScalaLove 2020
Monoids, Monoids, Monoids - ScalaLove 2020
 

Similar a Python crush course

3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib
웅식 전
 

Similar a Python crush course (20)

Python programming workshop
Python programming workshopPython programming workshop
Python programming workshop
 
C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)C cheat sheet for varsity (extreme edition)
C cheat sheet for varsity (extreme edition)
 
Python basic
Python basicPython basic
Python basic
 
Class 2: Welcome part 2
Class 2: Welcome part 2Class 2: Welcome part 2
Class 2: Welcome part 2
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHON
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Introduction to Go
Introduction to GoIntroduction to Go
Introduction to Go
 
MODULE. .pptx
MODULE.                              .pptxMODULE.                              .pptx
MODULE. .pptx
 
Python.pdf
Python.pdfPython.pdf
Python.pdf
 
C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607C# 6 and 7 and Futures 20180607
C# 6 and 7 and Futures 20180607
 
Writing a compiler in go
Writing a compiler in goWriting a compiler in go
Writing a compiler in go
 
Functions
FunctionsFunctions
Functions
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Presention programming
Presention programmingPresention programming
Presention programming
 
The Ring programming language version 1.8 book - Part 94 of 202
The Ring programming language version 1.8 book - Part 94 of 202The Ring programming language version 1.8 book - Part 94 of 202
The Ring programming language version 1.8 book - Part 94 of 202
 
Lex (lexical analyzer)
Lex (lexical analyzer)Lex (lexical analyzer)
Lex (lexical analyzer)
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib3 1. preprocessor, math, stdlib
3 1. preprocessor, math, stdlib
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Python basics
Python basicsPython basics
Python basics
 

Más de Mohammed El Rafie Tarabay (9)

التقنيات المستخدمة لتطوير المكتبات
التقنيات المستخدمة لتطوير المكتباتالتقنيات المستخدمة لتطوير المكتبات
التقنيات المستخدمة لتطوير المكتبات
 
IBM Business Automation Workflow
IBM Business Automation WorkflowIBM Business Automation Workflow
IBM Business Automation Workflow
 
Django crush course
Django crush course Django crush course
Django crush course
 
ITIL
ITILITIL
ITIL
 
React native
React nativeReact native
React native
 
IBM Business Process Management 8.5
IBM Business Process Management 8.5IBM Business Process Management 8.5
IBM Business Process Management 8.5
 
Bootstarp 3
Bootstarp 3Bootstarp 3
Bootstarp 3
 
IBM File Net P8
IBM File Net P8IBM File Net P8
IBM File Net P8
 
Django - sql alchemy - jquery
Django - sql alchemy - jqueryDjango - sql alchemy - jquery
Django - sql alchemy - jquery
 

Último

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 

Último (20)

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 

Python crush course

  • 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.
  • 8. Tuple (Read-Only List) thisTuple=("apple","banana","cherry","orange","kiwi","melon“) print(thisTuple[1]) print(thisTuple[-1]) print(thisTuple[2:5]) print(thisTuple[:4]) print(thisTuple[2:]) thisTuple[1]="blackcurrant“ print(len(thisTuple)) forxin thisTuple: print(x) if"apple"in thisTuple: print("Yes,'apple'isinthefruitstuple") thisTuple.append("orange") thisTuple.insert(1,"orange") thisTuple.remove("banana") thisTuple.pop() del thisTuple[0] mylist=thislist.copy() tuple3 = tuple1 + tuple2 Red means not valid
  • 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))
  • 17. Python Iterators class MyNumbers: def __iter__(self): self.a = 0 return self def __next__(self): self.a += 1 if self.a >100: raise StopIteration else: return self.a myclass = MyNumbers() myiter = iter(myclass) print(next(myiter)) print(next(myiter))
  • 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()
  • 21. Python User Input username = input("Enter username:") print("Username is: " + username)
  • 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")
  • 23. Python Requests Module import requests x = requests.get('https://w3schools.com/python/demopage.htm') print(x.text)
  • 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
  • 26. Database Table Here is a Sample DB table with name “Customers”
  • 27. CREATE TABLE • CREATE TABLE table_name ( column1 datatype, column2 datatype, column3 datatype, .... ); • CREATE TABLE Persons ( PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255), City varchar(255) );
  • 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;
  • 31. Operators in The WHERE Clause
  • 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;
  • 43. Python MySQL Handel DB from Python
  • 44. Python Mysql Connection import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword" ) mycursor = mydb.cursor() mycursor.execute("CREATE DATABASE mydatabase") mycursor.execute("SHOW DATABASES") for x in mycursor: print(x) mycursor.execute("CREATE TABLE mydatabase .customers (name VARCHAR(255), address VARCHAR(255))")
  • 45. Mysql Insert import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", passwd="yourpassword", database="mydatabase" ) mycursor = mydb.cursor() sql = "INSERT INTO customers (name, address) VALUES (%s, %s)" val = ("John", "Highway 21") mycursor.execute(sql, val) mydb.commit() print(mycursor.rowcount, "record inserted.")
  • 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")