Python Basic
Python Basic
print("hello world")
print()
# python indentation
if 5 > 2:
print("Five is greater than two!")
print()
"""
Since Python will ignore string literals that are not assigned to
a variable,
you can add a multiline string (triple quotes) in your code,
and place your comment inside it:
"""
#refer pdf also
built in datatypes
"""
# variables
x = 5
y = "john"
print(x)
print(y)
print()
print(type(x))
print(type(y))
print()
x = str(3)
print(type(x))
x = int(3)
print(type(x))
x = float(3)
print(type(x))
print()
# string can be declared using either '' or "" quotes
# and you know what is amazing thing? both are the same
x = "john"
print(x)
x = 'john'
print(x)
"""
Variable Names
A variable can have a short name (like x and y) or a more
descriptive name (age, carname, total_volume). Rules for Python
variables:
# python numbers
x = 1 # int
y = 2.8 # float
z = 1+2j # complex
print(type(x))
print(type(y))
print(type(z))
print()
# floats
x = 35e3
y = 12E4
z = -87.7e100
print(x, y, z)
print()
# complex
x = 3+5j
y = 5j
z = -5j
print(x, y, z)
print()
#random numbers
import random
print(random.randrange(0, 10))
print()
# Strings
"""
#refer pdf also
python string methods
"""
'''
Strings in python are surrounded by either single quotation marks,
or double quotation marks.
a = "hello"
print(a)
print()
# multiline string
a = """
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
"""
print(a)
print()
a = '''
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
'''
print(a)
print()
"""
Like many other popular programming languages, strings in Python
are arrays of bytes representing unicode characters.
# string length
print("Length of string a is", len(a))
print()
# check string
print("hello" in a)
print()
if 'hello' in a:
print("Yes string 'hello' is present in string a")
else:
print("No string 'hello is not present in string a'")
print()
# check if not
txt = "the best things in life are free"
print("expensive" not in txt)
print()
b = "hello, world!"
print(b[2:5])
print()
# negative indexing
print(b[-5:-2])
print()
#string modification
#String concatenation
a = "hello"
b = "World"
c = a + b
print(c)
c = a + " " + b
print(c)
print()
# String format
"""
#refer pdf also
python string formating
"""
# age = 20
# strng="My name is john and my age is " + age
# we can't combine string and number using concatenation operator
(+)
age = 20
txt = "my name is john and i'm {} years old"
print(txt.format(age))
# Escape characters
"""
#refer pdf also
Escape characters
"""
"""
To insert characters that are illegal in a string, use an escape
character.
#python booleans
print(10 > 9)
print(10 == 9)
print(10 < 9)
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
print(bool("Hello"))
print(bool(15))
print()
x = "Hello"
y = 15
print(bool(x))
print(bool(y))
print()
print(bool("abc"))
print(bool(123))
print(bool(["apple", "cherry", "banana"]))
print()
print(bool(False))
print(bool(None))
print(bool(0))
print(bool(""))
print(bool(()))
print(bool([]))
print(bool({}))
print()
# object checking
x = 200
print(isinstance(x, int))
print()
# python lists
"""
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store
collections of data, the other 3 are Tuple, Set, and Dictionary,
all with different qualities and usage.
#list length
print("length of list is",len(thislist))
#list constructor
thislist = list(("apple", "banana", "cherry")) # note the double
round-brackets
print(thislist)
print()
# neg indexing
print(thislist[-1])
#range of indexing
print(thislist[2:5])
# Note: The search will start at index 2 (included) and end at
index 5 (not included).
# Remember that the first item has index 0.
print(thislist[2:])
print(thislist[-4:-1])
#inserting items
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)
#The extend() method does not have to append lists, you can add
any iterable object (tuples, sets, dictionaries etc.).
thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)
print()
#If you do not specify the index, the pop() method removes the
last item.
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
print("list comprehention")
# list comprehention
thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]
print()
'''List comprehension offers a shorter syntax when you want to
create a new list based on the values of an existing list.'''
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
#With list comprehension you can do all that with only one line of
code:
print(newlist)
'''The Syntax
newlist = [expression for item in iterable if condition == True]
The return value is a new list, leaving the old list unchanged.
Condition
The condition is like a filter that only accepts the items that
valuate to True.'''
#With no if statement:
newlist = [x for x in fruits]
print(newlist)
print()
'''Iterable
The iterable can be any iterable object, like a list, tuple, set
etc.'''
#You can use the range() function to create an iterable:
newlist = [x for x in range(10)]
print(newlist)
'''Expression
# sorting in list
'''custom sort
You can also customize your own function by using the keyword
argument key = function.
The function will return a number that will be used to sort the
list (the lowest number first):
'''
def myfunc(n):
return abs(n - 50)
#reverse order
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.reverse()
print(thislist)
print()
#list copy
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
a = 33
b = 200
if b>a:
print("b is greater than a")
# else if
a = 33
b = 33
if b>a:
print("b is greater")
elif a>b:
print("a is greater")
else:
print("both are equal")
# shorthand if
a, b = 10, 5
if a>b: print("a is greater")
#shorthand if else
print("a is greater") if a>b else print("b is greater")
a = 330
b = 330
print("a>b") if a > b else print("a=b") if a == b else
print("a<b")
# pass statement
a=33
b=200
if b>a:
pass
print()
"""while loops"""
print("While loop")
i = 0
while i<6:
print(i)
i+=1
print()
# break statement
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
print()
#continue statement
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
print()
"""For loops"""
# break statement
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
print()
#continue statement
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
print()
#range function
for x in range(2,6):
print(x)
print()
#else if for loop
for x in range(6):
print(x)
else:
print("Finally finished!")
print()
#nested loop
for x in adj:
for y in fruits:
print(x, y)
#pass statement
for x in [0, 1, 2]:
pass
print()
"""funtion in python"""
def myfun():
print("hello from funtion")
myfun()
# arguement in function
def myfun(fname):
print("hello ", fname)
myfun("Mihir")
myfun("Morning", "Mihir")
#default arguments
def my_function(country = "India"):
print("I am from " + country)
my_function("Sweden")
my_function()
#list as an arguments
def my_function(food):
for x in food:
print(x)
my_function(fruits)
print()
#return value
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
#pass statement
def myfun():
pass
#recursion
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result