Академический Документы
Профессиональный Документы
Культура Документы
Beginner to Advance
PYTHON
Python is an interpreted, object-oriented, high-level programming
components together
PYTHON File Handling
The key function for working with files in Python is
the open() function.
The open() function takes two parameters; filename, and mode
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file
does not exist
"a" - Append - Opens a file for appending, creates the file if it does
not exist
"w" - Write - Opens a file for writing, creates the file if it does not
exist
"x" - Create - Creates the specified file, returns an error if the file
exists
Syntax
f = open("demofile.txt")
PYTHON MYSQL
Python can be used in database applications.
One of the most popular databases is MySQL.
demo_mysql_Test.py:
import mysql.connector
Create Connection
Start by creating a connection to the database.
Use the username and password from your MySQL database:
demo_mysql_connection.py:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
print(mydb)
PYTHON Comments
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.
Creating Comments
Comments starts with a #, and Python will ignore them:
Example
#This is a comment
print("Hello, World!")
PYTHON Variables
Variables are containers for storing data values.
Unlike other programming languages, Python has no command for
declaring a variable.
A variable is created the moment you first assign a value to it
Example
x=5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type and can
even change type after they have been set.
PYTHON variable Names
Variable names are case-sensitive (age, Age and AGE are three
different variables)
PYTHON Data Types
Variables can store data of different types, and different types can do
different things.
Python has the following data types built-in by default, in these
categories
Text Type: str
Numeric Types: int, float, complex
❑ int
❑ float
❑ complex
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
PYTHON Casting
There may be times when you want to specify a type on to a
variable. This can be done with casting. Python is an object-
orientated language, and as such it uses classes to define data
types, including its primitive types.
Floats
x = float(1) # x will be 1.0
y = float(2.8) # y will be 2.8
z = float("3") # z will be 3.0
String
x = str("s1") # x will be 's1'
y = str(2) # y will be '2'
z = str(3.0) # z will be '3.0'