Python QuickNotes help you learn python.
Follow the quick notes to learn python programming.
Note:
- Variable names are case sensitive i.e both var and VAR are different variables.
- Variable names must start with a letter or an underscore. Eg: _var
- Variable names can contain a number in between but not at the start. Eg: var1
- Variable names must not use spaces in between
Code:
x = 10 # int
z = 5.5 # float
firstName = "Alexa" # str
is_female = True # bool
Code:
name, age, weight, is_male = ("John", 22, 65.4, True)
Description:
We can assign multiple variables at a single time. The above code is equivalent to -
name = "John"
age = 22
weight = 65.4
is_male = True
Code:
add = x + y # addition
sub = x - y # substraction
div = x / y # division
mod = x % y # modulus
expo = x ** y # exponent
Note:
- All classes and metaclasses including
object
are subclasses ofobject
. - All classes and metaclasses including
type
are instances oftype
. - All objects including
object
are instances ofobject
.
Code:
issubclass(type, object) # True
issubclass(object, object) # True
issubclass(object, type) # False
isinstance(object, type) # True
isinstance(type, type) # True
isinstance(type, object) # True
isinstance(object, object) # True
Code:
x = str(x) # convert to string
y = int(y) # convert to integer
z = float(y) # convert to float
Code:
name = "Alexa"
age = 18
print("Hello, My name is " + name + " and I am " + str(age) + " years old.")
Code:
name, age = ("Alexa", 18)
print("My name is {name} and I am {age} years old.".format(name=name, age=age))
Description:
We can position the arguments inside the { }
and then call the .format()
method.
Code:
print(f"My name is {name} and I am {age} years old.")
Code:
s = "hello world"
Operations: s.capitalize()
s.upper()
s.lower()
s.swapcase()
len(s)
s.replace(old, new, count)
s.count(substring)
s.startswith(substring)
s.endswith(string)
s.split()
s.find(substring)
s.isalnum()
s.isalpha()
s.isnumeric()
Note:
- List is a collection which is ordered and changeable.
- Allow duplicate members.
Code:
fruits = ["Apples", "Oranges", "Mangos", "Pears"]
or
fruits = list(("Apples", "Oranges", "Mangos", "Pears"))
Operations: fruits.append(element)
fruits.remove(element)
fruits.insert(position, element)
fruits.pop(position)
fruits.reverse()
fruits.sort()
fruits.sort(reverse=True)
Note:
- Tuple is a collection which is ordered and unchangeable.
- Allow duplicate members.
Code:
fruits = ("Apples",)
Description: If you are assigning a single value inside the tuple please use ,
otherwise without ,
the type(fruits)
return <class 'str'>
instead of <class 'tuple'>
Note:
- A set is a collection of unordered and unindexed.
- No duplicate members.
Code:
fruits = {"Apples", "Oranges", "Mangos"}
Operations: fruits.add(element)
fruits.remove(element)
fruits.clear()
fruits.update(element)
fruits.pop()
Note:
- A dictionary is a collection which is unordered, changeable and indexed.
- No duplicate members.
Code:
person = {
'first_name': "John",
'last_name': "Nash",
'age' = 22
}
Operations: person.get(key)
person.items()
person.keys()
person.values()
person.pop(key)
person.clear()
person.copy()
len(person)
Code:
x1 = {'first_name' : 'John', 'last_name' : 'Doe'}
y1 = {'age' : 31, 'gender' : 'male'}
merge_x1_y1_dict = {**x1, **y1}
Description: We can merge two or more dictionaries using **
operator as shown in above code. In case if the key finds similar in two or more dictionaries, then the value of the key will be updated with the dictionay defined last.
Code:
getSum = lambda num1, num2: num1 + num2
print(getSum(10, 3))
Description: A Lambda function ( lambda <arguments> : <expression>
) can take as many number of arguments, but can only have one expression.
Code:
def about(name, age, country):
print(f"My name is {name} and I am {age} years old. I live in {country}.")
about_data = ["John Doe", 22, "USA"]
about(*about_data)
Description: In case your data is in a list or tuple then you can fetch it using *
operator i.e. about(*about_data)
instead of typing about(about_data[0], about_data[1], about_data[2])
where about_data
is the variable assigned to your list.
Code:
def about(name, age, country):
print(f"My name is {name} and I am {age} years old. I live in {country}")
about_data = {'name': "John Doe", 'age': 22, 'country': "USA"}
about(**about_data)
Description: In case you have to parse your data (inside a dictionay) then you just have to use **
operator in place of single *
operator. Note that in case of using dictionay the arguments must match exactly with the dictionay keys.
Code:
if (condition):
statement
else:
statement
Operators: ==
!=
>
<
>=
<==
Operators: and
or
not
Code:
name = "Alexa"
first_name = ["John", "Harry", "Alexa"]
if name in first_name:
print(f'{name} in first_name.')
elif name not in first_name:
print(f'{name} not in first_name.')
Operators: in
not in
Operators: is
is not
Note:
- A loop is used for iterating over a set of statements.
Code:
first_name = ["Alexa", "John", "Harry"]
for name in first_name:
print(f'{name}')
Code:
first_name = ["Alexa", "John", "Harry"]
for name in first_name:
if name == "John":
break
print(f'{name}')
Code:
first_name = ["Alexa", "John", "Harry"]
for name in first_name:
if name == "John":
continue
print(f'{name}')
Code:
for i in range(0, 10):
print(f'{i}')
Code:
count = 0
while count <= 10:
print(f'{count}')
count += 1 # count = count + 1