Python Notes
Python Notes
comments
- explain code
- make code readable
- to prevent execution of code when needed
starts with # - python ignores lines starting with #
comment can be placed at the end of code line – code line will be ignored
# can be placed before any line of code – it will be ignored
multiline code – no special syntax
# before every line
can use multiline strings as comments – python ignores string literals when no variable is assigned
triple quote – multiline strings – can be used as multiline comments
variables
used for storing data values
no command in python
created by assigning values – x = anything
no need to declare type & type can even be changed later if needed
casting – can declare type if needed x = str() / int () / float()
can find out data type of variable using – type ()
string variable – single or double quotes / x = “world”
variables are case sensitive
variable names
rules:
- start with letters or underscore
- can’t start with numbers
- only alphanumeric characters and underscore are allowed
- are case sensitive
multi word variable names – techniques used
- camel case – except first word, all words start with capital letters – myVariableName
- pascal case – all words start with capital letters – MyVariableName
- snake case – all words connected with underscores – my_variable_name
multiple assigning
assign values to multiple variables in one line – number of variables and values should be same
x,y,z = “A”,”B”,”C”
one value to multiple variables – x = y = z = “A”
unpack a collection(list, tuple, etc...) - fruits = [“A”,”B”,”C”] – x,y,z = fruits
output variables
print() - is used to output variables – print(x)
multiple variables output – two way – using comma and +
print(x,y,z) – space automatic – can be used with different data types – best way for multiple
variables
print(x+y+z) – space automatic – only used with same data types – numbers – works as
mathematical operator
global variable – can be used both inside and outside the function
local variable – can be created and used only inside a function
create and change global variable inside a function by using “global” – global x =
set data type – add () to all types – except range, bool, bytes, bytearray and memoryview
numbers:
int – whole numbers, integers – positive and negative (unlimited length, without decimals)
float – negative and positive numbers – one or more decimals and scientific numbers with e in them
(x = 12e4)
complex – with j beside integer
type conversions using – int(), float(), complex() - can convert one type into another
complex numbers cannot be converted into other types