What is Python?
Basic Programming with • Python is a popular programming language. It was created by Guido
van Rossum, and released in 1991.
Python
• It is used for:
• web development (server-side),
• software development,
Utsha Das • mathematics,
Lecturer • system scripting.
Department of CSE, RUET
What can Python do? Why Python?
• Python can be used on a server to create web applications. • Python works on different platforms (Windows, Mac, Linux,
Raspberry Pi, etc).
• Python can be used alongside software to create workflows.
• Python has a simple syntax similar to the English language.
• Python can connect to database systems. It can also read and modify
files. • Python has syntax that allows developers to write programs with fewer
lines than some other programming languages.
• Python can be used to handle big data and perform complex • Python runs on an interpreter system, meaning that code can be
mathematics. executed as soon as it is written. This means that prototyping can be
• Python can be used for rapid prototyping, or for production-ready very quick.
software development. • Python can be treated in a procedural way, an object-oriented way or a
functional way.
Python Syntax compared to other
Good to know
programming languages
• The most recent major version of Python is Python 3, which we shall • Python was designed for readability, and has some similarities to the
be using in this tutorial. However, Python 2, although not being English language with influence from mathematics.
updated with anything other than security updates, is still quite • Python uses new lines to complete a command, as opposed to other
popular. programming languages which often use semicolons or parentheses.
• In this tutorial Python will be written in a text editor. It is possible to • Python relies on indentation, using whitespace, to define scope; such
write Python in an Integrated Development Environment, such as as the scope of loops, functions and classes. Other programming
Thonny, Pycharm, Netbeans or Eclipse which are particularly useful languages often use curly-brackets for this purpose.
when managing larger collections of Python files.
Example Execute Python Syntax
print("Hello, World!") • As we learned in the previous page, Python syntax can be executed by
writing directly in the Command Line:
>>> print("Hello, World!")
Hello, World!
• Or by creating a python file on the server, using the .py file extension,
and running it in the Command Line:
Python Indentation Python Indentation Cont.
• Indentation refers to the spaces at the beginning of a code line. • Python will give you an error if you skip the indentation:
• Where in other programming languages the indentation in code is for • Syntax Error:
readability only, the indentation in Python is very important.
• Python uses indentation to indicate a block of code. if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
Python Indentation Cont. Python Indentation Cont.
• The number of spaces is up to you as a programmer, the most common • You have to use the same number of spaces in the same block of code,
use is four, but it has to be at least one. otherwise Python will give you an error:
• Syntax Error:
if 5 > 2:
print("Five is greater than two!") if 5 > 2:
if 5 > 2: print("Five is greater than two!")
print("Five is greater than two!") print("Five is greater than two!")
Python Variables Comments
• In Python, variables are created when you assign a value to it: • Python has commenting capability for the purpose of in-code
documentation.
x=5 • Comments start with a #, and Python will render the rest of the line as
a comment:
y = "Hello, World!“
#This is a comment.
• Python has no command for declaring a variable.
print("Hello, World!")
Creating a Comment Multiline Comments
• Comments starts with a #, and Python will ignore them: • Python does not really have a syntax for multiline comments.
#This is a comment • To add a multiline comment you could insert a # for each line:
print("Hello, World!")
• Comments can be placed at the end of a line, and Python will ignore the rest
of the line: #This is a comment
print("Hello, World!") #This is a comment #written in
• A comment does not have to be text that explains the code, it can also be #more than just one line
used to prevent Python from executing code:
#print("Hello, World!")
print("Hello, World!")
print("Cheers, Mate!")
Multiline Comments Cont. Creating Variables
• Or, not quite as intended, you can use a multiline string. • Python has no command for declaring a variable.
• Since Python will ignore string literals that are not assigned to a variable, • A variable is created the moment you first assign a value to it.
you can add a multiline string (triple quotes) in your code, and place your
comment inside it:
""" x=5
This is a comment y = "John"
written in
print(x)
more than just one line
"""
print(y)
print("Hello, World!")
Creating Variables Cont. Casting
• Variables do not need to be declared with any particular type, and can • If you want to specify the data type of a variable, this can be done with
even change type after they have been set. casting.
x=4 # x is of type int x = str(3) # x will be '3'
x = "Sally" # x is now of type str y = int(3) # y will be 3
print(x) z = float(3) # z will be 3.0
Get the Type Single or Double Quotes?
• You can get the data type of a variable with the type() function. • String variables can be declared either by using single or double
quotes:
x=5
y = "John" x = "John"
print(type(x)) # is the same as
print(type(y)) x = 'John'
Case-Sensitive Variable Names
• Variable names are case-sensitive. • 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=4 • A variable name must start with a letter or the underscore character
A = "Sally" • A variable name cannot start with a number
#A will not overwrite a • 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)
• A variable name cannot be any of the Python keywords.
Example : Legal Variable Names Example
myvar = "John" • Illegal variable names:
my_var = "John"
_my_var = "John" 2myvar = "John"
myVar = "John" my-var = "John"
MYVAR = "John" my var = "John"
myvar2 = "John"
Multi Words Variable Names Camel Case
• Variable names with more than one word can be difficult to read. • Each word, except the first, starts with a capital letter:
• There are several techniques you can use to make them more readable:
myVariableName = "John"
Pascal Case Snake Case
• Each word starts with a capital letter: • Each word is separated by an underscore character:
MyVariableName = "John" my_variable_name = "John"
Many Values to Multiple Variables One Value to Multiple Variables
• Python allows you to assign values to multiple variables in one line: • And you can assign the same value to multiple variables in one line:
x, y, z = "Orange", "Banana", "Cherry" x = y = z = "Orange"
print(x) print(x)
print(y) print(y)
print(z) print(z)
Unpack a Collection Output Variables
• If you have a collection of values in a list, tuple etc. Python allows you • The Python print() function is often used to output variables.
to extract the values into variables. This is called unpacking.
x = "Python is awesome"
fruits = ["apple", "banana", "cherry"] print(x)
x, y, z = fruits
print(x)
print(y)
print(z)
Output Variables Cont. Output Variables Cont.
• In the print() function, you output multiple variables, separated by a • You can also use the + operator to output multiple variables:
comma:
x = "Python "
x = "Python" y = "is "
y = "is" z = "awesome"
z = "awesome" print(x + y + z)
print(x, y, z)
Output Variables Cont. Output Variables Cont.
• For numbers, the + character works as a mathematical operator: • In the print() function, when you try to combine a string and a number
with the + operator, Python will give you an error:
x=5
y = 10 x=5
print(x + y) y = "John"
print(x + y)
Output Variables Cont. Global Variables
• The best way to output multiple variables in the print() function is to • Variables that are created outside of a function (as in all of the
separate them with commas, which even support different data types: examples in the previous pages) are known as global variables.
• Global variables can be used by everyone, both inside of functions and
x=5 outside.
y = "John"
print(x, y) x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
Global Variables Cont. The global Keyword
• If you create a variable with the x = "awesome" • Normally, when you create a variable inside a function, that variable is
same name inside a function, this def myfunc(): local, and can only be used inside that function.
variable will be local, and can • To create a global variable inside a function, you can use the global
only be used inside the function. x = "fantastic"
keyword.
The global variable with the print("Python is " + x)
same name will remain as it was, def myfunc():
myfunc()
global and with the original global x
value. print("Python is " + x)
x = "fantastic"
myfunc()
print("Python is " + x)
The global Keyword Cont. Built-in Data Types
• Also, use the global keyword if you want to change a global variable • In programming, data type is an important concept.
inside a function.
• Variables can store data of different types, and different types can do
different things.
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
Built-in Data Types Cont. Getting the Data Type
• Python has the following data types built-in by default, in these • You can get the data type of any object by using the type() function:
categories:
• Text Type: str
• Numeric Types: int, float, complex
x=5
• Sequence Types:list, tuple, range print(type(x))
• Mapping Type: dict
• Set Types: set, frozenset
• Boolean Type: bool
• Binary Types: bytes, bytearray, memoryview
• None Type: NoneType
Setting the Data Type Setting the Data Type Cont.
• In Python, the data type is set when you assign a value to a variable: • In Python, the data type is set when you assign a value to a variable:
Example Data Type Example Data Type
x = "Hello World" str x = frozenset({"apple", "banana", "cherry"}) frozenset
x = 20 int x = True bool
x = 20.5 float x = b"Hello" bytes
x = 1j complex x = bytearray(5) bytearray
x = ["apple", "banana", "cherry"] list x = memoryview(bytes(5)) Memoryview
x = ("apple", "banana", "cherry") tuple x = None NoneType
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} Set
Setting the Specific Data Type Setting the Specific Data Type Cont.
• If you want to specify the data type, you can use the following • If you want to specify the data type, you can use the following
constructor functions: constructor functions:
Example Data Type
x = str("Hello World“) str Example Data Type
x = int(20) int x = frozenset({"apple", "banana", "cherry"}) frozenset
x = float(20.5) float x = bool(5) bool
x = complex(1j) complex x = bytes(5) bytes
x = list(["apple", "banana", "cherry"]) list x = bytearray(5) bytearray
x = tuple(("apple", "banana", "cherry")) tuple x = memoryview(bytes(5)) Memoryview
x = range(6) range
x = dict({"name" : "John", "age" : 36}) dict
x = set(("apple", "banana", "cherry“)) Set
Python input() Function More Examples
• Ask for the user's name and print it: • Use the prompt parameter to write a message before the input:
print('Enter your name:') x = input('Enter your name:')
x = input() print('Hello, ' + x)
print('Hello, ' + x)
Thank You