Python Fundamentals-1
Python Fundamentals-1
BY AMIT PATEL
INTRODUCTION
▪ It is used for:
▪ Data Analysis
▪ Machine Learning
▪ Artificial Intelligence
▪ Web Development Guido van Rossum
▪ Desktop Application
▪ System Programming
INTRODUCTION
▪ Simple and easy to learn and provides lots of high-level data structures.
▪ Python's syntax and dynamic typing make it an ideal language for scripting and rapid application
development.
▪ That is why it is known as multipurpose programming language because it can be used with web,
enterprise, 3D CAD, etc.
because it is dynamically typed. so we can write a=10 to assign an integer value in an integer
variable.
Why Python?
▪ Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
▪ 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.
print("Hello World")
It takes only one statement without using a semicolon or curly braces in Python
Where Python is used?
• Desktop Applications
• Console-based Applications
• Mobile Applications
• Software Development
• Artificial Intelligence
• Web Applications
• Data Science and Machine Learning
• Computer Vision or Image Processing Applications.
• Speech Recognitions
Characteristics of Python
• It is very close to human language like English language so it is called high level language. So
we don’t need to remember syntax in Python.
Easy To Code
• Due to high level language it is very easy to write program in python than other language like c,
c++, c# etc. It is developer friendly language so anybody can easily learn and code in python.
• It means data type is decided at run time not in advance. So no need to declare variable.
Characteristics of Python
Interpreted Language
• Code is executed line by line at a time when we code. There is no need to compile python code.
It makes easy to debug and run. Source code is converted into “Bytecode”.
Portable Language
• It can be run on any platform it means python program written in windows can easily run on Mac
or Linux platform.
Integrated Language
• It has large standard library which provide rich set of functionality so you don’t need to write
separate code.
Open Source
▪ Python programs are typically organized with one statement per line.
▪ The end of the statement delimited by the newline character that marks the end of the line.
▪ There are so many IDE to run python program like Jupiter, PyCharm, VS Code
Structure of Python Programming Language
▪ Python Statements : In general, the interpreter reads and executes the statements line by line
i.e sequentially. Though, there are some statements that can alter this behavior like conditional
statements.
▪ We can also write multiple statements per line, but it is not a good practice as it reduces the
readability of the code.
▪ But, still you can write multiple lines by terminating one statement with the help of ‘;’.
▪ ‘;’ is used as the terminator of one statement in this case.
a = 10; b = 20; c = b + a
print(a); print(b); print(c)
Structure of Python Programming Language
▪ It provides us the feature to execute the Python statement one by one at the interactive prompt.
▪ It is preferable in the case where we are concerned about the output of each line of our Python
program.
▪ To open the interactive mode, open the terminal (or command prompt) and type “python”
▪ It will open the following prompt where we can execute the Python statement and check their
impact on the console.
Structure of Python Programming Language
Here, we get the message "Hello World !" printed on the console.
PYTHON INSTALLATION
Below, you’ll find links to some of the most popular online interpreters.
▪ https://www.python.org/shell/
▪ https://www.onlinegdb.com/online_python_interpreter
▪ https://repl.it/languages/python3
▪ https://www.tutorialspoint.com/execute_python3_online.php
▪ https://rextester.com/l/python3_online_compiler
▪ https://trinket.io/python3
Additional Python resources
Addition Resources
▪ Subscribe to the Python tutor mailing list, where you can ask questions and collaborate with
other Python learners. : https://mail.python.org/mailman/listinfo/tutor
▪ Subscribe to the Python-announce mailing list to read about the latest updates in the
language.: https://mail.python.org/mailman3/lists/python-announce-list.python.org/
▪ https://dabeaz-course.github.io/practical-python/Notes/Contents.html
PYTHON IDLE
▪ Python shell window (interactive interpreter) with colorizing of code input, output, and error messages
▪ Multi-window text editor with multiple undo, Python colorizing, smart indent, call tips, auto completion,
and other features
▪ Search within any window, replace within editor windows, and search through multiple files (grep)
▪ Debugger with persistent breakpoints, stepping, and viewing of global and local namespaces
Structure of Python Programming Language
▪ Using the script mode, we can write multiple lines code into a file which can be executed later.
▪ For this purpose, we need to open an editor like notepad, create a file named and save it
print ("hello world"); #here, we have used print() function to print the message on the console.
▪ To run this file named as first.py, we need to run the following command on the terminal.
Structure of Python Programming Language
Structure of Python Programming Language
Python Code Indention
▪ Indentation is nothing but adding whitespaces before the statement when it is needed.
▪ All statements with the same distance to the right belong to the same block of code.
▪ Without indentation Python doesn't know which statement to be executed to next. Indentation
also defines which statements belong to which block.
▪ Example
if 5 > 2:
print("Five is greater than two!")
Python Code Indention
j=1
while(j<= 5):
print(j)
j=j+1
Print(“Successful…”)
In above example : print (j ) and j=j+1 are block of code of while loop. So both statement must be
with same indention space
Python uses 4 spaces as indentation by default. However, the number of spaces is up to you,
but a minimum of 1 space has to be used.
Line Continuation
▪ Some statements may become very long and may force you to scroll the screen left and right
frequently.
▪ You can fit your code in such a way that you do not have to scroll here and there.
▪ Python allows you to write a single statement in multiple lines, is known as line continuation.
▪ This is the most straightforward technique in writing a statement that spans multiple lines.
▪ Any statement containing opening parentheses (‘(‘), brackets (‘[‘), or curly braces (‘{‘) is
presumed to be incomplete until all matching parentheses, square brackets, and curly braces
have been encountered.
▪ Until then, the statement can be implicitly continued across lines without raising an error.
Line Continuation
print(a)
Output:
[[1, 2, 3], [3, 4, 5], [5, 6, 7]]
Line Continuation
▪ Explicit Line joining is used mostly when implicit line joining is not applicable.
▪ In this method, you have to use a character that helps the interpreter to understand that the
particular statement is spanning more than one lines.
▪ Backslash (\) is used to indicate that a statement spans more than one line.
▪ The point is to be noted that ” must be the last character in that line, even white-space is not
allowed.
Line Continuation
x=\
1+2\
+5+6\
+ 10
print(x)
Output:
24
Comment
▪ Comments start with a #, and Python will render the rest of the line as a comment.
▪ The Python interpreter entirely ignores the lines followed by a hash ( # )character.
▪ A good programmer always uses the comments to make code under stable. Let's see the
following example of a comment.
Importance of Comment
▪ Comments are essential for defining the code and help us and other to understand the code.
▪ By looking the comment, we can easily understand the intention of every line that we have
written in code.
▪ We can also find the error very easily, fix them, and use in other applications.
Triple Quote
▪ 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:
"""
This is a comment
As long as the string is not assigned to a variable,
written in Python will read the code, but then ignore it, and you
more than just one line have made a multiline comment.
"""
print("Hello, World!")
Triple Quote
▪ 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:
"""
This is a comment
As long as the string is not assigned to a variable,
written in Python will read the code, but then ignore it, and you
more than just one line have made a multiline comment.
"""
print("Hello, World!")
Python Identifier
▪ Python identifiers refer to a name used to identify a variable, function, module, class, module or
other objects.
▪ Rules:
▪ A identifier name must start with either an English letter or underscore (_).
▪ A identifier name cannot start with the number.
▪ Special characters are not allowed in the variable name.
▪ The identifier's name is case sensitive.
Python Variable
▪ In Python, we don't need to specify the type of variable because Python is a infer language and
smart enough to get variable type.
▪ Variable names can be a group of both the letters and digits, but they have to begin with a letter
or an underscore.
▪ Python is a dynamically typed language. So, Python doesn't need an explicit variable
declaration to reserve memory. The variable declaration will happen automatically when we
assign value to it.
Python Variable
▪ 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
Creating Variables
▪ Variables do not need to be declared with any particular type, and can even change type after
they have been set.
Example : x = 5
y = "John"
Python Variable
Multiple Assignment
▪ Python allows us to assign a value to multiple variables in a single statement, which is also
known as multiple assignments.
▪ We can apply multiple assignments in two ways, either by assigning a single value to multiple
variables or assigning multiple values to multiple variables. Consider the following example.
Python Variable
X = y = z = 50
print(x)
print(y)
print(z)
Output: 50
50
Python Variable
a,b,c=5,10,15
print a
print b
print c
Output: 5
10
15
▪ The values will be assigned in the order in which variables appear.
Python Variable
Output Variable
Example
x = "awesome"
print("Python is “ , x)
Output
Python is awesome
Python Variable
Output Variable
▪ You can also use the + character to add a variable to another variable:
Example
x = "Python is "
y = "awesome" Output
print(z)
Python Variable
Output Variable
▪ If you try to combine a string and a number, Python will give you an error:
Example
x=5
Output
y = "John"
TypeError: unsupported operand type(s) for +: 'int' and 'str'
print(x + y)
Python Global Variable
▪ 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
x = “VTCBB"
def myfunc():
print("Python is " , x) Output
myfunc() //function call VTCBB
Python Global Variable
▪ 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.
x = “vtcbb"
def myfunc() :
x = "fantastic"
print("Python is " + x) Output
Delete Variable
del <variable_name>
▪ In the following example, we create a variable x and assign value to it. We deleted variable x,
and print it, we get the error "variable x is not defined". The variable x will no longer use in future.
Python Variable
▪ Example -
# Assigning a value to x
x=6
print(x)
# deleting a variable.
del x
print(x)
Python Variable
Output:
6
Traceback (most recent call last):
File "C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/multiprocessing.py", line 389, in
print(x)
NameError: name 'x' is not defined
print ( )
▪ Prints the message to the screen or any other standard output device.
Parameters:
value(s) : Any value, and as many as you like. Will be converted to string before printed
sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than one. Default :’ ‘
▪ For Example:
print("Python is fun.")
a=5
# Two objects are passed
print("a =", a)
Output:
b=a
Python is fun.
# Three objects are passed
a=5
print('a =', a, '= b') a=5=b
print ( )
▪ For Example:
print('Printing in a Nutshell', end='\n * ')
print('hello', 'world', sep='\n')
print('Calling Print', end='\n * ')
Output:
print('Separating Multiple Arguments', end='\n * ')
hello print('Preventing Line Breaks')
world
Output:
Printing in a Nutshell
* Calling Print
* Separating Multiple Arguments
* Preventing Line Breaks
Python Data Type
1. Numbers
2. String
3. List
4. Tuple
5. Dictionary
Python Data Type : Number
▪ They are immutable data types, means that changing the value of a number data type
results in a newly allocated object.
▪ For example :
var1 = 1
var2 = 10
Python Data Type : Number
▪ Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has
no restriction on the length of an integer.
▪ Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is accurate
upto 15 decimal points.
▪ complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote the
real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j, etc.
Python Data Type : Number
▪ Python provides the type() function to know the data-type of the variable.
▪ Similarly, the isinstance() function is used to check an object belongs to a particular class.
For example:
a=5
For example :
▪ Python does not support a character type; these are treated as strings of length one, thus
also considered a substring.
▪ To access substrings, use the square brackets for slicing along with the index or indices to
obtain your substring.
For example :
Output:
var1[0]: H
var2[1:5]: ytho
Python Data Type : String
print (str1 + str2) #printing the concatenation of str1 and str2 🡪hello Python how are you
Python Data Type : String
str = ‘VTCBCSR'
print(str[-1])
print(str[-3])
print(str[-2:])
Output:
print(str[-4:-1]) R
C
print(str[::-1]) SR
BCS
print(str[-12]) RSCBCTV
IndexError: string index out of range
Python Data Type : String
▪ The new value can be related to its previous value or to a completely different string
altogether.
For example:
+ Concatenation - Adds values on either side of the operator a + b will give HelloPython
* Repetition - Creates new strings, concatenating multiple copies a*2 will give -HelloHello
of the same string
[] Slice - Gives the character from the given index a[1] will give e
[:] Range Slice - Gives the characters from the given range a[1:4] will give ell
not in Membership - Returns true if a character does not exist in the M not in a will give 1
given string
Python Data Type : String
Triple-Quoted Strings
▪ Triple-quoted strings are delimited by matching groups of three single quotes or three
double quotes.
▪ Single quotes, double quotes, and newlines can be included without escaping them.
▪ This provides a convenient way to create a string with both single and double quotes in it.
Python Data Type : String
Output: This string has a single (') and a double (") quote.
\
Python Data Type : String
Triple-Quoted Strings
▪ Because newlines can be included without escaping them, this also allows for multiline
strings:
▪ For example:
print("""This is a Output:
▪ The items stored in the list are separated with a comma (,) and enclosed within square
brackets [ ].
▪ For Example:
▪ For Example:
a = [1,”om”, “sai”,80 ]
▪ Lists are mutable, meaning, the value of elements of a list can be altered.
▪ For Example:
a = [1,”om”, “sai”,80 ]
a[2]=“ram”
print (a) 🡪 [1,”om”,”ram”,80]
Python Data Type : List [ LBM ]
▪ Lists are mutable, meaning, the value of elements of a list can be altered.
▪ For Example:
a = [1,”om”, “sai”,80 ]
a[2]=“ram”
print (a) 🡪 [1,”om”,”ram”,80]
Python Data Type : Tuple [TPIm]
▪ A tuple is a read-only data structure as we can't modify the size and value of the items of a
tuple.
▪ Tuples are used to write-protect data and are usually faster than lists as they cannot change
dynamically.
Python Data Type : Tuple
▪ For Example
▪ It is like an associative array or a hash table where each key stores a specific value.
▪ Key can hold any primitive data type, whereas value is an arbitrary Python object.
▪ When to used? When we have a huge amount of data. Dictionaries are optimized for
retrieving data. We must know the key to retrieve the value.
▪ Dictionaries are defined within braces { } with each item being a pair in the form “key:value”.
Key and value can be of any type.
Python Data Type : Dictionary
▪ It is like an associative array or a hash table where each key stores a specific value.
▪ When to used? When we have a huge amount of data. Dictionaries are a great tool for
counting elements and analyzing frequency
▪ Dictionaries are defined within braces { } with each item being a pair in the form “key:value”.
Key and value can be of any type.
# Printing dictionary
▪ The process of converting the value of one data type (integer, string, float, etc.) to another
data type is called type conversion.
▪ In Implicit type conversion, Python automatically converts one data type to another data type.
This process doesn't need any user involvement.
num_int = 123
When we run the above program, the output will be:
num_flo = 1.23 datatype of num_int: <class 'int'>
print("datatype of num_flo:",type(num_flo))
Explicit Type Conversion
▪ In Explicit Type Conversion, users convert the data type of an object to required data type.
▪ We use the predefined functions like int(), float(), str(), etc to perform explicit type
conversion.
▪ This type of conversion is also called typecasting because the user casts (changes) the
data type of the objects.
▪ Syntax : <required_datatype> (expression)
▪ Typecasting can be done by assigning the required data type function to the expression.
Implicit Type Conversion
num_int = 123 When we run the above program, the output will be:
num_str = "456“ Data type of num_str after Type Casting: <class 'int'>
▪ Type Conversion is the conversion of object from one data type to another data type.
▪ Explicit Type Conversion is also called Type Casting, the data types of objects are
converted using predefined functions by the user.
▪ In Type Casting, loss of data may occur as we enforce the object to a specific data type.
Input & Output
▪ The input() method reads a line from input, converts into a string and returns it.
prompt (Optional) - a string that is written to standard output (usually screen) without trailing
newline
▪ Return value: The input() method reads a line from the input (usually from the user),
converts the line into a string by removing the trailing newline, and returns it.
Example:
▪ The print() function to output data to the standard output device (screen).
▪ Example:
print(‘VTCBB') Output:
VTCBB
a=5
The value of a is 5
print('The value of a is', a)
Input & Output : print()
▪ The sep separator is used between the values. It defaults into a space character.
▪ After all values are printed, end is printed. It defaults into a new line.
▪ The file is the object where the values are printed and its default value
is sys.stdout (screen).
Input & Output : print()
▪ Example: Output:
print(1, 2, 3, 4) 1234