0% found this document useful (0 votes)
3 views

Data-types-variables

The document covers fundamental concepts in Python programming, including data types, variables, input/output operations, and the print() function. It explains how to write and run simple Python programs, the nature of literals, and the distinction between positional and keyword arguments in functions. Additionally, it discusses different numeric types such as integers and floats, as well as string handling and Boolean values.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Data-types-variables

The document covers fundamental concepts in Python programming, including data types, variables, input/output operations, and the print() function. It explains how to write and run simple Python programs, the nature of literals, and the distinction between positional and keyword arguments in functions. Additionally, it discusses different numeric types such as integers and floats, as well as string handling and Boolean values.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

DATA TYPES, VARIABLES, BASIC INPUT OUTPUT OPERATIONS AND BASIC OPERATORS

At the end of each topic, the students are expected to:

1. how to write and run simple python programs;


2. what Python literals, operators, and expressions are;
3. what variables are and what are the rules that govern them; and
4. how to perform basic input and output operations.

The print() function


Consider the line of codes below:

The word print is a function name. Python functions are flexible and can contain more
content than their mathematical siblings. A function (in this context) is a separate part of the
computer code able to:

• cause some effect (e.g. send text to the terminal, create a file, a draw an image,
or play a sound)
• evaluate a value (e.g. the square root of a value or the length of a given text) and
return it as the function’s result; this is what makes Python functions the
relatives of mathematical concepts
Where do the functions come from?
 They may come from Python itself; the print() is one of this kind; such a function is an
added value received together with Python and its environment (built-in).
 They may come from one or more of Python’s add-ons named modules; some of the
modules come with Python, others may require separate installation.
 As programmer, you can write the functions yourself, placing as many functions as you
want and need inside your program to make it simpler and more elegant.
 It should be noted that the name of the function should be significant.

As mentioned above, a function may have an effect and a result. The third very important
function component is the argument (s). Mathematical functions usually take one argument, e.g.
sin(x), takes an x, which is the measure of the angle. Python functions, on the other hand, are
more versatile. Depending on the individual needs, they may accept any number of arguments -
as many as necessary to perform their tasks. Note: any number includes zero - some Python
functions don't need any argument. Inspite of the number of needed/provided arguments, Python
functions strongly demand the presence of a pair of parentheses - opening and closing ones,
respectively.
DATA TYPES, VARIABLES, BASIC INPUT OUTPUT OPERATIONS AND BASIC OPERATORS

It should be noted that to distinguish ordinary words from function names, place a pair of
empty parentheses after their names, even if the corresponding function wants one or more
arguments. This is a standard convention. Consider print (“Hello World”), the only argument
delivered to the print() is a string which is delimited with quotes. Anything put inside the quotes
will be taken literally not as codes, but as data.

Three Important Questions about print ()


1. What is the effect the print () function causes?
• takes its arguments (it may accept more than one argument and may also accept less
than one argument)
• converts them into human-readable form if needed (as you may suspect, strings don't
require this action, as the string is already readable)
• and sends the resulting data to the output device (usually the console); in other
words, anything you put into the print() function will appear on your screen.

2. What arguments does print () expect?

Any arguments. print() is able to operate with virtually all types of data offered by Python.
Strings, numbers, characters, logical values, objects - any of these may be successfully
passed to print().

3. What value does the print () return?

None. The effect is enough.

The print () function - instructions

 Python requires that there cannot be more than one instruction in a line.
 A line can be empty (i.e., it may contain no instruction at all) but it must not contain two,
three or more instructions. This is strictly prohibited.
 Note: Python makes one exception to this rule - it allows one instruction to spread across
more than one line (which may be helpful when your code contains complex
constructions).

The print () function – the escape and newline characters

 The backslash (\) has a very special meaning when used inside strings - this is
called the escape character.
 The word escape should be understood specifically - it means that the series of
characters in the string escapes for the moment (a very short moment) to introduce a
special inclusion.
 In other words, the backslash doesn't mean anything in itself, but is only a kind of
announcement, that the next character after the backslash has a different meaning too.
 The letter n placed after the backslash comes from the word newline.
DATA TYPES, VARIABLES, BASIC INPUT OUTPUT OPERATIONS AND BASIC OPERATORS

 Both the backslash and the n form a special symbol named a newline character, which
urges the console to start a new output line.
 This convention has two important consequences:

1. If you want to put just one backslash inside a string, don't forget its escaping
nature - you have to double it, e.g., such an invocation will cause an error:

print("\")

while this one won't:

print("\\")

2. Not all escape pairs (the backslash coupled with another character) mean
something.
The print () function – using multiple arguments
Consider the following code, there is one print () function invocation, but it contains three
arguments. All of the arguments are strings.

print("The itsy bitsy spider" , "climbed up" , "the waterspout.")

The arguments are separated by commas. There are spaces between arguments to
make them more visible, but it's not really necessary.The commas separating the arguments play
a completely different role than the comma inside the string. The former is a part of Python's
syntax, the latter is intended to be shown in the console.

Take note of the following reminders:

• a print() function invoked with more than one argument outputs them all on one line;
• the print() function puts a space between the outputted arguments on its own initiative.

The print() function - the positional way of passing the arguments

The way in which we are passing the arguments into the print() function is the most
common in Python, and is called the positional way (this name comes from the fact that the
meaning of the argument is dictated by its position, e.g., the second argument will be outputted
after the first, not the other way round).

The print() function - the keyword arguments

Python offers another mechanism for the passing of arguments, which can be helpful
when you want to convince the print() function to change its behavior a bit.
DATA TYPES, VARIABLES, BASIC INPUT OUTPUT OPERATIONS AND BASIC OPERATORS

The mechanism is called keyword arguments. The name stems from the fact that the
meaning of these arguments is taken not from its location (position) but from the special word
(keyword) used to identify them.

The print() function has two keyword arguments that you can use for your purposes. The
first of the keywords is called end.

In order to use end, it is necessary to know some rules:

• a keyword argument consists of three elements: a keyword identifying the argument


(end here); an equal sign (=); and a value assigned to that argument;
• any keyword arguments have to be put after the last positional argument (this is very
important)

The end keyword argument determines the characters the print() function sends to the
output once it reaches the end of its positional arguments.

The print() function separates its outputted arguments with spaces. This behavior can be
changed, too. The keyword argument that can do this is named sep (like separator).
Consider the following codes:

print (“My”, “name”, “is”, “Monty”, “Python”, sep = “-” )

Through, the use of the print() function, shown above, the print () function uses a dash,
instead of a space, to separate the outputted arguments. Also, both sep and end keyword
arguments may be mixed in one invocation, just like here in the editor window.

Key takeaways on print () function

1. The print() function is a built-in function. It prints/outputs a specified message to the


screen/consol window.

2. Built-in functions, contrary to user-defined functions, are always available and don't have to be
imported. Python 3.8 comes with 69 built-in functions. You can find their full list provided in
alphabetical order in the Python Standard Library.

3. To call a function (this process is known as function invocation or function call), you need
to use the function name followed by parentheses. You can pass arguments into a function by
placing them inside the parentheses. You must separate arguments with a comma,
e.g., print("Hello,", "world!"). An "empty" print() function outputs an empty line to the screen.

4. Python strings are delimited with quotes, e.g., "I am a string" (double quotes), or 'I am a string,
too' (single quotes).

5. Computer programs are collections of instructions. An instruction is a command to perform a


specific task when executed, e.g., to print a certain message to the screen.
DATA TYPES, VARIABLES, BASIC INPUT OUTPUT OPERATIONS AND BASIC OPERATORS

6. In Python strings the backslash (\) is a special character which announces that the next
character has a different meaning, e.g., \n (the newline character) starts a new output line.

7. Positional arguments are the ones whose meaning is dictated by their position, e.g., the
second argument is outputted after the first, the third is outputted after the second, etc.

8. Keyword arguments are the ones whose meaning is not dictated by their location, but by a
special word (keyword) used to identify them.

9. The end and sep parameters can be used for formatting the output of the print() function.
The sep parameter specifies the separator between the outputted arguments (e.g., print("H", "E",
"L", "L", "O", sep="-"), whereas the end parameter specifies what to print at the end of the print
statement.

Literals

 A literal is data whose values are determined by the literal itself.


 There are 2 different types of literals: 1) the string; and 2) an integer number.
The print() function presents them in exactly the same way.
 In the computer's memory, these two values are stored in completely different ways - the
string exists as just a string - a series of letters.
 The number is converted into machine representation (a set of bits).

Integers

 The numbers handled by modern computers are of two types:

1. integers, that is, those which are devoid of the fractional part;
2. and floating-point numbers (or simply floats), that contain (or are able to contain) the
fractional part.

 The characteristic of the numeric value which determines its kind, range, and application,
is called the type.
 Python allows the use of underscores in numeric literals like the number 11111111 can
be written as 11_111_111.
 Python 3.6 has introduced underscores in numeric literals, allowing for placing single
underscores between digits and after base specifiers for improved readability. This feature
is not available in older versions of Python.
 Negative numbers are coded in Python by adding a “-” (e.g. -11111111, or -11_111_111)

Integers: octal and hexadecimal numbers

 Python allows the use of numbers in an octal representation.


 If an integer number is preceded by an 0O or 0o prefix (zero-o), it will be treated as an
octal value. This means that the number must contain digits taken from the [0..7] range
only. 0o123 is an octal number with a (decimal) value equal to 83.
 The print() function does the conversion automatically. (e.g. print(0o123))
DATA TYPES, VARIABLES, BASIC INPUT OUTPUT OPERATIONS AND BASIC OPERATORS

 Python allows the use of hexadecimal numbers. Such numbers should be preceded by
the prefix 0x or 0X (zero-x).
 0x123 is a hexadecimal number with a (decimal) value equal to 291. The print()
function can manage these values too. (e.g. print(0x123))

Floats

 Floating-point numbers are numbers that have (or may have) a fractional part after the
decimal point.
 The point is what makes a float.
 The letter e makes a float. When numbers are very large, scientific notation may be
used. Take for example, 300000000 in Python, it is represented as 3E8. Both small
letter e and capital letter E maybe used.
 The exponent (the value after the E) has to be an integer.
 The base (the value in front of the E) may be an integer.
 As a reminder, Python always chooses the more economical form of the number's
presentation.

Strings

 Strings are used when you need to process text (like names of all kinds, addresses,
novels, etc.), not numbers.
 In strings, the catch is how to encode a quote inside a string which is already delimited by
quotes. without generating an error? There are two possible solutions: The first is based
on the concept of the escape character, which is played by the backslash. The
backslash can escape quotes too. A quote preceded by a backslash changes its meaning
- it's not a delimiter, but just a quote. The following line of code is an example and take
note that there are two escaped quotes inside the string

print("I like \"Monty Python\"")

 The second solution may be a bit surprising. Python can use an apostrophe instead of
a quote. Either of these characters may delimit strings, but should be consistent. If you
open a string with a quote, you have to close it with a quote. If you start a string with an
apostrophe, you have to end it with an apostrophe. The following line of code is the
example:

print('I like "Monty Python"')

 A string may also be empty. It may contain no characters at all. (e.g. ‘ ‘ and “ ”)
DATA TYPES, VARIABLES, BASIC INPUT OUTPUT OPERATIONS AND BASIC OPERATORS

Boolean values

 Each time you ask Python if one number is greater than another, the question results in
the creation of some specific data - a Boolean value.
 The name comes from George Boole (1815-1864), the author of the fundamental
work, The Laws of Thought, which contains the definition of Boolean algebra - a part of
algebra which makes use of only two distinct values: True and False, denoted
as 1 and 0.
 Computers know only two kinds of answers:

• Yes, this is true;


• No, this is false.

 True and False are also case-sensitivite.

Key takeaways

1. Literals are notations for representing some fixed values in code. Python has various types of
literals - for example, a literal can be a number (numeric literals, e.g., 123), or a string (string
literals, e.g., "I am a literal.").

2. The binary system is a system of numbers that employs 2 as the base. Therefore, a binary
number is made up of 0s and 1s only, e.g., 1010 is 10 in decimal.

Octal and hexadecimal numeration systems, similarly, employ 8 and 16 as their bases
respectively. The hexadecimal system uses the decimal numbers and six extra letters.

3. Integers (or simply ints) are one of the numerical types supported by Python. They are
numbers written without a fractional component, e.g., 256, or -1 (negative integers).

4. Floating-point numbers (or simply floats) are another one of the numerical types supported
by Python. They are numbers that contain (or are able to contain) a fractional component,
e.g., 1.27.

5. To encode an apostrophe or a quote inside a string you can either use the escape character,
e.g., 'I\'m happy.', or open and close the string using an opposite set of symbols to the ones you
wish to encode, e.g., "I'm happy." to encode an apostrophe, and 'He said "Python", not
"typhoon"' to encode a (double) quote.

6. Boolean values are the two constant objects True and False used to represent truth values
(in numeric contexts 1 is True, while 0 is False.
DATA TYPES, VARIABLES, BASIC INPUT OUTPUT OPERATIONS AND BASIC OPERATORS

Basic operators

 An operator is a symbol of the programming language, which is able to operate on the


values.
 The most widely recognized arithmetic operations: The order of their appearance is not
accidental. Remember that data and operators when connected together
form expressions. The simplest expression is a literal itself.

+, -, *, /, //, %, **

Arithmetic operators: exponentiation

 A ** (double asterisk) sign is an exponentiation (power) operator. Its left argument is


the base, its right, the exponent.
 Classical mathematics prefers notation with superscripts, just like this: 23. Pure text
editors don't accept that, so Python uses ** instead, e.g., 2 ** 3.
 Remember that: 1) when both ** arguments are integers, the result is an integer, too;
but 2) when at least one ** argument is a float, the result is a float, too.

Arithmetic operators

 An * (asterisk) sign is a multiplication operator.


 A / (slash) sign is a divisional operator. The value in front of the slash is a dividend,
the value behind the slash, a divisor. The result produced by the division operator
is always a float, regardless of whether or not the result seems to be a float at first
glance: 1 / 2, or if it looks like a pure integer: 2 / 1.
 A // (double slash) sign is an integer divisional operator. It differs from the
standard / operator in two details:

• its result lacks the fractional part - it's absent (for integers), or is always equal to zero
(for floats); this means that the results are always rounded;
• it conforms to the integer vs. float rule.

 The result of integer division is always rounded to the nearest integer value that is less
than the real (not rounded) result. Rounding always goes to the lesser integer.
 Integer division can also be called floor division.

Operators: remainder (modulo)

 Modulo is the the % (percent) sign. The result of the operator is a remainder left after
the integer division.
 As a reminder, division by zero doesn't work. Do not try to: 1) perform a division by
zero; 2) perform an integer division by zero; and 3) find a remainder of a division by
zero.
 The addition operator is the + (plus) sign, which is fully in line with mathematical
standards.
DATA TYPES, VARIABLES, BASIC INPUT OUTPUT OPERATIONS AND BASIC OPERATORS

 The subtraction operator is obviously the - (minus) sign, although you should note that
this operator also has another meaning - it can change the sign of a number. In
subtracting applications, the minus operator expects two arguments: the left
(a minuend in arithmetical terms) and right (a subtrahend).

Operators and their priorities

 Multiplications precede additions.


 The phenomenon that causes some operators to act before others is known as the
hierarchy of priorities.
 Python precisely defines the priorities of all operators, and assumes that operators of a
larger (higher) priority perform their operations before the operators of a lower priority.

Operators and their bindings

 The binding of the operator determines the order of computations performed by some
operators with equal priority, put side by side in one expression.
 Most of Python's operators have left-sided binding, which means that the calculation of
the expression is conducted from left to right.

Operators and their bindings: exponentiation

 The exponentiation operator uses right-sided binding.

List of priorities

 The table below, enumerated the operators in order from the highest (1) to the lowest
(4) priorities.

Priority Operator
1 +, - unary
2 **
3 *, /, //, %
4 +, - binary

Operators and parentheses

 Python allows the use of parentheses, which can change the natural order of a
calculation.
 In accordance with the arithmetic rules, subexpressions in parentheses are always
calculated first.
 Parentheses may be used as needed, and they're often used to improve the
readability of an expression, even if they don't change the order of the operations.
DATA TYPES, VARIABLES, BASIC INPUT OUTPUT OPERATIONS AND BASIC OPERATORS

Key takeaways

1. An expression is a combination of values (or variables, operators, calls to functions - you will
learn about them soon) which evaluates to a value, e.g., 1 + 2.

2. Operators are special symbols or keywords which are able to operate on the values and
perform (mathematical) operations, e.g., the * operator multiplies two values: x * y.

3. Arithmetic operators in Python: + (addition), - (subtraction), * (multiplication), / (classic


division - always returns a float), % (modulus - divides left operand by right operand and returns
the remainder of the operation, e.g., 5 % 2 = 1), ** (exponentiation - left operand raised to the
power of right operand, e.g., 2 ** 3 = 2 * 2 * 2 = 8), // (floor/integer division - returns a number
resulting from division, but rounded down to the nearest whole number, e.g., 3 // 2.0 = 1.0)

4. A unary operator is an operator with only one operand, e.g., -1, or +3.

5. A binary operator is an operator with two operands, e.g., 4 + 5, or 12 % 5.

6. Some operators act before others - the hierarchy of priorities:

• unary + and - have the highest priority


• then: **, then: *, /, and %, and then the lowest priority: binary + and -.

7. Subexpressions in parentheses are always calculated first, e.g., 15 - 1 * (5 * (1 + 2)) = 0.

8. The exponentiation operator uses right-sided binding, e.g., 2 ** 2 ** 3 = 256

Variables

 Variable is the name given to computer memory location to store values in a computer
program.
 The contents of the variable can be varied.
 Variables do not appear in a program automatically. As developer, you must decide how
many and which variables to use in your programs and you must also name them.

Rules in Naming a Python Variable


• the name of the variable must be composed of upper-case or lower-case letters, digits,
and the character _ (underscore)
• the name of the variable must begin with a letter;
• the underscore character is a letter;
• upper- and lower-case letters are treated as different (a little differently than in the real
world - Alice and ALICE are the same first names, but in Python they are two different
variable names, and consequently, two different variables);
• the name of the variable must not be any of Python's reserved words (the keywords -
we'll explain more about this soon).
DATA TYPES, VARIABLES, BASIC INPUT OUTPUT OPERATIONS AND BASIC OPERATORS

 The PEP 8 -- Style Guide for Python Code recommends the following naming
convention for variables and functions in Python:

• variable names should be lowercase, with words separated by underscores to


improve readability (e.g., var, my_variable)
• function names follow the same convention as variable names
(e.g., fun, my_function)
• it's also possible to use mixed case (e.g., myVariable), but only in contexts where
that's already the prevailing style, to retain backwards compatibility with the adopted
convention.

Keywords

Take a look at the list of words that play a very special role in every Python program.

['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else',
'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass',
'raise', 'return', 'try', 'while', 'with', 'yield']

 They are called keywords or (more precisely) reserved keywords. They are reserved
because you mustn't use them as names: neither for your variables, nor functions, nor
any other named entities you want to create.
 The meaning of the reserved word is predefined, and mustn't be changed in any way.
 Fortunately, due to the fact that Python is case-sensitive, you can modify any of these
words by changing the case of any letter, thus creating a new word, which is not
reserved anymore.

More on Variables

 A variable comes into existence as a result of assigning a value to it. Unlike in


other languages, you don't need to declare it in any special way.
 If you assign any value to a nonexistent variable, the variable will be automatically
created.
 The creation (or otherwise - its syntax) is extremely simple: just use the name of the
desired variable, then the equal sign (=) and the value you want to put into the
variable. (e.g. var =1 ; print (var) ).
 You're not allowed to use a variable which doesn't exist (in other words, a variable
that was not assigned a value). This example will cause an error.
 You can use the print() function and combine text and variables using the + operator to
output strings and variables, e.g.: var = "3.8.5" ; print("Python version: " + var)

Assigning a new value to an already existing variable

 The equal sign is in fact an assignment operator. It assigns the value of its right
argument to the left, while the right argument may be an arbitrarily complex expression
involving literals, operators and already defined variables.

You might also like