Introduction to PythonClass 2 Preethi Agenda Datatypes Math





























- Slides: 29
Introduction to Python-Class 2 Preethi
Agenda • Datatypes • Math Operators • If statements • else and elif statements • Nested Ifs • Testing set of Conditions • Assignments
Datatypes - Numbers Every value in Python has a datatype. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes. Python Numbers: Integers, floating point numbers and complex numbers falls under Python numbers category. They are defined as int, float and complex. Integers can be of any length, it is only limited by the memory available. A floating point number is accurate up to 15 decimal places. Integer and floating points are separated by decimal points. Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part.
Datatypes - List is an ordered sequence of items. It is one of the most used datatype in Python and is very flexible. All the items in a list do not need to be of the same type. We can use the slicing operator [ ] to extract an item or a range of items from a list. Index starts form 0 in Python. Lists are mutable, meaning, value of elements of a list can be altered.
List – Operations Append Insert Del Remove pop
Datatypes - Tuples Tuple is an ordered sequence of items same as list. The only difference is that tuples are immutable. Tuples once created cannot be modified. Tuples are used to write-protect data and are usually faster than list as it cannot change dynamically. It is defined within parentheses () where items are separated by commas.
Datatypes – Strings String is sequence of Unicode characters. We can use single quotes or double quotes to represent strings. Multi-line strings can be denoted using triple quotes, ''' or """. Like list and tuple, slicing operator [ ] can be used with string. Strings are immutable.
Datatypes - Sets Set is an unordered collection of unique items. Set is defined by values separated by comma inside braces { }. Items in a set are not ordered. We can perform set operations like union, intersection on two sets. Set have unique values. They eliminate duplicates. Since, set are unordered collection, indexing has no meaning. Hence the slicing operator [] does not work.
Datatypes – Python Dictionary is an unordered collection of key-value pairs. It is generally used when we have a huge amount of data. Dictionaries are optimized for retrieving data. We must know the key to retrieve the value. In Python, dictionaries are defined within braces {} with each item being a pair in the form key: value. Key and value can be of any type.
Conversion between data types We can convert between different data types by using different type conversion functions like int(), float(), str() etc. Conversion to and from string must contain compatible values. We can even convert one sequence to another. To convert to dictionary, each element must be a pair
Math Operators are special symbols in Python that carry out arithmetic or logical computation. Comparison operators are used to compare values. It either returns True or False according to the condition. Logical operators are the and, or, not operators. Bitwise operators act on operands as if they were string of binary digits. It operates bit by bit, hence the name.
Contd- Math Operators Assignment operators are used in Python to assign values to variables. A = 5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left. Python language offers some special type of operators like the identity operator or the membership operator. in and not in are the membership operators in Python. They are used to test whether a value or variable is found in a sequence (string, list, tuple, set and dictionary).
Operator Meaning Example + Add two operands or unary plus x+y +2 - Subtract right operand from the left or unary minus x-y -2 * Multiply two operands x*y / Divide left operand by the right one (always results into float) x/y % Modulus - remainder of the division of left operand by the right x % y (remainder of x/y) // Floor division - division that results into whole number adjusted to the left in the number line x // y ** Exponent - left operand raised to the power of right x**y (x to the power y) Arithmetic Operators
Comparison Operators Comparision operators in Python Operator Meaning Example > Greater than - True if left operand is greater than the right x>y < Less than - True if left operand is less than the right x<y == Equal to - True if both operands are equal x == y != Not equal to - True if operands are not equal x != y >= Greater than or equal to - True if left operand is greater than or equal to the right x >= y <= Less than or equal to - True if left operand is less than or equal to the right x <= y
Logical operators in Python Operator Meaning Example and True if both the operands are true x and y or True if either of the operands is true x or y not True if operand is false (complements the operand) not x
Bitwise Operators BITWIS E OP ERATORS IN PYTHON Operator Meaning Example & Bitwise AND x& y = 0 (0000) | Bitwise OR x | y = 14 (0000 1110) ~ Bitwise NOT ~x = -11 (1111 0101) ^ Bitwise XOR x ^ y = 14 (0000 1110) >> Bitwise right shift x>> 2 = 2 (0000 0010) << Bitwise left shift x<< 2 = 40 (0010 1000)
Assignment Operators Assignment operators in Python Operator Example Equivatent to = x=5 += x += 5 x=x+5 -= x -= 5 x=x-5 *= x *= 5 x=x*5 /= x /= 5 x=x/5 %= x %= 5 x=x%5 //= x //= 5 x = x // 5 **= x **= 5 x = x ** 5 &= x &= 5 x=x&5 |= x |= 5 x=x|5 ^= x ^= 5 x=x^5 >>= x >>= 5 x = x >> 5 <<= x <<= 5 x = x << 5
Identity Operators Operator Meaning Example is True if the operands are identical (refer to the same object) x is True is not True if the operands are not identical (do not refer to the same object) x is not True
Membership operators Operator Meaning Example in True if value/variable is found in the sequence 5 in x not in True if value/variable is not found in the sequence 5 not in x
Indentation Block can be regarded as the grouping of statements for a specific purpose. One of the distinctive features of Python is its use of indentation to highlight the blocks of code. Whitespace is used for indentation in Python. All statements with the same distance to the right belong to the same block of code. If a block has to be more deeply nested, it is simply indented further to the right.
IF statements The if…else statement is used in Python for decision making. In Python, the body of the if statement is indicated by the indentation. Body starts with an indentation and the first unindented line marks the end. Python interprets non-zero values as True. None and 0 are interpreted as False.
Comparison Operators in IF Equality Operator: Compare two things to see if they're equal. Not Equal to Operator: As the name indicates, its opposite of equality operator. Both the operators can be used to compare numbers, strings, variables, math expressions, and combinations. Both the operators are case-sensitive.
Contd: Comparison operators, that are usually used to compare numbers are: > is greater than < is less than >= is greater than or equal to <= is less than or equal to
If. . else Statement Decision making is required when we want to execute a code only if a certain condition is satisfied. The program evaluates the test expression and will execute statement(s) only if the text expression is True. If the condition is False, body of else is executed. Indentation is used to separate the blocks.
if. . . else Statement The elif is short for else if. It allows us to check for multiple expressions. If the condition for if is False, it checks the condition of the next elif block and so on. If all the conditions are False, body of else is executed. Only one block among the several if. . . else blocks is executed according to the condition. The if block can have only one else block. But it can have multiple elif blocks.
Nested if statements We can have a if. . . else statement inside another if. . . else statement. This is called nesting in computer programming. Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting.
Testing set of Conditions Testing for a combination of conditions is done using the python keywords: and, or and combination of all both mathematical operators and the keywords Example: if age > 65 or (age < 21 and res == "U. K. "):
Assignments Write a Python program to get a single string from two given strings, separated by a space and swap the first two characters of each string. Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself. Sample String : 'restart' Expected Result : 'resta$t’ Given a string and an integer number n, remove characters from a string starting from zero up to n and return a new string
Contd Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string is already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged. Sample String : 'abc' Expected Result : 'abcing' Sample String : 'string' Expected Result : 'stringly’