python object and data structure of basics

NUMBERS:

  • the answer for 0.1+0.2-0.3 should be zero , but the answer is5.551115123125783e-17

The reason behind this is Relative Error ,Ulps and Rounding according to “What Every Computer Scientist Should Know About Floating-Point Arithmetic“, by David Goldberg, published in the March, 1991.

python 3 perform true division . eg -output of 1/2 is 0.5

Rules for variable names :

  1. Names can not start with a number
  2. there are no spaces in variable name
  3. no special symbols can be used
  4. no special keywords can be used

python uses dynamic typing whereas C++ is static typing. Pros and Cons of dynamic typing:

  • User friendly
  • faster development time
  • May cause confusion between unexpected data types

type() -returns the data type of variable

Strings:

strings are ordered sequences .It can be denoted as ‘hello’ or “I don’t have time”,in second example if we had used a single quote then it would have ended at n.

Indexing grab a single character from a string[]. Reverse indexing is also possible.

slicing we grab a sub section of multiple characters .[star:stop:step].

for eg :mystring="Programmer Prodigy"
then to index we can use mystring[location of character in the string],string starts from location 0.

if we use mystring[starting_location:ending_location(not including the ending location):step size] ,we could address that to a sub string.
mystring[::-1] : means reversing the string,for eg mystring[::-1]=ygidorp remmargorp

\n-> a new line ,\t->four spaces

Built in functions

  1. len()- counts the white spaces
  2. concatenation – is done with the help of a ‘+”sign
  3. split()=by default it splits the string bu white spaces . Could also be done on a character

String properties

  1. Immutability
name="Sam"
#name[0]='P' will not work, so we could use
previous=name[1:]
'P'+previous

Formatting

A way to format a string is with the string.format()method .Syntax is                                print('This is a string {}'.format('Inserted'))

for example :
print('The {} {} {} '.format('fox','brown','quick'))
o/p->The fox brown quick
if we want to order the formatting of the string
print('The {2} {1} {0} '.format('fox','brown','quick'))
or
print('The {q} {b} {f}' .format(f='fox',b='brown',q='quick'))

precision of the result:
"{value:width.precision f}"
for ex-
pi = 22/7
print("the value of pi {p:1.8f}".format(p=pi))

string literal method :
This method came into use from python 3.6.
for example:
name="Hridyesh"
print(f'Hello ,my name is {name}')

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s