Python Fundamentals
Deepam Makwana
4 min read
This article contains gists for learning the Python Programming Fundamentals. I believe that you understand more from coding than reading about coding. Below are the most used practical codes in Python.
Output
# Using Print
print("Hello World!")
print("Hello", "World!")
print("Hello" + " World!")
print("hello" * 3)
try:
print("hello" + 3) # This will cause an error
except TypeError:
print("Error: cannot concatenate 'str' and 'int'")
print(type("Hello"))
print("Hello", "There", "World", sep=" - ")
print("Hello", "World", end="\n\n\n")
print("Hello", "World", "Hi", "There")
# Using F-strings
name = "Deepam"
print(f"Hello, {name}")
Variables & Primitives
# Initializing variables
x = 5
y = "Hello World"
truth_value = True
# Primitives: bool, int, float, complex, string
boolean_true = True
boolean_false = False
integer_variable = 5
negative_integer = -5
float_variable = 5.5
negative_float = -5.5
# Changing the datatype of a variable
integer_variable = 6.66
complex_variable = 6 + 4j
string_variable = "Hello World!"
print(boolean_true, boolean_false, integer_variable, negative_integer, float_variable, negative_float, complex_variable, string_variable)
# Type conversion
print(int(negative_float), complex(float_variable), str(float_variable))
# More on bool
print(bool(""), bool(False), bool([]), bool(0))
Input
name = input("Enter your name: ")
print(f"Hello, {name}")
try:
x = input("Enter number to add with 5: ")
print(int(x) + 5)
except ValueError:
print("Error: Input was not a number")
x = int(input("Enter number to add with 5 part 2: "))
print(x + 5)
Operators
# Arithmetic Operators & Assignment Operators
print(5 + 3, 5 - 3, 5 * 3, 5 / 3, 5 % 3, 5 ** 3, 5 // 3)
x = 5
x += 5
print(x)
x **= 2
print(x)
# Comparison, Logical, Identity, Membership, Bitwise operators
print(5 == 5, 5 != 3, 5 > 3, 5 >= 3, 5 < 3, 5 <= 3)
print(True and False, True or False, not True)
print(5 is 5, 5 is not 3)
print(5 in [1, 2, 3, 5], 5 not in [1, 2, 3])
print(5 & 3, 5 | 3, 5 ^ 3, ~5, 5 << 1, 5 >> 1)
Conditionals
x = 15
if x > 18:
print("Eligible to vote")
elif x == 18:
print("Just became eligible to vote")
elif x <= 5:
print("You're a child")
else:
print("Not Eligible")
Loops
# print 1 to 10
# using while loop
x = 1
while x <= 10:
print(x)
x += 1
# using for loop
for i in range(1, 11):
print(i)
Functions
# Parameter in definition, argument in function call
# No args + No return value
def print_hello():
print("Hello")
print_hello()
# args + no return value
def print_hello_with_name(name):
print("Hello", name)
print_hello_with_name("Deepam")
# Args + return value
def add_5(num):
return 5 + num
print(add_5(15))
# Args + return value
def pythagoras(x, y):
return (x**2 + y**2) ** 0.5
z = pythagoras(3, 4)
print(z)
List
l = [1, 2, 3, 4, 5]
# for loop
for i in l:
print(i)
# append
l.append(55)
print(l)
# pop & remove
print(l.pop())
l.remove(4)
print(l)
print(l.pop(1))
print(l)
# insert
l.insert(2, 55)
print(l)
# copy & clear
x = l.copy()
x.clear()
print(x)
# concatenate
x = [5, 3, 2]
print(x + l)
# count, index
print(l.count(5), (x + l).count(5))
print(l.index(5))
# sort & reverse
print(l, sorted(l))
x.sort()
print(x)
l.reverse()
print(l)
Tuple
t = (1, 2, 3, 4, 5, 5, 5)
# for loop
for i in t:
print(i)
# immutable
# count
print(t.count(5))
# index
print(t.index(5))
Set
s = {1, 2, 3, 4, 5, 55, 5}
print(s)
# for loop
for i in s:
print(i)
# add, remove, clear, discard
s.add(33)
print(s)
s.remove(4)
print(s)
s.clear()
print(s)
s = {1, 2, 3, 4, 5, 55}
s1 = {2, 3, 4}
print(s.difference(s1))
s.discard(55) # Doesn't raise error if element doesn't exist
print(s)
# union, intersection
print(s.intersection(s1))
print(s.union(s1))
# membership and pop
print(5 in s)
s.pop() # Takes no arguments
print(s)
Dictionary
d = {"a": 1, "b": 2, "c": 3}
print(d)
# Iterating
for key in d:
print(key, d[key])
for key, value in d.items():
print(key, value)
# add
d["d"] = 4
print(d)
# remove
del d["d"]
print(d)
# pop
print(d.pop("b", None)) # Remove key "b" if it exists, do nothing if it doesn't
print(d)
# membership
print("a" in d)
# clear
d.clear()
print(d)
1
Subscribe to my newsletter
Read articles from Deepam Makwana directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by