Python syntax and fundamentals
Python Syntax:
Python syntax can be written directly in the Visual Studio Code. For example, a print statement or any line of code can be written directly in the program. In contrast, in other programming language such as Java/c++, print and other lines of code typically need to be enclosed within a main() function.
Python Indentation:
Python Indentation is crucial in the language, as it defines the structure of the code. It signifies the spaces at the begining of code lines.
if i<5:
print i //program will execute successfully
if the indentation is missed, then the program will throw a syntax error.
if i<5:
print i //will throw an error
Python Comment line:
Comments in Python are used to annotate code for readability and explanation. They are ignored by the Python interpreter during execution.
Single line Comment - starts with # symbol -any text following # on the same line is considered as a comment, and is ignored by the interperter.
print("Hello World") #This will print the statement "Hello World"
Multiline comment - starts with triple quotes """ <code> """ - any text/line of code mentioned in the triple quotes """ """ is considered as the comment line, and this will be ignored by the interperter.
"""
if i<5:
print(i) //this entire if statement will be ignored if it's mentioned in the triple quotes.
"""
Python Variable:
Creating Variables:
A Python variable is created once you assign a value to it.
eg: i = 5 # i holds the integer value
j="Hello" #j holds the string value.
J="Hello" #uppercase J and lowercase j are different variable. J will not overwrite j
k=l="123" #k & l holds the string value.
a,b,c="Test","bat","cat" # a holds Test, b holds bat, c holds cat value
Rules for creating the variable:
Variable name starts with uppercase or lowercase letter.
Variable name cannot start with numbers but can contain numbers elsewhere.
Special characters are not allowed expect for the underscore(_), but it cannot be used at the beginning of the variable name.
Spaces are not allowed in variable names.
Casting:
Converting one datatype to another type.
i=5 #here i holds integer value
j=str(i) #here i value is converted to string
print(type(j)) #prints <class 'str'> indicating j now holds the string value
Type:
The type(), displays the datatype of a variable.
eg: i=5.5
print(type(i)) #displays <class 'float>, indicating i holds a float value
DataTypes:
Built-in data types:
Text type: str
Numeric type: int, float, complex
Sequence type: list, tuple, set
Mapping type: dictionary
Boolean type: bool
a="hello" # a holds string type
b=1 # b holds integer type
c=2.2 # c holds float type
li=[1,2,"helo", 3.4, 2+3j] #li holds list value
tu=(1,2,"helo", 3.4, 2+3j) #tu holds tuple value
se={1,2,"helo", 3.4, 2+3j} #se holds set value
di={a:1,b:2,c:"helo", d:3.4, e:2+3j} #di holds dictionary value with key-value pairs
boolean can hold True, False, 0, 1 value, True and 1 hold the same meaning, as do False and 0