Chapter 2: Basic Data Types - VinGok/Python-Basics GitHub Wiki
Variable names given for data type values. Identifiers point to the memory location that hold the data.
Rules to follow while naming identifiers
- The start character can be any alphabet ("a", "b", ..., "z", "A", "B", ..., "Z"), the underscore ("_"), as well as the alphabets from most non-English languages.
- Avoid using Python’s keywords, function names.
and, continue, except, global, lambda, pass, while,
as, def, False, if, None, raise, with,
assert, del, finally, import, nonlocal, return, yield,
break, elif, for, in, not, True, class, else, from, is, or, try
Important: Identifiers are case-sensitive.
## data pointed by the identifier
->>> a=120
->>> print(a)
120
## address of the memory location
->>> print(id(a))
1346189584
## input data from keyboard
->>> x = input ('Enter an integer: ')
Enter an integer: 135
->>> print(x)
135
## using function name as identifier
->>> input = 200
->>> print(input)
TypeError: 'int' object is not callable
Indentations have strict meaning. Do not use them unnecessarily!
Data type specifies the form of data. Examples: integer, floating, boolean, etc.
- Basic
- Integer: integral values; Examples: 2, 100, -1000, etc.
- Float: fractional values; Examples: 2.0, 100.9999, -999.12, etc.
- String: single/multiple characters; Examples: 'python', 'basics', 'python-basics', etc.
- Collection
- List: modifiable, ordered group of basic data types
- Tuple: un-modifiable, ordered group of basic data types
- Set: modifiable, unordered group of basic data types
- Dictionary: modifiable, unordered group of name-value pairs
No need to declare the data type of a identifier.
- int: 10, 35, -499
- boolean: True, False
Integer Operators and Functions
Syntax | Description |
---|---|
x + y | Adds number x and number y |
x - y | Subtracts y from x |
x * y | Multiplies x by y |
x / y | Divides x by y; always produces a fractional quotient |
x // y | Divides x by y; truncates any fractional part so always produces an integer result |
x % y | Produces the modulus (remainder) of dividing x by y |
x ** y | Raises x to the power of y; see also the pow() functions |
abs(x) | Returns the absolute value of x |
pow(x, y) | Raises x to the power of y ; the same as the ** operator |
->>> a=120
->>> b=80
->>> c=50
->>> type(a)
<class 'int'>
->>> a+b/c
121.6
->>> a+b//c
121
->>> a = 3
->>> a += 2
->>> print(a)
5
->>> a = 3
->>> a *= 2
->>> print(a)
6
->>> a = 30
->>> b = 50
->>> print(a, "plus", b, "equals to", a+b)
30 plus 50 equals to 80
## Convert user-input to integer
->>> a = int(input("Enter a number "))
Enter a number 12
->>> print(a)
12
Example: Write a Python program to add the two digits of a 2-digit user-input integer.
Programming Practice
1. Find out the sum of individual digits in a 6-digit integer.
2. Compute the Euclidean distance between the points (2, 2) and (3, 5).
- Generates a truth value - True or False
- Examples: 1 > 2 - False, 10 > 5 - True.
Boolean Operators
- and - True only if all operands are True; else False
- or - False only if all operands are False; else True
- not - invert the operand's value
->>> a=True
->>> type(a)
<class 'bool'>
->>> a = 1
->>> a == 1
True
->>> num1 = 13
->>> num2 = 25
->>> num1 > num2
False
->>> num1 <= num2
True
## Checking for equality
->>> num1 = -25
->>> num2 = num1
->>> num1 == num2
True
->>> not (num1+num2 <= 0)
False
## Not equal to condition
->>> 26.55 != 26.555
True
->>> (1 <= 2) and (10 == 10.0)
True
->>> (2+3 == 6) or (5//2 == 2)
True
Jump to Control Structures and return to this point
Number base system provides different forms of representing a number analogous to representing length in centimeter, inch, foot, yard, miles, etc. However, one could easily convert from one form to another when necessary.
Commonly used base systems are binary (0, 1), octal (0 to 8), decimal (0 to 9), and hexadecimal (0 to 9, A to F).
Steps for base conversion
1. Decimal to binary
- Divide the decimal number by 2 until it is no more divisible
- After each division, note down the remainders (1 or 0)
- At the end, write the remainders in reverse chronological order to get the binary equivalent
2. Binary to decimal
- Associate each digit of binary number with 2x, where x = 0 for the rightmost digit and increases by 1 per digit to it's left
- Multiply each digit with the corresponding pow(2, x)
- Add all products to get the decimal equivalent
Base Conversion Functions
Syntax | Description |
---|---|
bin(i) | Returns the binary representation of int i as a string |
hex(i) | Returns the hexadecimal representation of i as a string |
oct(i) | Returns the octal representation of i as a string |
int(i, b) | Converts string i to an integer; raises ValueError on failure. The argument b should be an integer between 2 and 36, inclusive of both. |
->>> bin(10)
'0b1010'
->>> int('1010', 2)
10
->>> int('1010')
1010
->>> oct(40)
'0o50'
->>> int ('50', 8)
40
->>> hex(255)
'0xff'
->>> int('ff', 16)
255
Example:
1. Convert 150 in octal to hexadecimal number system.
dec = int('150', 8)
print(hex(dec))
2. Convert 43 in 5-base to octal number system.
dec = int('43', 5)
print(oct(dec))
1. Convert the list of base-20 numbers into a list of hexadecimal numbers.
list_hex = ['AAB', '1039', '2GA3', 'JGH9']
Python provides different types of floating-point values
- the built-in float
- decimal - higher precision than built-in float
->>> a = 1.1
->>> type(a)
<class 'float'>
->>> a = 1.1 + 3
->>> print(a)
4.1
->>> a = 1.1/2
->>> print(a)
0.55
->>> a = float(input("Enter a number: "))
->>> Enter a number: 12.456
->>> print(a)
12.456
->>> int(2.333)
2
->>> float(2)
2.0
Math Module’s Functions and Constants
All functions and operations used with integers can be used with float: +, -, *, /, //, %, abs, pow.
Syntax | Description |
---|---|
math.ceil(x) | Returns the smallest integer greater than or equal to x as an int |
math.floor(x) | Returns the largest integer less than or equal to x as an int |
math.sqrt(x) | Returns square root of x |
->>> import math
->>> math.ceil(2.3)
3
->>>math.floor(2.3)
2
->>> math.sqrt(9)
3.0
Additional functions
Syntax | Description |
---|---|
math.pi | The constant π; approximately 3.141 592 653 589 793 1 |
math.e | The constant e; approximately 2.718 281 828 459 045 1 |
math.exp(x) | Returns ex |
math.acos(x) | Returns the arc cosine of x in radians |
math.acosh(x) | Returns the arc hyperbolic cosine of x in radians |
math.asin(x) | Returns the arc sine of x in radians |
math.asinh(x) | Returns the arc hyperbolic sine of x in radians |
math.atan(x) | Returns the arc tangent of x in radians |
math.atan2(y, x) | Returns the arc tangent of y / x in radians |
math.atanh(x) | Returns the arc hyperbolic tangent of x in radians |
math.copysign(x,y) | Returns x with y's sign |
math.cos(x) | Returns the cosine of x in radians |
math.cosh(x) | Returns the hyperbolic cosine of x in radians |
math.degrees(r) | Converts float r from radians to degrees |
math.factorial(x) | Returns x! |
math.fmod(x, y) | Produces the modulus (remainder) of dividing x by y ; this produces better results than % for float s |
math.frexp(x) | Returns a 2-tuple with the mantissa (as a float) and n the exponent (as an int) so, x= m×2n ; see math.ldexp() |
math.fsum(i) | Returns the sum of the values in iterable i as a float |
math.hypot(x, y) | Returns square root of x2 + y2 |
math.ldexp(m, n) | Returns m×2n |
math.log(x, b) | Returns log x to the base b; b is optional and defaults to math.e |
math.log10(x) | Returns log x to the base 10 |
math.log1p(x) | Returns log (1 + x) to the base e |
math.modf(x) | Returns x's fractional and whole parts as two floats |
math.pow(x, y) | Returns xy as a float |
math.radians(d) | Converts float d from degrees to radians |
math.sin(x) | Returns the sine of x in radians |
math.sinh(x) | Returns the hyperbolic sine of x in radians |
math.tan(x) | Returns the tangent of x in radians |
math.tanh(x) | Returns the hyperbolic tangent of x in radians |
math.trunc(x) | Returns the whole part of x as an int ; same as int(x) |
math.isinf(x) | Returns True if float x is ± inf (± ∞) |
math.isnan(x) | Returns True if float x is nan (“not a number”) |
Used to work with higher precision floating point numbers.
->>> import decimal as d
->>> import math
->>> m.pi
3.141592653589793
->>> d.Decimal(math.pi)
Decimal('3.141592653589793115997963468544185161590576171875')
Decimal and e.g. float cannot be mixed.
->>> from decimal import Decimal as dd
->>> dd(23) / dd("1.05")
Decimal('21.9047619047619047619047619047619047619047619047619047619047619048')
->>> dd(23.15 / math.pi)
Decimal('7.3688738651547538438535411842167377471923828125')
String is enclosed within single quotes (' ') or double quotes (" ") or triple quotes (""" """). If you want to use the same quotes as a part of the string, use escape sequence \ preceding the quotes in the text.
->>> a = "This is Python Basics course"
->>> print(a)
This is Python Basics course
->>> type(a)
<class 'str'>
->>> a = "Python"
->>> print(len(a))
6
->>> a = 'It's a Thursday'
SyntaxError: invalid syntax
->>> a = 'It\'s a Thursday'
->>> print(a)
It's a Thursday
->>> b = "This is "Python Basics" course"
SyntaxError: invalid syntax
->>> b = "This is \"Python Basics\" course"
This is "Python Basics" course
->>> c = "This is Python Basics Course.
It runs every Thursday"
SyntaxError: EOL while scanning string literal
->>> c = """This is Python Basics Course.
It runs every Thursday"""
->>> print(c)
This is Python Basics Course.
It runs every Thursday
Accessing characters: Indexing in Python begins from 0 and not 1. Negative indexes also exist.
->>> a = "This is Python Basics course"
->>> print(a[1])
h
->>> a = "This is Python Basics course"
->>> print(a[len(a)])
IndexError: string index out of range
->>> print(a[len(a)-1])
e
->>> print(a[-2])
s
->>> print(a[-len(a)])
T
Conversion: String conversion to and from int, and float.
->>> a = float('12.34')
->>> print(a, type(a))
12.34 <class 'float'>
->>> a = str(12.34)
->>> print(a, type(a))
12.34 <class 'str'>
->>> a = int('12')
->>> print(a, type(a))
12 <class 'int'>
->>> a = str(12)
->>> print(a, type(a))
12 <class 'str'>
->>> a = int('12.34')
ValueError: invalid literal for int() with base 10: '12.34'
Accessing digits from integers through strings:
->>> a = 150
->>> int(str(a)[0]) + int(str(a)[1]) + int(str(a)[2])
6
for loop with strings
text = "This is Python Basics course"
for i in text:
print (i, end = "")
Output:
This is Python Basics course
text = "This is Python Basics course"
for i in range (0, len(text)):
print (text[i], end="")
Output:
This is Python Basics course
Examples:
Write a Python program to count the number of words in a user-input sentence.
text = "This is Python Basics course"
spaces = 0
for i in text:
if (i == " "):
spaces = spaces+1
print("Word count: ",spaces+1)
Output:
5
->>> "P" in "Python"
True
->>> 3 in (2, 3, 4)
True
->>> "r" not in "Thursday"
False
Programming Practice
5. Print the count of user-input character in a user-input string.
6. Count the number of vowels in a user-input string.
String Operators
1. + string concatenation
2. * string replication
->>> a = "this is Python Basics course"
->>> a = a + " running in winter semester"
->>> print(a)
this is Python Basics course running in winter semester
->>> a = "this is Python Basics course"
->>> a = a + " running in winter semester"
->>> print(a)
this is Python Basics course running in winter semester
->>> a = "this is Python Basics course"
->>> a = a * 2
->>> print(a)
this is Python Basics coursethis is Python Basics course
->>> a = "this is Python Basics course"
->>> print(len(a))
28
Write a Python program to extract only the last word of a string.
text = input("Enter the text: ")
last_word = ""
for i in range (-1,-len(text),-1):
if (text[i] == " "):
break
for j in range(i+1,0):
last_word = last_word + text[j]
print(last_word)
Programming Practice
6. Write a program to eliminate the characters with divisible-by-5 index from a user-input string using break/continue.
7. Write a Python program to replace all vowels by exclamation mark (!) from a user-input string using break/continue.
Immutability - Once assigned, the value of an object cannot be altered. Int, float, boolean, and strings are all immutable.
->>> a = "Python"
->>> a[1] = "m"
TypeError: 'str' object does not support item assignment
->>> a = "Python"
->>> a = a + " Basics"
->>> print(a)
Python Basics
->>> a = "Python"
->>> id(a)
->>> a = a + " Basics"
->>> id(a)
ASCII representation: How computer understands characters in a string?
Every character (numeric and non-numeric) is represented using a number.
Character | ASCII Code | Character | ASCII Code |
---|---|---|---|
A | 65 | a | 97 |
B | 66 | b | 98 |
C | 67 | c | 99 |
: | : | : | : |
Z | 90 | z | 122 |
! | 33 | " | 34 |
# | 35 | $ | 36 |
: | : | : | : |
->>> print(ord('A'))
65
->>> print(ord('!'))
33
->>> print(ord(':'))
58
->>> print(chr(97))
a
->>> print(chr(125))
}
Example: Count the number of upper-case characters in a string
text = "This is Python Basics course"
count = 0
for i in text:
if (ord(i) >= 65 and ord(i) <= 90):
count = count + 1
print("Number of upper-case characters is ", count)
String Encoding example: Write a program to accept a user-input string and output the string in which each character has an ASCII code 15 higher than the corresponding character in user-input string.
input_string = input("Enter the string: ")
output_string = ""
for i in input_string:
output_string = output_string + chr(ord(i)+15)
print("Output string is ", output_string)
Programming Practice:
8. Count the number of consonants in a user-input string.
String Output Formatting:
->>> a = 50
->>> b = 20
->>> print("Sum of", a, "and", b, "is", a+b, "and the difference between", a, "and", b, "is", a-b)
Sum of 50 and 20 is 70 and the difference between 50 and 20 is 30
->>> print("Sum of {0} and {1} is {2}, and the difference between {0} and {1} is {3}".format(a, b, a+b, a-b))
Sum of 50 and 20 is 70, and the difference between 50 and 20 is 30
Slicing and Striding
Slicing - extracting a continuous portion of the string
->>> a = "Python Basics"
->>> print(a[5:10])
n Bas
->>> print(a[-5:-2])
asi
->>> print(a[:])
Python Basics
->>> print(a[2:])
thon Basics
->>> print(a[:8])
Python B
->>> print(a[-2:7])
->>> print(a[9:2:-1])
saB noh
->>> print(a[::])
Python Basics
->>> print(a[::-1])
scisaB nohtyP
->>> print(a[2::-1])
tyP
Striding - extracting a discontinuous portion of the string
->>> a = "Python Basics"
->>> print(a[2:12:2])
to ai
->>> print(a[-2:-14:-4])
cBh
->>> print(a[-6:len(a):2])
Bsc
->>> print(a[::2])
Pto ais
Programming Practice
6. Count the number of characters in the second half of a user-input string.
7. Count the number of vowels at even index positions.
String methods:
Syntax | Description |
---|---|
s.count(t,start, end) | Returns the number of occurrences of string t in string s (or in the start:end slice of s) |
s.index(t, start, end) | Returns the leftmost position of t in s (or in the start:end slice of s ) or raises ValueError if not found. Use str.rindex() to search from the right. |
s.lower() | Returns a lowercased copy of s |
s.upper() | Returns an uppercased copy of s |
s.islower() | Returns True if all alphabets in s are in lowercase; returns False otherwise; returns False if there are no alphabets |
s.isupper() | Returns True if all alphabets in s are in uppercase; returns False otherwise; returns False if there are no alphabets |
s.strip(chars) | Returns a copy of s with leading and trailing characters in string chars removed |
s.isalpha() | Returns True if s is nonempty and every character in s is an alphabet |
s.split(t, n) | Returns a list of strings splitting at most n times on string t ; if n isn’t given, splits as many times as possible; if t isn’t given, splits on whitespace. |
s.isalnum() | Returns True if s is nonempty and every character in s is alphanumeric |
s.isdigit() | Returns True if s is nonempty and every character in s is an ASCII digit |
->>> a = 'Tyrion Lanister'
->>> a.index("i")
3
->>> a.count("i")
2
->>> a.isupper()
False
->>> print(a.upper())
TYRION LANISTER
->>> s="I have a cat her name is Lit and on the mat she loves to sit"
->>> s[10:].index("a")
3
->>> s[5:-3].count("i")
2
->>> s.split(" ")
['I', 'have', 'a', 'cat', 'her', 'name', 'is', 'Lit', 'and', 'on', 'the', 'mat', 'she', 'loves', 'to', 'sit']
->>> text = "Python Basics"
->>> for i in text:
->>> text = text.lstrip(i)
->>> print(text)
ython Basics
thon Basics
hon Basics
on Basics
n Basics
Basics
Basics
asics
sics
ics
cs
s
Program Examples
1. Segregate upper case alphabets, lower case alphabets, and special characters in a string.
name = "This is Python Basics course; it runs every Thursday!."
lower = ""
upper = ""
special = ""
for i in name:
if (i.isupper()):
lower = lower + i
lower = lower + ","
elif (i.islower()):
upper = upper + i
upper = upper + ","
else:
special = special + i
special = special + ","
print ("""Upper case alphabets: {0} \n Lower case alphabets: {1} \n Special characters: {2}""".format(upper, lower, special))
2. Print the word with the maximum number of alphabets in a string.
text = """This is a very short paragraph which gives no useful information!
The point of this statement is to only make the ""paragraph"" long :). However,
it's time to end it here!"""
max_length = 0
text = text.split(" ")
for i in text:
count = 0
for j in i:
if (j.isalpha()):
count = count + 1
if (count > max_length):
max_length = count
max_word = i
print("{0} is the word with max. length {1}".format(max_word, max_length))
->>> information! is the word with max. length 11
3. Rectify the incorrect format of the following statement - This is a nice morning. we would like to explore. today's weather is great!
s = "This is a nice morning. we would like to explore. today's weather is great!"
new = ""
i = s.split(". ")
for j in i:
if (j[0].islower()):
new = new + j[0].upper() + j[1:] + ". "
else:
new = new + j + ". "
new = new.rstrip(". ")
print(new)
Additional Functions
Syntax | Description |
---|---|
s.find(t,start, end) | Returns the leftmost position of t in s (or in the start:end slice of s ) or -1 if not found. Use str.rfind() to find the rightmost position. See also str.index() |
s.capitalize() | Returns a copy of str s with the first letter capitalized; see also the str.title() method |
s.center(width,char) | Returns a copy of s centered in a string of length width padded with spaces or optionally with char (a string of length 1); see str.ljust() , str.rjust() , and str.format()__ |
s.encode(encoding,err) | Returns a bytes object that represents the string using the default encoding or using the specified encoding and handling errors according to the optional err argument bytes |
s.endswith(x,start, end) | Returns True if s (or the start:end slice of s ) ends with str x or with any of the strings in tuple x ; otherwise, returns False . See also str.startswith(). |
s.expandtabs(size) | Returns a copy of s with tabs replaced with spaces in multiples of 8 or of size if specified |
s.format(...) | Returns a copy of s formatted according to the given arguments. This method and its arguments are covered in the next subsection. |
s.isdecimal() | Returns True if s is nonempty and every character in s is a Unicode base 10 digit |
s.isidentifier() | Returns True if s is nonempty and is a valid identifier |
s.isnumeric() | Returns True if s is nonempty and every character in s is a numeric Unicode character such as a digit or fraction |
s.isprintable() | Returns True if s is empty or if every character in s is considered to be printable, including space, but not newline |
s.isspace() | Returns True if s is nonempty and every character in s is a whitespace character |
s.istitle() | Returns True if s is a nonempty title-cased string; see also str.title() |
s.isupper() | Returns True if str s has at least one uppercaseable character and all its uppercaseable characters are uppercase; see also str.islower() |
s.ljust(width,char) | Returns a copy of s left-aligned in a string of length width padded with spaces or optionally with char (a string of length 1). Use str.rjust() to right-align and str.center() to center. See also str.format() |
s.maketrans() | Companion of str.translate() ; see text for details |
s.partition(t) | Returns a tuple of three strings—the part of str s before the leftmost str t , t , and the part of s after t ; or if t isn’t in s returns s and two empty strings. Use str.rpartition() to partition on the rightmost occurrence of t . |
s.splitlines(f) | Returns the list of lines produced by splitting s on line terminators, stripping the terminators unless f is True |
s.startswith( x, start, end) | Returns True if s (or the start:end slice of s ) starts with str x or with any of the strings in tuple x ; otherwise, returns False . See also str.endswith() . |
s.title() | Returns a copy of s where the first letter of each word is uppercased and all other letters are lowercased; see str.istitle() |
s.translate() | Companion of str.maketrans() ; see text for details |
s.zfill(w) | Returns a copy of s , which if shorter than w is padded with leading zeros to make it w characters long |
s.swapcase() | Returns a copy of string s with uppercase characters lowercased and lowercase characters uppercased |
s.replace(t, u, n) | Returns a copy of s with every (or a maximum of n if given) occurrences of string t replaced with string u |
s.join(seq) | Returns the concatenation of every item in the sequence seq , with string s (which may be empty) between each one |
Programming Practice
7. Below is a statement with unwanted non-alphabetic characters typed at the end. Write a Python program to truncate the unwanted characters.
This is a very short paragraph which gives no useful information!
The point of this statement is to only make the ""paragraph"" long :).
However, it's time to end it here.!#$#$#$#!@..&%()(*^@7#$#