Python – Fundamental

Multi Line Comments :

"""
This is a comment
written in
more than just one line
"""

Variables

Casting :

x = str(3)    # x will be '3'
y = int(3)    # y will be 3
z = float(3)  # z will be 3.0


Get the Type :

x = 5
y = "John"
print(type(x)) # <class 'int'>
print(type(y)) # <class 'str'>


Output Variables :

x = "awesome"
print("Python is " + x)
# Python is awesome

x = "Python is "
y = "awesome"
z =  x + y
print(z)
# Python is awesome

x = 5
y = "John"
print(x + y)
# ERROR

Multiline Strings :

a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

OR

a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)

Check String :

txt = "The best things in life are free!"
if "free" in txt:
  print("Yes, 'free' is present.")
  # Yes, 'free' is present.

txt = "The best things in life are free!"
if "expensive" not in txt:
  print("Yes, 'expensive' is NOT present.")

Slicing Strings :

b = "Hello, World!"
print(b[2:5])
# llo

Slice From the Start :

b = "Hello, World!"
print(b[:5])
# Hello

Slice To the End :

b = "Hello, World!"
print(b[2:])
# llo, World!

Modify Strings :

Upper Case :

a = "Hello, World!"
print(a.upper())

Lower Case :

a = "Hello, World!"
print(a.lower())

Remove Whitespace :

a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

Replace String :

a = "Hello, World!"
print(a.replace("H", "J"))

Split String : 

a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']


Format String :

age = 36
txt = "My name is John, and I am {}".format(age)
print(txt)

Escape Character :

txt = "We are the so-called \"Vikings\" from the north."
print(txt)
# We are the so-called "Vikings" from the north.

\'	Single Quote	
\\	Backslash	
\n	New Line	
\r	Carriage Return	
\t	Tab

String Methods :

https://www.w3schools.com/python/python_strings_methods.asp

List Items :

first list item :

thislist = ["apple", "banana", "cherry", "pie"]
print(thislist[0])
# apple

last list item :

thislist = ["apple", "banana", "cherry", "pie"]
print(thislist[-1])
# pie

list items 1-3 :

thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[0:2])
# ['apple', 'banana', 'cherry']

Leave a Reply

Your email address will not be published. Required fields are marked *