0% found this document useful (0 votes)
5 views25 pages

Chapter 4

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 25

Kingdom of Saudi Arabia ‫المملكة العربية السعودية‬

Ministry of education ‫وزارة التعليم‬


Qassim University ‫جامعة القصيم‬
Applied College ‫الكلية التطبيقية‬

Chapter 4: Python Data Types,


Variables, Operators, and Basic I/O
Operations

1
ITBS103

Your very first program

❑ It's time to start writing some real, working Python code. It'll be very simple for the time being.

❑ The print() function

2
ITBS103

2
Your very first program

❑ String as the print() function's argument


❑ the string is delimited with quotes

❑ Function invocation
❑ The function name (print in this case) along with the parentheses and argument(s), forms the function invocation.

Let's see:
➢ First, Python checks if the name specified is legal (it browses its internal data in order to find an existing function of the
name; if this search fails, Python aborts the code)
➢ second, Python checks if the function's requirements for the number of arguments allows you to invoke the function in this
way (e.g., if a specific function demands exactly two arguments, any invocation delivering only one argument will be
considered erroneous, and will abort the code's execution)
➢ third, Python leaves your code for a moment and jumps into the function you want to invoke; of course, it takes your
argument(s) too and passes it/them to the function;
➢ fourth, the function executes its code, causes the desired effect (if any), evaluates the desired result(s) (if any) and finishes its
task;
➢ finally, Python returns to your code (to the place just after the invocation) and resumes its execution.

3
ITBS103

Your very first program

❑ Examples

❑ As you can see, the empty print() invocation is not as empty as you may have expected ‒ it
does output an empty line, or (this interpretation is also correct) it outputs a newline.
❑ This is not the only way to produce a newline in the output console. We're now going to
4
show you another way.
ITBS103

4
Escape Characters

5
ITBS103

Escape Characters
❑ The print() function has two keyword arguments that you can use for your purposes. The first
is called end.

❑ As you can see, the end keyword argument determines the characters the print() function
sends to the output once it reaches the end of its positional arguments.
❑ The default behavior reflects the situation where the end keyword argument is implicitly used
in the following way: end="\n". 6
ITBS103

6
7
ITBS103

• Positional arguments

• 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).

• print("My name is", "Python.")

• 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.

• 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.

8
ITBS103

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

print("My name is", "Python.", end=" ")

print("Monty Python.")

In order to use it, 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)

In our example, we have made use of the end keyword argument, and set it to a string
containing one space. 9
ITBS103

The keyword argument that can do this is named sep (as in separator).
print("My", "name", "is", "Monty", "Python.", sep="-")

Output:
My-name-is-Monty-Python.

10
ITBS103

10
SECTION SUMMARY

11
ITBS103

11

SECTION SUMMARY

12
ITBS103

12
Understanding Literals in Python

❑ What are Python Literals?


▪ Python literals constant or fixed values in the source code that do not change during the execution of a program.
We can also define Literals as the raw values that are given to Python variables.

▪ Let’s consider the below examples for better understanding:

▪ Literals are a way of representing data types in Python. They can be anything from numbers to textual data,
Boolean values, etc. Let’s discuss the various types of literals

13
ITBS103

13

Understanding Literals in Python

❑ Types of Python Literals


▪ The usage of Python literals varies according to the type. Let’s look at the five types of literals Python has to offer:

▪ Now, let’s talk about each of them in detail:

14
ITBS103

14
Understanding Literals in Python

❑ Numeric Literals

▪ These literals contain only immutable numeric values. By immutable, it implies that one
cannot changes its values during runtime.

▪ From Python 3 onwards, numeric literals have three subtypes:

▪ Integers
▪ Float
▪ Complex

▪ Let’s look at each of them in detail –

15
ITBS103

15

Understanding Literals in Python


Integers
All the natural numbers – negative, zero, or positive are integers. We
can also categorize them into the following types:

▪ Decimal integers – contain digits from 0 to 9. The base for


decimal values is 10.
▪ Binary integers – contain only two digits- 0 and 1. The base for
binary values is 2 and prefixed with “0b”. ➔ bin(5) = 0b101
▪ Octal integers – contain the digits from 0 to 7. The base for octal
values is 8. In Python, the octal values are prefixed with “0o”.
Oct(15)=0o17
▪ Hexadecimal integers – Contain digits from 0 to 9 and alphabets
from A to F. hex(15)=0xf

Consider the below Python examples of integer literals:

16
ITBS103

16
Understanding Literals in Python

Python sees integer and floating-point number in a completely different way.


4 is an integer number, whereas 4.0 is a floating-point number.
The point is what makes a float.

17
ITBS103

17

18
ITBS103

18
Understanding Literals in Python

19
ITBS103

19

Understanding Literals in Python

20
ITBS103

20
Understanding Literals in Python

21
ITBS103

21

how to encode a quote inside a string which is already delimited by


quotes.

1- using The backslash (A quote preceded by a backslash changes its meaning


‒ it's not a delimiter, but just a quote.)

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

2- Python can use an apostrophe instead of a quote.

print('I like "Monty Python"')

22
ITBS103

22
Understanding Literals in Python

Boolean Values
In programming you often need to know if an expression
is True ro False.
You can evaluate any expression in Python, and get one of two
answers, True ro False.
print(10 > 9)
print(10 == 9)
print(10 < 9)

23
ITBS103

23

24
ITBS103

24
• Try it:

• bool(False)
bool(None)
bool(0)
bool("")
bool(())
bool([])
bool({}) 25
ITBS103

25

Variables
❑ Variables are containers for storing data values.
❑ Creating Variables
▪ Python has no command for declaring a variable.
▪ A variable is created the moment you first assign a value to it.
Variables do not need to be declared with any particular type, and
can even change type after they have been set.
Casting
If you want to specify the data type of a variable, this can be done
with casting.

26
ITBS103

26
Operators - data manipulation tools
❑ Basic operators
▪ An operator is a symbol of the programming language, which is able to operate on
the values.

27
ITBS103

27

Operators - data manipulation tools


❑ Examples

28
ITBS103

28
Operators and their priorities
❑ List of priorities

29
ITBS103

29

Operators and their priorities


Examples

print(9 % 6 % 2)

print(2 ** 2 ** 3)

print((5 * ((25 % 13) + 100) / (2 * 13)) // 2)

30
ITBS103

30
SECTION SUMMARY

1) An expression is a combination of values (or variables, operators, calls to functions ‒ you will
learn about them soon) which evaluates to a certain 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.

31
ITBS103

31

SECTION SUMMARY

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

➢ the ** operator (exponentiation) has the highest priority;

➢ then the unary + and - (note: a unary operator to the right of the exponentiation
operator binds more strongly, for example 4 ** -1 equals 0.25)
➢ then: *, /, and %,
➢ and finally, 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.

32
ITBS103

32
Variables – data-shaped boxes

❑ What does every Python variable have?


▪ a name;
▪ a value (the content of the container)
❑ Let's start with the issues related to a variable's name.
❑ Variables do not appear in a program automatically. As a developer, you must decide
how many and which variables to use in your programs.
You must also name them.

33
ITBS103

33

Variable names
❑ If you want to give a name to a variable, you must follow some strict rules:

✓ 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).
34
ITBS103

34
❑ Note that the same restrictions apply to function names.
❑ Python does not impose restrictions on the length of variable names, but that doesn't mean
that a long variable name is always better than a short one.

35
ITBS103

35

Keywords

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

❑ 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.

36
ITBS103

36
37
ITBS103

37

❑ 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.

38
ITBS103

38
Keywords

❑ 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.

print(f"{a} is the first number")


print(f"{a+b+c} is the perimeter")
print(f"{a} + {b} + {c} is the perimeter")
39
ITBS103

39

Shortcut operators

40
ITBS103

40
Comments

❑ Comments – why, when, and how?


➢ Comments can be used to explain Python code.
➢ Comments can be used to make the code more readable.
➢ Comments can be used to prevent execution when testing code.

❑ Creating a Comment
➢ Comments starts with a #, and Python will ignore them:

❑ Multiline Comments

41
ITBS103

41

Interaction with the user


The input() function
❑ We're now going to introduce you to a completely new function, which seems to
be a mirror reflection of the good old print() function.
❑ Why? Well, print() sends data to the console.
❑ The new function gets data from it.
❑ print() has no usable result. The meaning of the new function is to return a very
usable result.

42
ITBS103

42
❑ The input() function is able to read data entered by the user and to return the
same data to the running program.
❑ The program can manipulate the data, making the code truly interactive.
❑ Virtually all programs read and process data. A program which doesn't get a
user's input is a deaf program.
❑ Take a look at our example:

43
ITBS103

43

The input() function

Note:
❑ the input() function is invoked with one argument ‒ it's a string containing a message;
❑ the message will be displayed on the console before the user is given an opportunity to
enter anything;
❑ input() will then do its job.
This variant of the input() invocation simplifies the code and makes it clearer.

44
ITBS103

44
❑ The last line of the sentence explains everything ‒ you tried to apply the ** operator
to 'str' (string) accompanied with 'float'.
❑ This is prohibited.
❑ This should be obvious - can you predict the value of "to be or not to be" raised to the power
of 2?
❑ We can't. Python can't, either.
❑ Have we fallen into a deadlock? Is there a solution to this issue? Of course there is.

45
ITBS103

45

Type casting (type conversions)

46
ITBS103

46
Type casting (type conversions)

47
ITBS103

47

String operators

48
ITBS103

48
Type conversions once again

49
ITBS103

49

You might also like