Special Lecture
Python programming
Python Syntax
Where in other programming languages the indentation in code is for readability
Python Indentation only, the indentation in Python is very important.
in-code documentation. #This is a comment.
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.
print("Hello, World!") #This is a comment.
Python Variables Variables are containers for storing data values.
Python has no command for declaring a variable.
specify the data type
Get the Type type() Case-Sensitive
Python Data Types
Variable Names
•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.
Illegal variable names:
Legal variable names:
Assign Multiple Values
Unpack a Collection If you have a collection of values in a list, tuple etc. Python allows you to extract the
values into variables. This is called unpacking.
Output Variables print() function
In the print() function, you output multiple variables, separated by a comma:
You can also use the + operator to output multiple variables:
?
Global Variables Global variables can be used by everyone, both inside of functions and outside.
Python Numbers There are three numeric types in Python: int float complex
?
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:
x = 1 # int
y = 2.8 # float
z = 1j # complex
Random Number
Python does not have a random()
function to make a random number,
but Python has a built-in module
called random that can be used to
Specify a Variable Type make random numbers:
Specify a Variable Type Casting in python is therefore done using constructor functions:
Strings in python are surrounded by either single quotation marks, or double quotation
Strings marks. 'hello' is the same as "hello".
Quotes Inside Quotes
?
Assign String to a Variable
Looping Through a String
String Length To get the length of a string, use the len() function.
?
Check String
Check if NOT ?