0% found this document useful (0 votes)
2 views14 pages

Python Basics

The document provides an overview of Python data types, including integers, floats, strings, lists, and dictionaries, along with examples of their usage. It discusses variable assignment rules, dynamic typing, and basic operations like addition, subtraction, and string manipulation. Additionally, it covers string formatting techniques, including the use of the format method and f-strings for better readability and control over output formatting.

Uploaded by

tianable2020
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views14 pages

Python Basics

The document provides an overview of Python data types, including integers, floats, strings, lists, and dictionaries, along with examples of their usage. It discusses variable assignment rules, dynamic typing, and basic operations like addition, subtraction, and string manipulation. Additionally, it covers string formatting techniques, including the use of the format method and f-strings for better readability and control over output formatting.

Uploaded by

tianable2020
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

In [8]: #float

88/11

Out[8]: 8.0
Data Types
In [9]: #modulo operator gives the remainder of a divison
Common data types include:
14 % 3
int (for integer) Out[9]: 2
float
str (for string)
In [10]: #power
list 3**2
tuple
dict (for dictionary) Out[10]: 9
set
bool (for Boolean True/False) In [11]: #Order of operation pemdas
2+3*10+5

Out[11]: 37
In [50]: from [Link] import Image, display
display(Image(filename='C:/Users/Gayathri/Pictures/Screenshots/data_type.pn
g')) In [1]: (2+3)*(10+5)

Out[1]: 75

Variable Assignment
Variables must start be written in lowercase
Should not start with either a number or a symbol
Must not contain keywords
Spaces are not allowed and should be represented by an underscore

Python is dynamically typed which means the same variable name can be assigned to different data types
or values i.e reassignment

In [2]: a = 5
Numbers
In [3]: a
In [6]: #integer
Out[3]: 5
2+3

Out[6]: 5 In [4]: a = 20

In [5]: 20-17 In [5]: a


Out[5]: 3 Out[5]: 20

In [7]: 15*2 In [6]: a = a + a


Out[7]: 30
In [7]: a

Out[7]: 40
In [8]: a = "Snape" In [29]: mul

Out[29]: 12
In [9]: a

Out[9]: 'Snape' In [30]: div = 6

div /= 3 #div = div/3


In order to make find any error that may occur due to dynamic typing after displaying output , we can
restart the values in kernel to find the source of error or confusion. In [31]: div

Python lets you add, subtract, multiply and divide numbers with reassignment using +=, -=, *=, and Out[31]: 2.0
/= .

In [18]: my_profit = 10.0 Strings


item_sold = 4
Strings are ordered sequence of characters.
item_price = item_sold * my_profit
item_price

tot_price = print("The total item price is ",item_price) Creation of strings


The total item price is 40.0
In [51]: #Using single quotes with single word
'hello'
In [20]: type (my_profit)
Out[51]: 'hello'
Out[20]: float

In [53]: #Using single quotes with phrase


In [21]: type (item_sold) 'Hello there mister'
Out[21]: int Out[53]: 'Hello there mister'

In [22]: type (tot_price) In [55]: #Using double quotes


"I am still here"
Out[22]: NoneType
Out[55]: 'I am still here'
In [24]: #assignment operator
In [57]: #Using single quotes where apostrophe is also expected
add = 5 'This could've created an error'
add += 5 #add = add+5
File "<ipython-input-57-c1b31d0da56c>", line 2
In [25]: add 'This could've created an error'
^
Out[25]: 10 SyntaxError: invalid syntax

In [26]: sub = 10 In [58]: #Correct use with apostrophe


"This wouldn't create an error"
sub -= 2 #sub = sub-2
Out[58]: "This wouldn't create an error"

In [27]: sub

Out[27]: 8

In [28]: mul = 3

mul *= 4 #mul = mul*4


In [65]: my_string[-1] #to get the last letter of the string when the length is unkn
own
Printing a string
Out[65]: 'n'
In [59]: print("Rice cake")
print('Sandwich') In [66]: my_string[5]
print('Manhattan \nNew Pizza')
print('Manhattan \n New Pizza') Out[66]: 'e'
print('\n')
print('Side \t Story') In [68]: my_string[-3] #counted backwards in the string
Rice cake Out[68]: 'i'
Sandwich
Manhattan
New Pizza
Manhattan String Slicing
New Pizza
Slicing is used to get a subsection of a string

Side Story Syntax: [start:stop:step]


start indicates the start of the required index number
stop indicates go upto but not including the index number
step is used to show how many jumps are required
String functions
len function is used to specify the length of the string In [70]: cur_str = 'abcdefghijkl'
cur_str

In [60]: s = 'sequence' Out[70]: 'abcdefghijkl'


len(s)

Out[60]: 8 In [71]: cur_str[1:] #start from b go all the way to l

Out[71]: 'bcdefghijkl'
In [61]: st = 'sequence of char'
len(st)
In [73]: cur_str[:10] #from the start till j
Out[61]: 16
Out[73]: 'abcdefghij'

String Indexing In [74]: cur_str[:] #displays all the letters

Out[74]: 'abcdefghijkl'
Strings have an index value starting from 0.

Example : In [75]: cur_str[::] #displays all the letters


hello
Out[75]: 'abcdefghijkl'

01234
In [76]: cur_str[2:6] #go from c all the way till f with a default step size of 1

In [63]: my_string = 'Manifestation' Out[76]: 'cdef'


my_string

Out[63]: 'Manifestation' In [77]: cur_str[2:6:2] #go from c all the way till f with a step size of 12

Out[77]: 'ce'
In [64]: my_string[0]

Out[64]: 'M' In [79]: cur_str[:-1] #display everything except last letter

Out[79]: 'abcdefghijk'
In [80]: cur_str[-1:] #display only last letter In [91]: fun_str = 'I am an AI Engineer'
fun_str
Out[80]: 'l'
Out[91]: 'I am an AI Engineer'
In [81]: cur_str [::-1] #String reversal
In [92]: fun_str.upper()
Out[81]: 'lkjihgfedcba'
Out[92]: 'I AM AN AI ENGINEER'

In [93]: fun_str.lower()
String is immutable
Out[93]: 'i am an ai engineer'
The elements in a string cannot be changed or replaced once it is assigned

In [95]: fun_str.upper #since () is not included, it says what upper function is


In [82]: s = 'blue'
Out[95]: <function [Link]()>

In [83]: s[0] = 'c' #this will give an error


In [96]: fun_str.split() #splits based on whitespace by default
--------------------------------------------------------------------------
- Out[96]: ['I', 'am', 'an', 'AI', 'Engineer']
TypeError Traceback (most recent call las
t) In [98]: fun_str.split('i') #splits based on the letter i and it is case sensitive
<ipython-input-83-b7948e2279c5> in <module>
----> 1 s[0] = 'c' #this will give an error Out[98]: ['I am an AI Eng', 'neer']

TypeError: 'str' object does not support item assignment

In [84]: s_first = s[1:] #use slicing to change the element String Formatting
s_first

Out[84]: 'lue'
String formatting helps to inject the items into a string i.e interpolation instead of chaining them through a plus
In [86]: #String concatenation sign i.e. concatenation
s = 'c' + s_first
s There are three ways

Out[86]: 'clue' Using string formatting operator


Using .format() method
In [87]: disp = 'raise' Using string literals
disp + 'above'

Out[87]: 'raiseabove'

String formatting operator method


In [90]: #strings can be repeated by using the multiplication symbol
sleep = 'z' By using the modulo operator %
sleep*10

Out[90]: 'zzzzzzzzzz' In [3]: print("The world %s around me" %'revolves')

The world revolves around me

Basic built-in functions In [4]: print("I %s , I %s , I %s" %('sit','stand','speak'))

Built-in functions in python can be called by [Link](parameters) I sit , I stand , I speak


In [5]: a,b = 'less','more' In [13]: print("Earthquake magnitude was around %.3f richter" %6.2360)
print ("Talk %s,Work %s" %(a,b))
Earthquake magnitude was around 6.236 richter
Talk less,Work more
In [14]: print("Earthquake magnitude was around %27.1f richter" %6.2360)

Format conversion methods Earthquake magnitude was around 6.2 richter

%s and %r used to convert anything to a string. Similarly str() and repr() function is used for string
representation. Multiple formatting

%r is used to include the apostrophe and escape sequences in the output whereas %s shows the output
In [16]: print("Alex has %d barrels of %s weighing around %3.3f litres" %(2.2,'liquo
displaying the intended functionality of the apostrophe and escape sequences. r',5.78190))

In [6]: print("This is a work of %s" %'art') Alex has 2 barrels of liquor weighing around 5.782 litres
print("This is a work of %r" %'art')

This is a work of art


This is a work of 'art' Formatting with .format()
Syntax is "Stranger { } is { } granger" .format('danger','ranger')
In [7]: print("I hope they %s" %'live \t happy')
print("I hope they %r" %'live \t happy') There are three adavantages of using .format() method over %s method
I hope they live happy
I hope they 'live \t happy'
[Link] using index value

%s converts any integer, float to a string In [17]: print("The {2} {0} {1} ".format('brown','fox','quick'))
%d converts any number to a integer with a roundoff
The quick brown fox

In [9]: print("Samson weighs %s kg" %57.25)


print("Samson weighs %d kg" %57.25) [Link] based on assigned keywords

Samson weighs 57.25 kg


Samson weighs 57 kg In [18]: print("The {a} {f} only {m}".format(m='me',f='favours', a='algorithm'))
print("She {n} {o} glasses of {w}".format(o=5,w='water',n='needs'))

The algorithm favours only me


Padding and precision in floating point numbers She needs 5 glasses of water

%5.2f format is used.


`5` represents the minimum number of string that is to be used, if the required number is not present , then [Link] values can be reassigned instead of duplication
whitespace is taken upon

In [19]: print("She is %s and she needs a %s" %('penny','penny'))


`.2` represents how many digits are allowed after a decimal point print("She is {p} and she needs a {p}".format(p='penny'))

She is penny and she needs a penny


In [10]: print("Earthquake magnitude was around %5.2f richter" %6.2360)
She is penny and she needs a penny
Earthquake magnitude was around 6.24 richter

In [11]: print("Earthquake magnitude was around %1.0f richter" %6.2360) Alignment , padding and precision with float

Earthquake magnitude was around 6 richter


By default , letters are aligned to left and numbers are aligned to the right
In [24]: print("{0:11} | {1:8}".format('veggies','quantity'))
print("{0:11} | {1:8}".format('Onion',12)) r! is used for string representation
print("{0:11} | {1:8}".format('Tomato',10))

veggies | quantity In [33]: name ='Gary'


Onion | 12 print(f"My name is {name!r}" )
Tomato | 10
My name is 'Gary'

In [25]: #note the difference in field lengths in the output


print("{0:6} | {1:8}".format('veggies','quantity')) Floating point representation uses {value:{[Link]}}
print("{0:6} | {1:8}".format('Onion',12))
print("{0:6} | {1:8}".format('Tomato',10))

veggies | quantity In .format() method, 10.4f gives 10 characters to before decimal point (incase of less than 10 characters ,
Onion | 12 whitespace is added) and 4 digits after the decimal point (incase of more digits, it is rounded off whereas if it
Tomato | 10 is less, padding is done)

We can include < , ^ , > assignment for left , center, right alignment In f string literals ,the same 10.4f is represented by {10.6} Here 6 is the number of digits required in total and
there is no padding
In [27]: print("{0:<11} | {1:^8} | {2:>15}".format('veggies','quantity','price'))
print("{0:<11} | {1:^8} | {2:>15}".format('Onion',12,24)) In [35]: weight = 23.45678
print("{0:<11} | {1:^8} | {2:>15}".format('Tomato',10,30)) print("Her weight is around {0:10.4f}".format(23.45678))
print(f"Her weight is around {weight:{10.6}}")
veggies | quantity | price
Onion | 12 | 24 Her weight is around 23.4568
Tomato | 10 | 30 Her weight is around 23.4568

We can also include padding character along with alignment We can also use 10.4f method in f string literal

In [28]: print("{0:=<11} | {1:-^8} | {2:+>15}".format('veggies','quantity','price')) In [39]: # do not forget to remove the curly braces around width and precision while
print("{0:=<11} | {1:-^8} | {2:+>15}".format('Onion',12,24)) using .format method in a f-string literal
print("{0:=<11} | {1:-^8} | {2:+>15}".format('Tomato',10,30)) weight = 23.45
print(f"Her weight is around {weight:10.4f}")
veggies==== | quantity | ++++++++++price
Onion====== | ---12--- | +++++++++++++24 Her weight is around 23.4500
Tomato===== | ---10--- | +++++++++++++30

In [41]: weight = 23.45


print("Her weight is around {0:10.4f}".format(weight))
Using floating point operator print(f"Her weight is around {weight:{10.6}}")

In [30]: print("The value of pi is {0:5.2f}".format(3.14159)) Her weight is around 23.4500


Her weight is around 23.45
The value of pi is 3.14

Lists
Formatting using string literals

We can pass the variables instead of arguments in f string literals Creation of lists
Lists can have elements of same data type or different data [Link] are ordered sequence of characters.
In [31]: name = 'Gary'
print(f"My name is {name}" )
In [43]: my_list1 = [1,2,3]
My name is Gary
In [44]: my_list2 = ['Arithmetic',5,0.28] In [59]: # we can add two lists together

newest_list = my_list2 + my_list3


In [45]: my_list2
newest_list
Out[45]: ['Arithmetic', 5, 0.28]
Out[59]: ['Arithmetic', 5, 0.28, 'elbow', 'shire', 0, 9.45, 'sequel', 2356]

In [46]: my_list1

Out[46]: [1, 2, 3]
List duplication
In [47]: #length function is used to find the length of the list The * is used to duplicate elements in a list
len(my_list1)

Out[47]: 3 In [60]: newest_list * 2

Out[60]: ['Arithmetic',
5,
0.28,
Indexing and slicing of lists 'elbow',
'shire',
Index position starts from 0. 0,
9.45,
In [48]: my_list2[2] 'sequel',
2356,
Out[48]: 0.28 'Arithmetic',
5,
0.28,
In [50]: my_list3 = ['elbow','shire',0,9.45,'sequel',2356]
'elbow',
'shire',
my_list3[2:]
0,
Out[50]: [0, 9.45, 'sequel', 2356] 9.45,
'sequel',
2356]
In [51]: my_list3[:4]

Out[51]: ['elbow', 'shire', 0, 9.45]

Basic list functions


In [53]: my_list3[:-1]

Out[53]: ['elbow', 'shire', 0, 9.45, 'sequel']


Append

append() method to add an item to the end of the list permanently


Concatenation
In [61]: my_list1
Using '+' sign
Out[61]: [1, 2, 3]

In [57]: # we can add an element to a list


new_list = my_list1 + ['style'] In [62]: my_list1.append('added permanently')

In [58]: new_list In [63]: my_list1

Out[58]: [1, 2, 3, 'style'] Out[63]: [1, 2, 3, 'added permanently']


In [80]: newest_list
Pop
Out[80]: [2356, 'sequel', 9.45, 0, 'shire', 'elbow', 0.28, 5, 'Arithmetic']
pop() method to remove an element from the list.
By default, it removes the last element with index position -1 In [81]: newest_list.reverse() #gets reversed again

In [64]: my_list1.pop() In [82]: newest_list

Out[64]: 'added permanently' Out[82]: ['Arithmetic', 5, 0.28, 'elbow', 'shire', 0, 9.45, 'sequel', 2356]

In [65]: my_list1

Out[65]: [1, 2, 3] Reassignment of elements [Mutable]

In [83]: my_list1
Sort Out[83]: [1, 2, 3]
sort() method to sort the list in alphabetical or ascending order
In [84]: my_list1[2] = 4

In [66]: name_list = ['x','i','o','r','d']


num_list =[9,3,4,0,8,1] In [85]: my_list1

Out[85]: [1, 2, 4]
In [67]: name_list.sort()

In [68]: name_list
Nested lists
Out[68]: ['d', 'i', 'o', 'r', 'x']
In [86]: lst1 = [1,2,3]
In [69]: num_list.sort()
In [87]: lst2 = [4,5,6]
In [70]: num_list

Out[70]: [0, 1, 3, 4, 8, 9] In [88]: lst3 = [7,8,9]

In [71]: newest_list In [89]: listed = [lst1,lst2,lst3]

Out[71]: ['Arithmetic', 5, 0.28, 'elbow', 'shire', 0, 9.45, 'sequel', 2356]


In [90]: listed

In [73]: newest_list.sort() #sort method not supported when there are different obje Out[90]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
cts in a list
In [91]: listed[0][1] #to get the number 2
--------------------------------------------------------------------------
- Out[91]: 2
TypeError Traceback (most recent call las
t)
<ipython-input-73-fb62abb9f973> in <module> In [92]: listed[2][0] #to get the number 7
----> 1 newest_list.sort() #sort method not supported when there are diffe Out[92]: 7
rent objects in a list

TypeError: '<' not supported between instances of 'int' and 'str'

Dictionaries
Reverse

Dictionaries are unordered sequence of elements. They follow key value pairs.
In [79]: newest_list.reverse() # this is permanent
In [105]: dict1['key1'] = 'sound'
When to use a dictionary and list? dict1
Dictionary is used when we need quick retrival of data whereas list is used when we need to know the
Out[105]: {'key1': 'sound'}
location of data

In [106]: dict1['key2'] = 'horn'

Constructing a dictionary In [107]: dict1

Out[107]: {'key1': 'sound', 'key2': 'horn'}


In [93]: my_dict1 = {'key1':'apple','key2':'rice','key3':'protein'}
my_dict1

Out[93]: {'key1': 'apple', 'key2': 'rice', 'key3': 'protein'}


Using functions with dictionary
In [94]: my_dict2 = {'k1':12,'k2':45,'k3':56}
my_dict2 In [110]: dict1['key1'].upper()

Out[94]: {'k1': 12, 'k2': 45, 'k3': 56} Out[110]: 'SOUND'

In [95]: my_dict3 = {'name':'Gayathri','age':27,'weight':68.35,'scores':[91,92,9 In [111]: dict1


3],'dict':{'k1':'good','k2':11,'k3':9.10}}
Out[111]: {'key1': 'sound', 'key2': 'horn'}

In [96]: my_dict3

Out[96]: {'name': 'Gayathri', Similarly other arithmetic operations such as additon,subtraction, multiplication , division can also be done on
'age': 27, dictionaries
'weight': 68.35,
'scores': [91, 92, 93],
In [112]: dict2 = {'k1':34,'k2':56}
'dict': {'k1': 'good', 'k2': 11, 'k3': 9.1}}
dict2

In [98]: my_dict3['name'] Out[112]: {'k1': 34, 'k2': 56}

Out[98]: 'Gayathri'
In [113]: dict2['k1'] = dict2['k1']-21

In [100]: my_dict3['scores'][1]
In [115]: dict2
Out[100]: 92
Out[115]: {'k1': 13, 'k2': 56}

In [101]: my_dict3['dict']

Out[101]: {'k1': 'good', 'k2': 11, 'k3': 9.1} Assignment operation can also be done

In [102]: my_dict3['dict']['k2'] In [116]: dict2['k1'] += 10


dict2
Out[102]: 11
Out[116]: {'k1': 23, 'k2': 56}

In [117]: [Link]()
Adding elements to a dictionary [Mutable]
Out[117]: dict_keys(['key1', 'key2'])

In [103]: #if we started off with an empty dictionary


dict1 = {} In [118]: [Link]()

Out[118]: dict_values(['sound', 'horn'])


In [104]: dict1

Out[104]: {}
In [119]: [Link]() In [6]: #Indexing
tup3[2]
Out[119]: dict_items([('key1', 'sound'), ('key2', 'horn')])
Out[6]: 3

In [7]: tup3[3][1]
Nested dictionaries
Out[7]: 6
In [122]: new_dict = {'outkey':{'inkey':{'innerkey':100}}}
new_dict In [8]: tup3[-1]
Out[122]: {'outkey': {'inkey': {'innerkey': 100}}} Out[8]: [5, 6, 7]

In [130]: new_dict['outkey'] In [9]: #Slicing


tup3[2:]
Out[130]: {'inkey': {'innerkey': 100}}
Out[9]: (3, [5, 6, 7])
In [131]: new_dict['outkey']['inkey']
In [10]: tup3[:-1]
Out[131]: {'innerkey': 100}
Out[10]: (1, 2, 3)
In [132]: new_dict['outkey']['inkey']['innerkey']
In [11]: len(tup3)
Out[132]: 100
Out[11]: 4

In [14]: tup4 = (1,1,4,7,9,3,5,5)


Tuples tup4

Out[14]: (1, 1, 4, 7, 9, 3, 5, 5)
Tuples are ordered sequence of characters similar to lists
Tuples are immutable that is they cannot be changed In [15]: #Index method allows only the display of position of first occurence of the
Tuples have only two methods element
[Link](5)
Tuples can have more than one object type
Out[15]: 6

In [1]: tup1 = (1,2,3,4)


In [16]: #Count method
[Link](1)
In [2]: tup1
Out[16]: 2
Out[2]: (1, 2, 3, 4)

In [17]: #Tuples are immutable


In [3]: tup2 = (1,'one',3,9,'seek') tup4[0] = 2
tup2
--------------------------------------------------------------------------
Out[3]: (1, 'one', 3, 9, 'seek') -
TypeError Traceback (most recent call las
In [4]: tup3 = (1,2,3,[5,6,7]) t)
<ipython-input-17-12226e5d6504> in <module>
1 #Tuples are immutable
In [5]: tup3 ----> 2 tup4[0] = 2
Out[5]: (1, 2, 3, [5, 6, 7])
TypeError: 'tuple' object does not support item assignment
In [31]: y = 1>2
y
Sets Out[31]: False

Sets are unordered collection of unique objects. In [32]: 8 == 8

Out[32]: True
In [18]: set1 = set() #empty set
In [33]: a = None
In [19]: set1 print(a)

Out[19]: set() None

In [20]: [Link](2) #adding an element to a set


set1

Out[20]: {2}
I/O Files

In [22]: [Link](3)
IPython writing a file
In [23]: set1
In [3]: %%writefile [Link]
Out[23]: {2, 3} Hi, this is my first time creating a file in python

Writing [Link]
In [24]: [Link](2) #set only takes unique objects
set1

Out[24]: {2, 3}
Opening a python file
In [25]: [Link]('struck')
In [5]: #Saved in the same directory as the .py script
fileopen = open('[Link]')
In [26]: set1

Out[26]: {2, 3, 'struck'} In [6]: #reading the opened file


[Link]()
In [27]: list1 = [5,5,5,5,5,5,9,9,9,9,9,4,4,4,4,4,4,4] Out[6]: 'Hi, this is my first time creating a file in python\n'
list1

Out[27]: [5, 5, 5, 5, 5, 5, 9, 9, 9, 9, 9, 4, 4, 4, 4, 4, 4, 4] In [7]: #rereading the opened file


[Link]()
In [29]: set(list1) #typecasting Out[7]: ''
Out[29]: {4, 5, 9}

The output is a blank space because the cursor is at the end of the line and we are supposed to make it point
to the beginning of the document so that it can reread.
Boolean
In [8]: [Link](0) #argument 0 shows the beginning of the line i.e start of f
ile at index 0
Boolean has two values 'True' and 'False' meaning 1 and 0. It also has a placeholder value 'None'
Out[8]: 0

In [30]: x = True In [9]: [Link]()


x
Out[9]: 'Hi, this is my first time creating a file in python\n'
Out[30]: True
In [10]: [Link](0) In [27]: [Link]() #the error is because we have used the write only mode `w` an
[Link]() #readlines() method reads the text line by line d hence it is not readable

Out[10]: ['Hi, this is my first time creating a file in python\n'] --------------------------------------------------------------------------


-
UnsupportedOperation Traceback (most recent call las
In [11]: [Link]()
t)
<ipython-input-27-f51008fa62ae> in <module>
----> 1 [Link]()

Writing into a file UnsupportedOperation: not readable

In [14]: # 'w' and 'w+' lets you read and write into a file
In [28]: [Link]()
myfile = open('[Link]','w+')

In [31]: myfile = open('[Link]')


In [15]: [Link]('This is an open ended argument')

Out[15]: 30 In [32]: [Link]() #the lines written before `w` operation have been deleted

Out[32]: 'What is gonna happen here?'


In [16]: [Link]()

Out[16]: ''

Appending to a file
In [17]: [Link](0)
[Link]() Passing the argument 'a' opens the file and puts the pointer at the end, so anything written is appended. Like
Out[17]: 'This is an open ended argument' 'w+', 'a+' lets us read and write to a file. If the file does not exist, one will be created.

In [33]: myfile = open('[Link]','a+')


Since we have used w+ to write , already present lines have been deleted and the new lines have been [Link]('\nWho knows and who cares?')
[Link]('\nDo you?')
overwritten in this file
Out[33]: 8
In [18]: [Link]()
In [34]: [Link](0)
In [20]: myfile = open('[Link]') [Link]()
[Link]()
Out[34]: 'What is gonna happen here?\nWho knows and who cares?\nDo you?'
Out[20]: 'This is an open ended argument'
In [35]: print([Link]())
In [21]: [Link]()
[]

In [22]: myfile = open('[Link]','w')


In [36]: [Link](0)

In [23]: [Link]('What is gonna happen here?') Out[36]: 0

Out[23]: 26
In [37]: print([Link]())

In [26]: [Link](0) ['What is gonna happen here?\n', 'Who knows and who cares?\n', 'Do you?']

Out[26]: 0
In [38]: [Link](0)
print([Link]())

What is gonna happen here?


Who knows and who cares?
Do you?
In [40]: [Link]()

Table of Comparison Operators


Appending to %%write In the table below, a=3 and b=4.

In [44]: %%writefile -a [Link] Operator Description Example


So this is happiness
== If the values of two operands are equal, then the (a == b) is not true.
Appending to [Link]
condition becomes true.

In [45]: myfile = open('[Link]') != If values of two operands are not equal, then (a != b) is true
[Link]() condition becomes true.

Out[45]: 'What is gonna happen here?\nWho knows and who cares?\nDo you? So this > If the value of left operand is greater than the value of (a > b) is not true.
is happiness\n' right operand, then condition becomes true.

In [46]: [Link]() < If the value of left operand is less than the value of (a < b) is true.
right operand, then condition becomes true.

>= If the value of left operand is greater than or equal to (a >= b) is not true.
Iterating through a file the value of right operand, then condition becomes
true.

In [48]: for jjk in open('[Link]'): <= If the value of left operand is less than or equal to the (a <= b) is true.
print(jjk) value of right operand, then condition becomes true.

What is gonna happen here?

Who knows and who cares?


In [1]: 1 < 2 < 3
Do you? So this is happiness
Out[1]: True

The above statement checks if 1 was less than 2 and if 2 was less than 3. We could have written this using

Comparison Operators an and statement in Python:

In [2]: 1<2 and 2<3

Out[2]: True

The and is used to make sure two checks have to be true in order for the total check to be true. Let's see
another example:

In [3]: 1 < 3 > 2

Out[3]: True

The above checks if 3 is larger than both of the other numbers, so you could use and to rewrite it as:

In [4]: 1<3 and 3>2

Out[4]: True
It's important to note that Python is checking both instances of the comparisons. We can also use or to write
comparisons in Python. For example:

In [5]: 1==2 or 2<3

Out[5]: True

Note how it was true; this is because with the or operator, we only need one or the other to be true. Let's see
one more example to drive this home:

In [6]: 1==1 or 100==1

Out[6]: True

You might also like