Python – Numbers

Course Curriculum

Python – Numbers

Number data types store numeric values. They are immutable data types, means that changing the value of a number data type results in a newly allocated object.
Number objects are created when you assign a value to them. For example −

num1 = 100
num2 = 200.222

Python supports four different numerical types −

  • int (signed integers) − They are often called just integers or ints, are positive or negative whole numbers with no decimal point.
  • long (long integers ) − Also called longs, they are integers of unlimited size, written like integers and followed by an uppercase or lowercase L.
  • float (floating point real values) − Also called floats, they represent real numbers and are written with a decimal point dividing the integer and fractional parts. Floats may also be in scientific notation, with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250).
  • complex (complex numbers) − are of the form a + bJ, where a and b are floats and J (or j) represents the square root of -1 (which is an imaginary number). The real part of the number is a, and the imaginary part is b. Complex numbers are not used much in Python programming.

    Examples

    Here are some examples of numbers

    int long float complex
    10 51924361L 0.0 3.14j
    100 -0x19323L 15.20 45.j
    -786 0122L -21.9 9.322e-36j
    080 0xDEFABCECBDAECBFBAEL 32.3+e18 .876j
    -0490 535633629843L -90. -.6545+0J
    -0x260 -052318172735L -32.54e100 3e+26J
    0x69 -4721885298529L 70.2-E12 4.53e-7j
  • Python allows you to use a lowercase L with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1. Python displays long integers with an uppercase L.
  • A complex number consists of an ordered pair of real floating point numbers denoted by a + bj, where a is the real part and b is the imaginary part of the complex number.

    Number Type Conversion

    Python converts numbers internally in an expression containing mixed types to a common type for evaluation. But sometimes, you need to coerce a number explicitly from one type to another to satisfy the requirements of an operator or function parameter.

  • Type int(x) to convert x to a plain integer.
  • Type long(x) to convert x to a long integer.
  • Type float(x) to convert x to a floating-point number.
  • Type complex(x) to convert x to a complex number with real part x and imaginary part zero.
  • Type complex(x, y) to convert x and y to a complex number with real part x and imaginary part y. x and y are numeric expressions

    Mathematical Functions

    Python includes following functions that perform mathematical calculations.

    Sr.No. Function & Returns ( description )
    1 abs(x)

    The absolute value of x: the (positive) distance between x and zero.

    2 ceil(x)

    The ceiling of x: the smallest integer not less than x

    3 cmp(x, y)

    -1 if x y

    4 exp(x)

    The exponential of x: ex

    5 fabs(x)

    The absolute value of x.

    6 floor(x)

    The floor of x: the largest integer not greater than x

    7 log(x)

    The natural logarithm of x, for x> 0

    8 log10(x)

    The base-10 logarithm of x for x> 0.

    9 max(x1, x2,...)

    The largest of its arguments: the value closest to positive infinity

    10 min(x1, x2,...)

    The smallest of its arguments: the value closest to negative infinity

    11 modf(x)

    The fractional and integer parts of x in a two-item tuple. Both parts have the same sign as x. The integer part is returned as a float.

    12 pow(x, y)

    The value of x**y.

    13 round(x [,n])

    x rounded to n digits from the decimal point. Python rounds away from zero as a tie-breaker: round(0.5) is 1.0 and round(-0.5) is -1.0.

    14 sqrt(x)

    The square root of x for x > 0

    Random Number Functions

    Random numbers are used for games, simulations, testing, security, and privacy applications. Python includes following functions that are commonly used.

    Sr.No. Function & Description
    1 choice(seq)

    A random item from a list, tuple, or string.

    2 randrange ([start,] stop [,step])

    A randomly selected element from range(start, stop, step)

    3 random()

    A random float r, such that 0 is less than or equal to r and r is less than 1

    4 seed([x])

    Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None.

    5 shuffle(lst)

    Randomizes the items of a list in place. Returns None.

    6 uniform(x, y)

    A random float r, such that x is less than or equal to r and r is less than y

    Trigonometric Functions

    Python includes following functions that perform trigonometric calculations.

    Sr.No. Function & Description
    1 acos(x)

    Return the arc cosine of x, in radians.

    2 asin(x)

    Return the arc sine of x, in radians.

    3 atan(x)

    Return the arc tangent of x, in radians.

    4 atan2(y, x)

    Return atan(y / x), in radians.

    5 cos(x)

    Return the cosine of x radians.

    6 hypot(x, y)

    Return the Euclidean norm, sqrt(x*x + y*y).

    7 sin(x)

    Return the sine of x radians.

    8 tan(x)

    Return the tangent of x radians.

    9 degrees(x)

    Converts angle x from radians to degrees.

    10 radians(x)

    Converts angle x from degrees to radians.

    Mathematical Constants

    The module also defines two mathematical constants −

    Sr.No. Constants & Description
    1 pi

    The mathematical constant pi.

    2 e

    The mathematical constant e.

    https://prutor.ai/python/python_strings.htm

    Python - Strings

    Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single quotes the same as double quotes. Creating strings is as simple as assigning a value to a variable. For example −

    a = 'Hello Prutor'
    b = "Python Programming"

    Accessing Values in Strings

    Python does not support a character type; these are treated as strings of length one, thus also considered a substring.
    To access substrings, use the square brackets for slicing along with the index or indices to obtain your substring. For example −

    a = 'Hello Prutor'
    b = "Python Programming"
    print ("a[0]: ", a[0])
    print ("b[1:5]: ", b[1:5])

    When the above code is executed, it produces the following result −

    a[0]:  H
    b[1:5]:  ytho

    Updating Strings

    You can "update" an existing string by (re)assigning a variable to another string. The new value can be related to its previous value or to a completely different string altogether. For example −

    str = 'Hello prutor!'
    print("orignal string :- " + str)
    print ("Updated String :- ", str[:6] + 'Python')

    When the above code is executed, it produces the following result −

    orignal string :- Hello prutor!
    Updated String :-  Hello Python

    Escape Characters

    Following table is a list of escape or non-printable characters that can be represented with backslash notation.
    An escape character gets interpreted; in a single quoted as well as double quoted strings.

    Backslash notation Hexadecimal character Description
    a 0x07 Bell or alert
    b 0x08 Backspace
    cx Control-x
    C-x Control-x
    e 0x1b Escape
    f 0x0c Formfeed
    M-C-x Meta-Control-x
    n 0x0a Newline
    nnn Octal notation, where n is in the range 0.7
    r 0x0d Carriage return
    s 0x20 Space
    t 0x09 Tab
    v 0x0b Vertical tab
    x Character x
    xnn Hexadecimal notation, where n is in the range 0.9, a.f, or A.F

    String Special Operators

    Assume string variable a holds 'Hello' and variable b holds 'Prutor', then −

    Operator Description Example
    + Concatenation - Adds values on either side of the operator a + b will give HelloPrutor
    * Repetition - Creates new strings, concatenating multiple copies of the same
    string
    a*2 will give -HelloHello
    [] Slice - Gives the character from the given index a[1] will give e
    [ : ] Range Slice - Gives the characters from the given range a[1:4] will give ell
    in Membership - Returns true if a character exists in the given string 'H' in a will give true
    not in Membership - Returns true if a character does not exist in the given string M not in a will give true
    r/R Raw String - Suppresses actual meaning of Escape characters. The syntax for raw strings is exactly the same as for normal strings with the exception of the raw string operator, the letter "r," which precedes the quotation marks. The "r" can be lowercase (r) or uppercase (R) and must be placed immediately preceding the first quote mark. print r'n' prints n and print R'n'prints n
    % Format - Performs String formatting See at next section

    String Formatting Operator

    One of Python's coolest features is the string format operator %. This operator is unique to strings and makes up for the pack of having functions from C's printf() family. Following is a simple example −

    print ("Current Month is %s and current date is %d !" % ('February', 27))

    When the above code is executed, it produces the following result −

    Current Month is February and current date is 27 !

    Here is the list of complete set of symbols which can be used along with % −

    Format Symbol Conversion
    %c character
    %s string conversion via str() prior to formatting
    %i signed decimal integer
    %d signed decimal integer
    %u unsigned decimal integer
    %o octal integer
    %x hexadecimal integer (lowercase letters)
    %X hexadecimal integer (UPPERcase letters)
    %e exponential notation (with lowercase 'e')
    %E exponential notation (with UPPERcase 'E')
    %f floating point real number
    %g the shorter of %f and %e
    %G the shorter of %f and %E

    Other supported symbols and functionality are listed in the following table −

    Symbol Functionality
    * argument specifies width or precision
    - left justification
    + display the sign
    leave a blank space before a positive number
    # add the octal leading zero ( '0' ) or hexadecimal leading '0x' or '0X', depending on whether 'x' or 'X' were used.
    0 pad from left with zeros (instead of spaces)
    % '%%' leaves you with a single literal '%'
    (var) mapping variable (dictionary arguments)
    m.n. m is the minimum total width and n is the number of digits to display after the decimal point (if appl.)

    Example

    my_name = 'John'
    my_age = 24
    my_height = 74 # inches
    my_weight = 180 # lbs
    my_eyes = 'Blue'
    my_teeth = 'White'
    my_hair = 'Brown'
    print(f"Let's talk about {my_name}.")
    print(f"He's {my_height} inches tall.")
    print(f"He's {my_weight} pounds heavy.")
    print("Actually that's not too heavy.")
    print(f"He's got {my_eyes} eyes and {my_hair} hair.")
    print(f"His teeth are usually {my_teeth} depending on the coffee.")
    # this line is tricky, try to get it exactly right
    total = my_age + my_height + my_weight
    print(f"If I add {my_age}, {my_height}, and {my_weight} I get {total}.")
  • this will give following output
    Let's talk about John.
    He's 74 inches tall.
    He's 180 pounds heavy.
    Actually that's not too heavy.
    He's got Blue eyes and Brown hair.
    His teeth are usually White depending on the coffee.
    If I add 24, 74, and 180 I get 278.

    Triple Quotes

    Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters.
    The syntax for triple quotes consists of three consecutive single or double quotes.

    triple_quotes_example = """Spanning strings over multiple lines can be done using python’s triple quotes. It is also used for long comments in code. Special characters like TABs, verbatim or NEWLINEs can also be used within the triple quotes. As the name suggests its syntax consists of three consecutive single or double-quotes."""
    """this is comment"""
    print(triple_quotes_example)

    When the above code is executed, it produces the following result.

    Spanning strings over multiple lines can be done using python’s triple quotes. It is also used for long comments in code. Special characters like TABs, verbatim or NEWLINEs can also be used within the triple quotes. As the name suggests
    its syntax consists of three consecutive single or double-quotes.

    Raw strings do not treat the backslash as a special character at all. Every character you put into a raw string stays the way you wrote it −

    print ('hello n this in prutor')

    When the above code is executed, it produces the following result −

    hello
    this in prutor

    Now let's make use of raw string. We would put expression in r'expression' as follows −

    print (r'hello n this in prutor')

    When the above code is executed, it produces the following result −

    hello n this in prutor
  • some more example
    days = "Mon Tue Wed Thu Fri Sat Sun"
    months = "JannFebnMarnAprnMaynJunnJulnAug"
    print("Here are the days: ", days)
    print("Here are the months: ", months)
    print("""
    There's something going on here.
    With the three double-quotes.
    We'll be able to type as much as we like.
    Even 4 lines if we want, or 5, or 6.
    """)
  • When the above code is executed, it produces the following result −
    Here are the days:  Mon Tue Wed Thu Fri Sat Sun
    Here are the months:  Jan
    Feb
    Mar
    Apr
    May
    Jun
    Jul
    Aug
    There's something going on here.
    With the three double-quotes.
    We'll be able to type as much as we like.
    Even 4 lines if we want, or 5, or 6.

    String Length

    To get the length of a string, use the len() function.

    str = "Hello World!"
    print (len(str))
  • output: 12

    Upper Case

    The upper() method returns the string in upper case:

    str = "Hello World!"
    print (str.upper())
    output: HELLO WORLD!

    Lower Case

    The lower() method returns the string in lower case:

    str = "Hello World!"
    print (str.lower())
    output: hello world!

    Unicode String

    Normal strings in Python are stored internally as 8-bit ASCII, while Unicode strings are stored as 16-bit Unicode. This allows for a more varied set of characters, including special characters from most languages in the world. I'll restrict my treatment of Unicode strings to the following −
    The Unicode standard describes how characters are represented by code points. A code point value is an integer in the range 0 to 0x10FFFF (about 1.1 million values, the actual number assigned is less than that). In the standard and in this document, a code point is written using the notation U+265E to mean the character with value 0x265e (9,822 in decimal).

    print(u'Hello, world!')

    When the above code is executed, it produces the following result −

    Hello, world!

    As you can see, Unicode strings use the prefix u, just as raw strings use the prefix r.

    Built-in String Methods

    Python includes the following built-in methods to manipulate strings −

    Sr.No. Methods with Description
    1 capitalize()

    Capitalizes first letter of string

    2 center(width, fillchar)

    Returns a space-padded string with the original string centered to a total of width columns.

    3 count(str, beg= 0,end=len(string))

    Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given.

    4 decode(encoding='UTF-8',errors='strict')

    Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding.

    5 encode(encoding='UTF-8',errors='strict')

    Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with 'ignore' or 'replace'.

    6 endswith(suffix, beg=0, end=len(string))

    Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.

    7 expandtabs(tabsize=8)

    Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.

    8 find(str, beg=0 end=len(string))

    Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.

    9 index(str, beg=0, end=len(string))

    Same as find(), but raises an exception if str not found.

    10 isalnum()

    Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.

    11 isalpha()

    Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.

    12 isdigit()

    Returns true if string contains only digits and false otherwise.

    13 islower()

    Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.

    14 isnumeric()

    Returns true if a unicode string contains only numeric characters and false otherwise.

    15 isspace()

    Returns true if string contains only whitespace characters and false otherwise.

    16 istitle()

    Returns true if string is properly "titlecased" and false otherwise.

    17 isupper()

    Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.

    18 join(seq)

    Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.

    19 len(string)

    Returns the length of the string

    20 ljust(width[, fillchar])

    Returns a space-padded string with the original string left-justified to a total of width columns.

    21 lower()

    Converts all uppercase letters in string to lowercase.

    22 lstrip()

    Removes all leading whitespace in string.

    23 maketrans()

    Returns a translation table to be used in translate function.

    24 max(str)

    Returns the max alphabetical character from the string str.

    25 min(str)

    Returns the min alphabetical character from the string str.

    26 replace(old, new [, max])

    Replaces all occurrences of old in string with new or at most max occurrences if max given.

    27 rfind(str, beg=0,end=len(string))

    Same as find(), but search backwards in string.

    28 rindex( str, beg=0, end=len(string))

    Same as index(), but search backwards in string.

    29 rjust(width,[, fillchar])

    Returns a space-padded string with the original string right-justified to a total of width columns.

    30 rstrip()

    Removes all trailing whitespace of string.

    31 split(str="", num=string.count(str))

    Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given.

    32 splitlines( num=string.count('n'))

    Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed.

    33 startswith(str, beg=0,end=len(string))

    Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring str; returns true if so and false otherwise.

    34 strip([chars])

    Performs both lstrip() and rstrip() on string.

    35 swapcase()

    Inverts case for all letters in string.

    36 title()

    Returns "titlecased" version of string, that is, all words begin with uppercase and the rest are lowercase.

    37 translate(table, deletechars="")

    Translates string according to translation table str(256 chars), removing those in the del string.

    38 upper()

    Converts lowercase letters in string to uppercase.

    39 zfill (width)

    Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).

    40 isdecimal()

    Returns true if a unicode string contains only decimal characters and false otherwise.

    https://prutor.ai/python/python_lists.htm

    Python - Lists

    The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number - its position or index. The first index is zero, the second index is one, and so forth.
    Python has six built-in types of sequences, but the most common ones are lists and tuples, which we would see in this tutorial.
    There are certain things you can do with all sequence types. These operations include indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has built-in functions for finding the length of a sequence and for finding its largest and smallest elements.

    Python Lists

    The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type.
    Creating a list is as simple as putting different comma-separated values between square brackets. For example −

    list1 = ["mango", 34, True, False, "male",22.7]
    list2 = [1, 5, 7, 9, 3]
    list3 = ['w','x','y','z']

    Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.

    Accessing Values in Lists

    To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −

    list1 = ["mango", 34, True, False, "male",22.7]
    list2 = [1, 5, 7, 9, 3]
    list3 = ['w','x','y','z']
    print("list1[0]" , list1[0])
    print("list2[1]",list2[1])
    print("list1[1:3]",list1[1:3])
    print("list3[1:]",list3[1:])

    When the above code is executed, it produces the following result −

    list1[0] #mango
    list2[1] #5
    list1[1:3] #[34, True]
    list3[1:] #['x', 'y', 'z']

    Updating Lists

    You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method. For example −

    list = ['demo',567,3.6,'prutor',570.7]
    print ("Value available at index 2 : ")
    print(list[2])
    list[2] = "22.77777"
    print("New value available at index 2 : ")
    print(list[2])

    When the above code is executed, it produces the following result −

    Value available at index 2 :
    3.6
    New value available at index 2 :
    22.77777

    Delete List Elements

    To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know. For example −

    list = ["mango", 34, True, False, "male",22.7]
    print(list)
    del list[3]
    print("After deleting index 3 value from list",list)

    When the above code is executed, it produces following result −

    ['mango', 34, True, False, 'male', 22.7]
    After deleting index 3 value from list ['mango', 34, True, 'male', 22.7]

    some examples

  • To find sum of all nested lists
    def nested_sum(t):
    s=0
    for i in range(len(t)):
    s+=sum(t[i])
    return s
    t=[[1,2],[3],[4,5,6]]
    print(nested_sum(t))

    it will give following output

    21

    To return a list without first and last element

    def middle(t):
    return t[1:-1]
    t = [1, 2, 3, 4, 5]
    print(middle(t))

    it will give following output

    [2, 3, 4]

    To chop head and tail of list

    def chop(t):
    del t[0]
    del t[-1]
    t = [1, 2, 3, 4]
    chop(t)
    print(t)
    [2, 3]

    Library Management system with basic functionality

    books = ['physics', 'chemstry', 'english', 'bioa']
    def add_book():
    book_name = input("enter book name : ")
    books.append(book_name)
    print(books)
    def return_book():
    book_name = input("enter book name to return : ")
    print("your %s has successfully returned!" % book_name)
    def remove_book():
    book_name = input("enter book name to remove : ")
    print("your %s has successfully removed" % book_name)
    print("""
    Welcome to Python Library System.
    a To add a book
    b To return a book
    c To remove a book from the collection
    """)
    user_option = input('Enter your choice now:')
    user_option = user_option.lower()
    if user_option == 'a':
    add_book()
    elif user_option == 'b':
    return_book()
    elif user_option == 'c':
    remove_book()
    else:
    print("Invalid choice")

    Basic List Operations

    Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string.
    In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter.

    Python Expression Results Description
    len([12,19,50]) 3 Length
    [12,19,50] + [90,30,56] [12,19,50,90,30,56] Concatenation
    ['prutor'] * 3 ['prutor','prutor','prutor','prutor' Repetition
    45 in [90, 47,35] True Membership
    for x in [90,47,45]: print (x), 90 47 45 Iteration

    Indexing, Slicing, and Matrixes

    Because lists are sequences, indexing and slicing work the same way for lists as they do for strings.
    Assuming following input −

    list = ['apple','mango','Papaya']
    Python Expression Results Description
    print(list[2]) Papaya Offsets start at zero
    print(list[-2]) mango Negative: count from the right
    print(list[1:]) ['mango', 'Papaya'] Slicing fetches sections

    Built-in List Functions & Methods

    Python includes the following list functions −

    Sr.No. Function with Description
    1 cmp(list1, list2)

    Compares elements of both lists.

    2 len(list)

    Gives the total length of the list.

    3 max(list)

    Returns item from the list with max value.

    4 min(list)

    Returns item from the list with min value.

    5 list(seq)

    Converts a tuple into list.

    Python includes following list methods

    Sr.No. Methods with Description
    1 list.append(obj)

    Appends object obj to list

    2 list.count(obj)

    Returns count of how many times obj occurs in list

    3 list.extend(seq)

    Appends the contents of seq to list

    4 list.index(obj)

    Returns the lowest index in list that obj appears

    5 list.insert(index, obj)

    Inserts object obj into list at offset index

    6 list.pop(obj=list[-1])

    Removes and returns last object or obj from list

    7 list.remove(obj)

    Removes object obj from list

    8 list.reverse()

    Reverses objects of list in place

    9 list.sort([func])

    Sorts objects of list, use compare func if given

Python – Loops (Prev Lesson)
(Next Lesson) Python – Modules
', { 'anonymize_ip': true });