Unit 1 Notes
Unit 1 Notes
Python is a popular programming language. It was created by Guido van Rossum, and released in
1991.
It is used for:
web development (server-side),
software development,
mathematics,
system scripting.
What can Python do?
Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software development.
Why Python?
Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a functional way.
Good to know
The most recent major version of Python is Python 3, which we shall be using in this tutorial.
However, Python 2, although not being updated with anything other than security updates, is
still quite popular.
In this tutorial Python will be written in a text editor. It is possible to write Python in an
Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which
are particularly useful when managing larger collections of Python files.
Python Syntax compared to other programming languages
Python was designed for readability, and has some similarities to the English language with
influence from mathematics.
Python uses new lines to complete a command, as opposed to other programming languages
which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the scope of loops,
functions and classes. Other programming languages often use curly-brackets for this
purpose.
Example
print("Hello, World!")
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability only, the indentation
in Python is very important.
Python uses indentation to indicate a block of code.
Example
if 5 > 2:
print("Five is greater than two!")
Python will give you an error if you skip the indentation:
Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
The number of spaces is up to you as a programmer, the most common use is four, but it has to be at
least one.
Example
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
You have to use the same number of spaces in the same block of code, otherwise Python will give you
an error:
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Python Variables
In Python, variables are created when you assign a value to it:
Example
Variables in Python:
x=5
y = "Hello, World!"
Python has no command for declaring a variable.
Comments
Creating a Comment
Comments starts with a #, and Python will ignore them:
Example
#This is a comment
print("Hello, World!")
Comments can be placed at the end of a line, and Python will ignore the rest of the line:
A comment does not have to be text that explains the code, it can also be used to prevent Python from
executing code:
Multiline Comments
Python does not really have a syntax for multiline comments.
To add a multiline comment you could insert a # for each line:
Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Or, not quite as intended, you can use a multiline string.
Since Python will ignore string literals that are not assigned to a variable, you can add a multiline
string (triple quotes) in your code, and place your comment inside it:
Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
As long as the string is not assigned to a variable, Python will read the code, but then ignore it, and
you have made a multiline comment.
Python Variables
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.
ExampleGet your own Python Server
x=5
y = "John"
print(x)
print(y)
Variables do not need to be declared with any particular type, and can even change type after they
have been set.
Example
x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Casting
If you want to specify the data type of a variable, this can be done with casting.
Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
Get the Type
You can get the data type of a variable with the type() function.
Example
x=5
y = "John"
print(type(x))
print(type(y))
Single or Double Quotes?
String variables can be declared either by using single or double quotes:
Example
x = "John"
# is the same as
x = 'John'
Case-Sensitive
Variable names are case-sensitive.
Example
This will create two variables:
a=4
A = "Sally"
#A will not overwrite a
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)
A variable name cannot be any of the Python keywords.
ExampleGet your own Python Server
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Example
Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"
Multi Words Variable Names
Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:
Camel Case
Each word, except the first, starts with a capital letter:
myVariableName = "John"
Pascal Case
Each word starts with a capital letter:
MyVariableName = "John"
Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"
The best way to output multiple variables in the print() function is to separate them with commas,
which even support different data types:
Example
x=5
y = "John"
print(x, y)
Global Variables
Variables that are created outside of a function (as in all of the examples above) are known as global
variables.
Global variables can be used by everyone, both inside of functions and outside.
Example
Create a variable outside of a function, and use it inside the function
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
output: Python is awesome
If you create a variable with the same name inside a function, this variable will be local, and can only
be used inside the function. The global variable with the same name will remain as it was, global and
with the original value.
Example
Create a variable inside a function, with the same name as the global variable
x = "awesome"
def myfunc():
x = "fantastic"
print("Python is " + x)
myfunc()
print("Python is " + x)
output Python is fantastic
Python is awesome
The global Keyword
Normally, when you create a variable inside a function, that variable is local, and can only be used
inside that function.
To create a global variable inside a function, you can use the global keyword.
Example
If you use the global keyword, the variable belongs to the global scope:
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
output Python is fantastic
Also, use the global keyword if you want to change a global variable inside a function.
Example
To change the value of a global variable inside a function, refer to the variable by using
the global keyword:
x = "awesome"
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)
output Python is fantastic
To verify the type of any object in Python, use the type() function:
Example
print(type(x))
print(type(y))
print(type(z))
Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
Example Integers:
x=1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Float
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
Example Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
Float can also be scientific numbers with an "e" to indicate the power of 10.
Example Floats:
x = 35e3
y = 12E4
z = -87.7e100
print(type(x))
print(type(y))
print(type(z))
Complex: Complex numbers are written with a "j" as the imaginary part:
Example Complex:
x = 3+5j
y = 5j
z = -5j
print(type(x))print(type(y))print(type(z))
Random Number
Python does not have a random() function to make a random number, but Python has a built-
in module called random that can be used to make random numbers:
Example
Import the random module, and display a random number between 1 and 9:
import random
print(random.randrange(1, 10))
Comparison Operators
Logical Operators
Bitwise Operators
# Examples of Bitwise operators
a = 10
b=4
Identity Operators
Identity operators are used to compare the objects, not if they are equal, but
if they are actually the same object, with the same memory location:
Example
a = 10
b = 20
c=a
print(a is not b)
print(a is c)
Membership Operators
x = 24
y = 20
list = [10, 20, 30, 40, 50]
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
Operator Precedence
Operator precedence describes the order in which operations are performed
If two operators have the same precedence, the expression is evaluated from left to right.
# Output
print("Hello, " + name)
print(type(name))
output
Enter the Numbers : 2 3 4
The Numbers are : 2 3 4
output
GFG
GFG
We can use formatted string literals, by starting a string with f or F before opening
quotation marks or triple quotation marks. In this string, we can write Python expressions
between { and } that can refer to a variable or any literal value.
Example: Python String formatting using F string
# Declaring a variable
name = "Gfg"
print(f'Hello {name}! How are you?')
Output:
Hello Gfg! How are you?
Using format()
We can also use format() function to format our output to make it look presentable. The
curly braces { } work as placeholders. We can specify the order in which variables occur in
the output.
Example: Python string formatting using format() function
# Initializing variables
a = 20
b = 10
# addition
sum = a + b
# subtraction
sub = a- b
Output:
The value of a is 20 and b is 10
30 is the sum of 20 and 10
10 is the subtraction of 20 and 10
if Syntax
if (condition) :
Statement 1
Statement 2
…………
Statement n
if.......elif....... Else
While
While (condition):
statements
ex:
i = 1
while i < 6:
print(i)
i += 1
for A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).
Example:
for i in range(5):
print(i)
for x in "banana":
print(x)
Arguments are used to call a function and there are primarily 4 types of functions that
one can use:
Positional (Required )arguments
Default Arguments
Keyword Arguments
Variable-length arguments (Arbitrary Arguments)
Keyword arguments will invoke the function after the parameters are recognized by
their parameter names. The value of the keyword argument is matched with the
parameter name and so, one can also put arguments in improper order (not in order).
Example:
def display(a,b):
print(a,b)
display(b=20,a=10)
Variable-Length Arguments -In some instances you might need to pass more arguments
than have already been specified. Going back to the function to redefine it can be a tedious
process. Variable-Length arguments can be used instead. These are not specified in the
function’s definition and an asterisk (*) is used to define such arguments.
Example:
def display(*course):
for I in course:
print(I)
display(“MCA”,”MBA”,”BCA”)
Anonymous functions
In Python Function - In Python, an anonymous function means that a function is without a
name. As we already know the def keyword is used to define the normal functions and the
lambda keyword is used to create anonymous functions.
Example :
def cube(x): return x*x*x
cube_v2 = lambda x : x*x*x
print(cube(7))
print(cube_v2(7))