0% found this document useful (0 votes)
4 views60 pages

Bda24202 Chapter2

The document provides an introduction to the structure of programming languages, focusing on Python, its syntax, data types, and the installation of related IDEs like Anaconda, Jupyter Notebook, and Spyder. It explains how to create and use variables, the importance of indentation, and how to run Python scripts in different modes. Additionally, it covers data type conversion and the basic principles of programming in Python.

Uploaded by

cd240290
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views60 pages

Bda24202 Chapter2

The document provides an introduction to the structure of programming languages, focusing on Python, its syntax, data types, and the installation of related IDEs like Anaconda, Jupyter Notebook, and Spyder. It explains how to create and use variables, the importance of indentation, and how to run Python scripts in different modes. Additionally, it covers data type conversion and the basic principles of programming in Python.

Uploaded by

cd240290
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

BDA24202

COMPUTER
PROGRAMMING
CHAPTER 2
The Structure of Programming Language
2.1 Introduction to Programming Structure
2.2 Basic Syntax and Structure (variables,
comments, indentation)
2.3 Data Types: primitive type & conversion
type
Introduction to Phyton
• Python is a general-purpose programming language in a similar to
other programming languages that you might have heard of such
as C++, JavaScript or Microsoft’s C# and Oracle’s Java.
• The easiest programming language used among developers is
Python.
• This language is open-source, enabling programmers to modify
its source code to fit their needs.
• It is an object-oriented programming language.
• The language has a high-level data structure, and built-in libraries,
that make it easy to use and suitable for rapid application
development.
• It can be used for various tasks, from data analysis and
visualization to web development, prototyping, and automation.
• It has been around for some considerable time having been
originally conceived back in the 1980s by Guido van Rossum at
Centrum Wiskunde & Informatica (CWI) in the Netherlands.
Introduction to Phyton

Term Definition
Open-source software (OSS) Open source means it is free. Phyton
has large community with access to the
software’s code to continuous
development and upgrading
General purpose There is a broad set of field of Phyton-
web programming, analysis of financial
data, analysis of big data and more
High-level Employs syntax closer to human logic,
make the languages easier to learn
Introduction to Phyton
There are several ways in which you can run a Python program, including:

• Interactively using the Python interpreter


• Stored in a file and run using the Python command
• Run as a script file specifying the Python interpreter to use within
the script file
• From within a Python IDE (Integrated Development Environment)
such as PyCharm, Jupyter Notebook , Spyder
Python command

Python interpreter
Download and Install Phyton IDE

Installation of Anaconda Navigator


Anaconda is a free and open-
source distribution of Python and R
• https://www.anaconda.com/ programming languages for
• Select “Individual edition” and click “Download” scientific computing that aims to
• Install according to Operating System (Windows, simplify package management and
MacOS or Linux) deployment.

Installation of related Python IDE and Libraries


Jupyter Notebook and Spyder are quite popular for Python
• List of required Python IDE: IDE. With installed Anaconda distribution, both Jupyter
o Jupyter Notebook and Spyder can be installed together. The selection of
Python IDE totally depends on the developer requirement.
o Spyder Python libraries are ready-to-use prewritten programs
which are required to run common coding tasks.

7
INSTALLING
ANACONDA

8
Installing Jupyter Notebook and Spyder IDE
Use Anaconda Navigator
1. Select suitable environment
2. Scroll the applications and select icon ”Launh” for Jupyter Notebook & Spyder

environment
Installation of Relate Phyton IDE &
Libraries
OPTION 2
Create the environment using Anaconda Prompt
• Open the “Anaconda Prompt (Anaconda3)”
located on Windows Start menu.
OPTION 1
• To create an environment, type “conda create --
Creating the environment using
name myenv” inside the anaconda prompt and
Anaconda Navigator
proceed.
• Click “Create” in
• “myenv” can be replaced by own environment
Environments tab.
name.
Activating the environment
• Activation of conda environment by typing in
“conda activate myenv” in the anaconda prompt.

10
• Open Anaconda navigator
• Choose Environments → Create→ Name environment as
“myenv”→click create
Starting Python using Jupyter
• Open Anaconda navigator → Launch Jupyter
• Your default browser should start (or open a new tab) to the
following URL: http://localhost:8888/tree

Now we are running Notebook server


Starting Python using Jupyter
• As soon as you load the notebook, the Jupyter dashboard opens.
• Each file and directory has a check box next to it.
• By ticking and unticking an item, you could manipulate the respective object
– that means you can duplicate or shutdown a running file.
• By expanding the New button – can create a new text file, a new folder or a
new notebook file.
Creating a Notebook in Jupyter
• Click on the New button (upper right), choose Notebook and it will
open up a list of choices. Choose Phyton 3

• This is webpage to start coding


Can rename notebook
Jupyter Interface for Input/Otput
• Access a cell by pressing “Enter”.
• Once you’ve done that, you’ll be able to see the cursor, so you can start
typing codes.

New cell by press Enter


Jupyter Interface for Input/Otput
• Access a cell by pressing “Enter”.
• Once you’ve done that, you’ll be able to see the cursor, so you can start typing
codes.
Example Greeting Program
• Write following code
print (‘Hello World!’)

• To execute a cell, select the cell and click the Run button
Starting Python using Spyder
• Open Anaconda navigator → Launch Spyder

Now we are running Notebook server


Starting Python using Spyder
Run file button Current folder path

Editor:
Write your script/
instruction here.
Will be executed to
the console Console:
Code execution
directly form script
Introduction to Programming Structure

comment that explains the purpose of the code

import the random module to generate random numbers later


in the program

Define variable

Statement
Python command
Modes of Python Interpreter

Interactive Mode Script Mode


• Interactive mode provides us • This is the normal mode where a
with a quick way of running python code is written in a text
blocks or a single line of Python file with a ‘.py’ extension, and
code. Python interpreter executes the
file.
• The result is immediately
displayed on the Python shell as • The result of the code will be
soon as the Python interpreter displayed after the Python
interprets the command. interpreter runs the file.
Interactive Mode
• Jupyter commonly used for interactive mode

Result display after run without save the file


Script Mode
• Launch Spider in Anaconda navigator
Save the file as hello.py
• Write the code for script mode

Writing coding Now, your file has


been saved in the
folder
Run Script Mode in Spyder
• Lauch Spyder → File→Open→ Choose file Hello.py in the saved
folder
• Click Run icon to execute the file
• Code execution in the console based on script
Example 1:
• Write a program that displays Welcome to Python and
Programming is fun using interactive mode
• The output should be as the following:
Example 1: Solution
Example 2
• Write a program that displays Welcome to Python and
Programming is fun using script mode. Save the file as
Example 2.py.
Example 2: Solution

Writing coding

Output
Variables in Python

• Variables reserved memory locations to store values. This means


that when you create a variable you reserve some space in
memory.
• Based on the data type of a variable, the interpreter allocates
memory and decides what can be stored in the reserved memory.
Therefore, by assigning different data types to variables, you can
store integers, decimals, or characters in these variables.
Variables in Python
• Python variables are simply containers for storing data values -
gives data to the computer for processing.
• Think of a variable as a name attached to a particular object.
• In Python, variables need not be declared or defined in advance, as
is the case in many other programming languages.
• To create a variable, you just assign it a value and then start using
it.
• Assignment is done with a single equals sign (=)

This is read or interpreted as “n is assigned

the value 300.” Once this is done, n can be

used in a statement or expression.


Creating Variables

• Python has no command for declaring a variable.


• A variable is created the moment you first assign a value to it
• Example:

Command/Instruction

Output
Creating Variables
• Variables do not need to be declared with any particular type, and
can even change type after they have been set.
• Example:

1st line x is integer

2nd line x is str

Output read the latest line


Python - Variable Names
• A variable can have a short name (like x and y) or a more
descriptive name (age, carname, total_volume). Rules for Python
variables:
• A variable name must start with a letter or the underscore
character
• A variable name cannot start with a number
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
• Variable names are case-sensitive (age, Age and AGE are three
different variables)
Python - Variable Names
• Example
• Legal variable names:
Using a Variable
• A variable can be used instead of a value:

greeting = "Hello"
planet = "World"
print(greeting, planet)
• The output is:

'Hello World'
• The variables are: ‘greeting’ and ‘planet’
• Any names
Python Data Types
• In programming, data type
is an important concept.
• Variables can store data
of different types, and
different types can do
different things.
• Python has the following
data types built-in by
default, in these
categories:
Example of Writing Data Types in Python
String
Integer
Float
Complex
List
Tuple
Range
Python Numbers
There are three numeric types in Python:

• int
• float
• complex
Python Strings
• Strings in python are surrounded by either single quotation marks,
or double quotation marks.

• 'hello' is the same as "hello".

• You can display a string literal with the print() function


Quotes Inside Quotes

• Can use quotes inside a string, as long as they don't match the
quotes surrounding the string
Assign String to a Variable
• Assigning a string to a variable is done with the variable name
followed by an equal sign and the string:

Variable name Data type: string


Python Casting
• There may be times when you want to specify a type on to a variable. This can
be done with casting.
• Casting in python is therefore done using constructor functions:

• int() - constructs an integer number from an integer literal, a float literal


(by removing all decimals), or a string literal (providing the string
represents a whole number)
• float() - constructs a float number from an integer literal, a float literal or
a string literal (providing the string represents a float or an integer)
• str() - constructs a string from a wide variety of data types, including
strings, integer literals and float literals
Errors
• A variable must be given a value before it is used:
Cell [2] Line 1

• Notice:
• The message is complex – read it carefully
• Only the first error is mentioned
Exercise 1
• Write the following command in Spyder Editor and
observe the output and data type in Variable Explorer
Exercise 1: Solution
• Write the following command in Spyder Editor and observe the
output and data type in Variable Explorer

Editor

In Spyder we can see the data


types that a variable has using the
Variable Explorer

Output
Exercise 2
• What is the output for this coding?
Exercise 2:Solution
• What is the output for this coding?
Assignment
• The statement to set a variable is call ‘assignment’
>>> x = 10
• … can be read as ‘10 is assigned to x’

• How do you read?


>>> x = y

Warning: assignment is not equals


Statement
• A statement represents an action or a sequence of actions.

• The statement print ("Welcome to Python") in the program is a


statement to display the greeting "Welcome to Python“.

LISTING 1.1 Welcome.py


1 # Display two messages It is a statement
(action)
2 print("Welcome to Python")
3 print("Python is fun") It is a statement
(action)

Anatomy of a Python Program 5


Assignment
• “x is assigned the value of y” or “the value of y is assigned to
variable x”

>>> x = y

• How are the two variables used?


• Variable ‘x’ changes value; the value of ‘y’ stays the same
• The value of ‘y’ is used (or read); an error occurs if ‘y’ has
never been given a value.
Comment in Python
• When the Python interpreter sees #, it ignores all text after #
on the same line.

• When it sees ''', it scans for the next ''' and ignores any text
between the triple quotation marks.
• Here are examples of comments:

1 # This program displays Welcome to Python (a line


comment)
It is a comment,
2 ''' This program displays Welcome to Python and so the
3 Python is fun (a paragraph comment) Python interpreter will
4 ''' ignore it when
5 print("Welcome to Python") executing the
6 print("Python is fun") program.

Anatomy of a Python Program 5


Indentation
• The indentation matters in Block 1
Python. Block 2
Block 3
• The following figure is a
Block 2, Continuation
block structure visualizing
Block 1, Continuation
indentation.

• Note that the statements are entered from the first column in the new
line. It would cause an error if the program is typed as follows:

1 # Display two messages It would cause an error


2 print("Welcome to Python") because this statement
has a wrong
3 print("Python is fun") indentation.

Anatomy of a Python Program 5


Caution!
• Don’t put any punctuation at the end of a statement.

• For example, the Python interpreter will report errors for the following
code:

1 # Display two messages


2 print("Welcome to Python").
3 print("Python is fun").

• Python programs are case sensitive.

• It would be wrong, for example, to replace print in the program with Print.

Anatomy of a Python Program 55


Special Symbols

Anatomy of a Python Program 5


Data Type Conversion:
Function Description
int(x [,base]) Converts x to an integer. base specifies the base if x is a string.
long(x [,base] ) Converts x to a long integer. base specifies the base if x is a string.
float(x) Converts x to a floating-point number.
complex(real Creates a complex number.
[,imag])
str(x) Converts object x to a string representation.
repr(x) Converts object x to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(s) Converts s to a tuple.
list(s) Converts s to a list.
set(s) Converts s to a set.
dict(d) Creates a dictionary. d must be a sequence of (key,value) tuples.
frozenset(s) Converts s to a frozen set.
chr(x) Converts an integer to a character.
unichr(x) Converts an integer to a Unicode character.
ord(x) Converts a single character to its integer value.
hex(x) Converts an integer to a hexadecimal string.
oct(x) Converts an integer to an octal string.
Datatype Conversion
• As a matter of fact, we can do various kinds of conversions between
strings, integers and floats using the built-in int, float, and str
functions

>>> x = 10 >>> y = "20" >>> z = 30.0


>>> float(x) >>> float(y) >>> int(z)
10.0 20.0 30
>>> str(x) >>> int(y) >>> str(z)
'10' 20 '30.0'
>>> >>> >>>

integer ➔ float string ➔ float float ➔ integer


integer ➔ string string ➔ integer float ➔ string
References
1. Python Programming, Hans-Petter Halvorsen. ISBN:978-82-
691106-4-7
2. Automate the Boring Stuff with Python, 2nd Edition Practical
Programming for Total Beginners. By Al Sweigart · 2019
Terima kasih

You might also like