0% found this document useful (0 votes)
132 views

Python Basic

Python is a programming language that uses indentation to delimit code blocks rather than brackets. It supports features like comments, variables, built-in data types, conditional statements, functions, modules and packages. Variables can be assigned letters, numbers or other variables. Python supports strings, integers, floats, booleans and lists. Strings can be indexed, sliced and manipulated using methods. Lists are ordered collections of items that can be accessed by index and support methods like append, insert, remove and pop. Python also supports conditional statements, loops, functions and modules.

Uploaded by

Aman Udyog
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
132 views

Python Basic

Python is a programming language that uses indentation to delimit code blocks rather than brackets. It supports features like comments, variables, built-in data types, conditional statements, functions, modules and packages. Variables can be assigned letters, numbers or other variables. Python supports strings, integers, floats, booleans and lists. Strings can be indexed, sliced and manipulated using methods. Lists are ordered collections of items that can be accessed by index and support methods like append, insert, remove and pop. Python also supports conditional statements, loops, functions and modules.

Uploaded by

Aman Udyog
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

"""

#refer pdf also


What is python
"""

print("hello world")
print()

# python indentation
if 5 > 2:
print("Five is greater than two!")
print()

# this is Single line comment

"""
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:

so finally its a multiline string


"""

"""
#refer pdf also
built in datatypes
"""
# variables

x = 5
y = "john"

print(x)
print(y)
print()

# get type of variables

print(type(x))
print(type(y))
print()

# typecast variable using appropriate typecast function

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)

# variables name is case sensitive, this will create two variables


a = 4
A = 3
print("a =",a,"A =",A)

"""
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:

A variable name must start with a letter or the underscore


character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three
different variables)
"""

# many values to multiple variables


x, y, z = 1, 2, 3
print(x, y, z)
print()

# 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.

'hello' is the same as "hello".

You can display a string literal with the print() function:


'''
print("hello")
print('hello')
print()

# assign string to variable

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()

# string are arrays

"""
Like many other popular programming languages, strings in Python
are arrays of bytes representing unicode characters.

However, Python does not have a character data type, a single


character is simply a string with a length of 1.

Square brackets can be used to access elements of the string.


"""
a = "hello! world"
# 012345678901
print(a[1]) #indexing starts from position 0
print()

# looping thru string


for x in a:
print(x)
print()

# string length
print("Length of string a is", len(a))
print()

# check string
print("hello" in a)
print()

# check using if statement

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()

# check if not using if statement


if 'expensive' not in txt:
print("No string 'expensive' is not present in string txt")
else:
print("Yes string 'expensive' is not present in string txt")
print()

# python slicing string

b = "hello, world!"
print(b[2:5])
print()

# Slice from the start


print(b[:5])
print()

# slice to the end


print(b[7:])
print()

# negative indexing
print(b[-5:-2])
print()

#string modification

a = " Hello, World! "


print("String:", a)
print("Uppercase:", a.upper())
print("Lowercase:", a.lower())
print("Remove whitespace:", a.strip())
print("Replacing:", a.replace("H", "J"))
print("Spliting: ", a.split(","))
print()

#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
(+)

# single argument formating using format() function

age = 20
txt = "my name is john and i'm {} years old"
print(txt.format(age))

# multiple argument formating using format() function


quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} fzr {} dollars."
print(myorder.format(quantity, itemno, price))

# formating with the help of placeholder


myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))
print()

# Escape characters

"""
#refer pdf also
Escape characters
"""

"""
To insert characters that are illegal in a string, use an escape
character.

An escape character is a backslash \ followed by the character you


want to insert.

An example of an illegal character is a double quote inside a


string that is surrounded by double quotes:"""

txt = "We are the so-called \"Vikings\" from the north."


print(txt)
print()

#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.

Lists are created using square brackets:


"""

thislist = ["apple", "banana", "cherry"]


print(thislist)

#list items (ordered)


print(thislist[0])

#items changeable and allows duplicates too

thislist = ["apple", "banana", "cherry", "apple", "cherry"]


print(thislist)

#list length
print("length of list is",len(thislist))

#list can contain different datatype


list1 = ["abc", 34, True, 40, "male"]
print(list1)
print(type(list1))

#list constructor
thislist = list(("apple", "banana", "cherry")) # note the double
round-brackets
print(thislist)
print()

# accessing list items


thislist = ["apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango"]
print(thislist[1])

# 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])

#checking if item exists in the list or not


if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
print()

#changing item value


thislist[1] = "blackcurrant"
print(thislist)

#changing the range of item values


thislist = ["apple", "banana", "cherry", "orange", "kiwi",
"mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)
print()

# replacing one item with two items

thislist = ["apple", "banana", "cherry"]


thislist[1:2] = ["blackcurrant", "watermelon"]
print(thislist)
#Note: The length of the list will change when the number of items
inserted does not match the number of items replaced.

thislist = ["apple", "banana", "cherry"]


thislist[1:3] = ["watermelon"]
print(thislist)

#inserting items
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)

#appending list or extending list


thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
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()

# The remove() method removes the specified item.


thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)

#The pop() method removes the specified index.

thislist = ["apple", "banana", "cherry"]


thislist.pop(1)
print(thislist)

#If you do not specify the index, the pop() method removes the
last item.
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)

#The del keyword also removes the specified index


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

#The del keyword can also delete the list completely.


thislist = ["apple", "banana", "cherry"]
del thislist

#clear list content


thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
print()

#loop with list item


thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
print()

#loop thru list index


thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(i,thislist[i])
print()

#while with list


thislist = ["apple", "banana", "cherry"]
i = 0
while i < len(thislist):
print(i,thislist[i])
i = i + 1
print()

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.'''

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]


newlist = []

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:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

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.'''

# Only accept items that are not "apple":


newlist = [x for x in fruits if x != "apple"]
print(newlist)

#The condition if x != "apple" will return True for all elements


other than "apple", making the new list contain all fruits except
"apple".

#The condition is optional and can be omitted:

#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)

#Same example, but with a condition:

#Accept only numbers lower than 5:


newlist = [x for x in range(10) if x < 5]
print(newlist)
print()

'''Expression

The expression is the current item in the iteration, but it is


also the outcome, which you can manipulate before it ends up like
a list item in the new list:'''

#Set the values in the new list to upper case:


newlist = [x.upper() for x in fruits]
print(newlist)
#You can set the outcome to whatever you like:

#Set all values in the new list to 'hello':


newlist = ['hello' for x in fruits]
print(newlist)
#The expression can also contain conditions, not like a filter,
but as a way to manipulate the outcome:

#Return "orange" instead of "banana":


newlist = [x if x != "banana" else "orange" for x in fruits]
print(newlist)
print()
'''The expression in the example above says:

Return the item if is not banana, if it is banana return orange'''

# sorting in list

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]


thislist.sort()
print(thislist)
thislist.sort(reverse = True)
print(thislist)
print()

thislist = [100, 50, 65, 82, 23]


thislist.sort()
print(thislist)
thislist.sort(reverse = True)
print(thislist)
print()

'''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)

thislist = [100, 50, 65, 82, 23]


thislist.sort(key = myfunc)
print(thislist)
print()

#case insensitive sort


#By default the sort() method is case sensitive, resulting in all
capital letters being sorted before lower case letters
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort()
print(thislist)

#Luckily we can use built-in functions as key functions when


sorting a list.

#So if you want a case-insensitive sort function, use str.lower as


a key function:
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.sort(key = str.lower)
print(thislist)

#reverse order
thislist = ["banana", "Orange", "Kiwi", "cherry"]
thislist.reverse()
print(thislist)
print()

#list copy
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)

thislist = ["apple", "banana", "cherry"]


mylist = list(thislist)
print(mylist)
print()
"""if else"""

print("if Else statement in python")


print()

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"""

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
print()

#looping thru string


for x in "banana":
print(x)

# 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()

#else will not executed if loop is stoped by break statement


for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
print()

#nested loop

adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]

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")

#multiple arguments in function


def myfun(greeting, fname):
print("good", greeting, fname)
myfun("Morning", "Mihir")

# arbitary arguments in function


def myfun(*args):
print("good", args[0], args[1])

myfun("Morning", "Mihir")

#keyword argument in function


def myfun(greeting, fname):
print("good", greeting, fname)

myfun(fname = "Mihir", greeting = "Evening")

#arbitary argument, **kwargs


def myfun(**kargs):
print("good", kargs["greeting"], kargs["fname"])

myfun(greeting = "Evening", fname = "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)

fruits = ["apple", "banana", "cherry"]

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

print("\n\nRecursion Example Results")


tri_recursion(6)

You might also like