Python Basics 1
Python Basics 1
Python Basics 1
1
INDEX:
5. KEYWORDS 14-16
6. PYTHON-VARIABLES 16-23
NOTE: If you really strong in the basics, then remaining things will
become so easy
2
INTRODUCTION:
1. WHAT IS PYTHON ?
- By simply seeing the code, programmer can understand the program. He can write the code
very easily.
- High level languages are Programmer friendly languages but not machine friendly languages
a = 10
b = 20
c = 30
if (a<b):
print('true')
else:
print('false')
Output: true
Do you Know, if we can take this code, are in a position to understand this code?
Yes,You are not required to have any programming knowledge.
By observing the code you can say that, the output is true.
This type of thing is called as High level programming.
3
-Why Python is called as Interpreted Language?
Python is an interpreted language, which means that the code is executed line by line,
rather than being compiled all at once. This has several advantages, including faster development
time and easier debugging.
Before learning about Python interpreter and how it works, let us start by discussing what
an interpreter is.
WHAT IS INTERPRETER?
An Interpreter is a program that converts the code a developer writes into an intermediate
language, called the byte code. It converts the code line by line, one at a time. It translates
till the end and stops at that line where an error occurs, if any, making the debugging process easy.
1. *Code Compilation*: Python code (e.g., "Hello, World!") is translated into bytecode, a
binary format.
3. *Execution by PVM*: Python Virtual Machine (PVM) reads and executes the bytecode
on the hardware.
-Interactive editing
-Use of variables initialized in the previous prompts
-Writing the complete code in it with a readline facility.
-To get command-line editing, one can press Ctrl+P, which gives a beep
indicating the mode is activated.
4
This is how a Python interpreter works. The following chart summarizes
To open the Python interpreter, installed in the system, search in the Start menu. Then click on
The picture below shows the Python interpreter once opened. Small description of the Python
version, storage, etc. Along with this, you can see three arrows (>>>), called prompt. This is the
5
Coding in the Python Interpreter Environment
The interpreter allows interactive editing. Once you write the code, press the “Enter” button to
see the results. The below example shows a simple code of printing “Hello, World!”
Output
Hello, World!
After the result, the interpreter gives another prompt for the next program/code.
Finally, Let’s understand with an example on how python interpreted nature works:
x=5
6
y = 10
z=x+y
print(z)
When this code is run, the Python interpreter reads the code line by line and executes each line
in turn. It starts by assigning the value 5 to the variable ‘x’, then assigns the value 10 to the variable
‘y’. It then adds ‘x’ and ‘y’ together and stores the result in the variable ‘z’. Finally, it prints the
If this program contained a syntax error, such as a misspelled keyword or missing parentheses,
the Python interpreter would catch the error and print a message explaining what went wrong.
This is because the interpreter checks each line of code as it is executed, rather than compiling
Python is a general-purpose language, not specialized for any specific problems, and
used to create various programmes.. For example, Desktop Applications Web Applications,
Data Science Applications, Machine learning applications and so on. Everywhere you can use Python
2. HISTORY OF PYTHON:
Python was created by Guido van Rossum, and
first released on February 20,
Python goals:
an easy and intuitive language just as powerful as those of the major competitors;
open source, so anyone can contribute to its development;
code that is as understandable as plain English;
suitable for everyday tasks, allowing for short development times.
7
2. WHY LEARN PYTHON?
There are couple of factors that make Python great for learning:
It is easy to learn – the time needed to learn Python is shorter than for many other languages; this
It is easy to use for writing new software – it’s often possible to write code faster when using
Python;
It is easy to obtain, install and deploy – Python is free, open and multiplatform; not all languages
If you want to learn Python programming, what is the prerequisite knowledge required?
Nothing is required, If you are in a position to read English statements, that is enough to learn
Python programming.
8
Just to print 'Hello World',
When compared with any other prgramming language (C, C++, C## or Java),
We can use Python everywhere. The most common important application areas are as follows:
The Applications which are running on a single systems (i.e., Stand alone applications)
8. For IOT
3. Top Software companies like Google, Microsoft, IBM, Yahoo, Dropbox, Netflix, Instagram
using python.
9
GETTING STARTED WITH PYTHON:
PYTHON INSTALLATION:
-IN WINDOWS:
There are many interpreters available freely to run Python scripts like IDLE
(Integrated Development Environment) that comes bundled with the Python software downloaded
from https://www.python.org/
On the web browser, in the official site of python (www.python.org), move to the
All the available versions of Python will be listed. Select the version required by you
different operating system specifications. Choose the installer which suits your system
operating system and download the instlaller. Let suppose, we select the Windows
installer(64 bits).
Run the installer. Make sure to select both the checkboxes at the bottom and then click Install Now.
The installation process will take few minutes to complete and once the installation is successful,
To ensure if Python is succesfully installed on your system. Follow the given steps -
-Linux: Python comes preinstalled with popular Linux distros such as Ubuntu and in Fedora.
To check which version of Python you're running, type "python" in the terminal emulator.
The interpreter should start and print the version number.
-macOS: Generally, Python 2.7 comes bundled with macOS. You'll have to manually install
11
Python Identifiers:
What is an Identifier?
- A name in Python program is called identifier. It can be class name or function name or module name
or variable name.
identifier or not.
Eg: a = 20
12
2.Identifier should not starts with digit
3.Identifiers are case sensitive. Of course Python language itself is case sensitive language.
4.There is no length limit for Python identifiers. But not recommended to use too lengthy identifiers.
13
KEYWORDS IN PYTHON:
Python Keywords are some predefined and reserved words in Python that have special meanings.
Keywords are used to define the syntax of the coding. The keyword cannot be used as an identifier,
function, or variable name. All the keywords in Python are written in lowercase except True and
False. There are 35 keywords in Python 3.12.
In Python, there is an inbuilt keyword module that provides an iskeyword() function that can be used
to check whether a given string is a valid keyword or not. Furthermore, we can check the name of the
keywords in Python by using the kwlist attribute of the keyword module.
Keywords Description
This is a logical operator which returns true if both the operands are
and
true else returns false.
Else is used with if and elif conditional statements. The else block is
else
executed if the given condition is not true.
14
Keywords Description
This function is used for debugging purposes. Usually used to check the
assert
correctness of code
15
Keywords Description
in It’s used to check whether a value is present in a list, range, tuple, etc.
The following code allows you to view the complete list of Python’s keywords.
This code imports the “keyword” module in Python and then prints a list of all the keywords in
Python using the “kwlist” attribute of the “keyword” module. The “kwlist” attribute is a list of
strings, where each string represents a keyword in Python. By printing this list, we can see all the
keywords that are reserved in Python and cannot be used as identifiers.
PYTHON VARIABLES:
Python Variables are containers that store values. Python is not “statically typed”. We do not
need to declare variables before using them or declare their type. A variable is created the
16
moment we first assign a value to it.
A Python variable name must start with a letter or the underscore character.
A Python variable name cannot start with a number.
A Python variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ ).
Variable in Python names are case-sensitive (name, Name, and NAME are three different
variables).
The reserved words(keywords) in Python cannot be used to name the variable in Python.
Examples:
1. x = 5
y = "John"
print(x)
print(y)
Output: 5
John
-Variables do not need to be declared with any particular type, and can even change
2. x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Output: Sally
Case-Sensitive
a = 4
A = "Sally"
#A will not overwrite a
17
4.
-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
myVariableName = "John"
Pascal Case
MyVariableName = "John"
Snake Case
my_variable_name = "John"
Example:
Output: Orange
Banana
Cherry
Note: Make sure the number of variables matches the number of values, or else you will get an error.
18
-One Value to Multiple Variables
-And you can assign the same value to multiple variables in one line:
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)
Output: Orange
Orange
Orange
Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values
Example
Unpack a list:
Output: apple
banana
cherry
Example:
19
Output: Python is awesome
-In the print() function, the output multiple variables, separated by a comma:
Example:
Output:Python is awesome
Example:
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
Notice the space character after "Python " and "is ", without them the result
would be "Pythonisawesome".
-In the print() function, when you try to combine a string and a number with the + operator
Example:
Output:
The best way to output multiple variables in the print() function is to separate them with
20
Example:
Output: 5 John
global variables.
Global variables can be used by everyone, both inside of functions and outside.
Example:
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
-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
Example:
Create a variable inside a function, with the same name as the global variable
21
Output:
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:
Output:
-Also, use the global keyword if you want to change a global variable inside a function.
Example:
22
Output:
PYTHON DATATYPES:
Python Data types are the classification or categorization of data items. It represents the kind
of value that tells what operations can be performed on a particular data. Since everything
is an object in Python programming, Python data types are classes and variables
are instances (objects) of these classes. The following are the standard or built-in data
types in Python:
Numeric
Sequence Type
Boolean
Set
Dictionary
Binary Types( memoryview, bytearray, bytes)
23
Getting the Data Type:
You can get the data type of any object by using the type() function:
Example:
x = 5
print(type(x))
Output:
x = 20 int
x = 20.5 float
x = 1j complex
x = range(6) range
x = True bool
24
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType
The numeric data type in Python represents the data that has a numeric value.
These values are defined as Python int, Python float, and Python complex classes in Python..
-Int
Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
Example:
Float
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
Example:
25
-Complex
Complex numbers are written with a "j" as the imaginary part:
Example:
Type Conversion
You can convert from one type to another with the int(), float(), and complex() methods:
Example:
26
Output:
Note: You cannot convert complex numbers into another number type.
-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:
27
Output:
PYTHON STRINGS:
STRING:A String is a sequence of characters enclosed within single quotes or double quotes.
In Python to represent a string, can we use a pair of single quotes ('') or double quotes ("")?
The answer is, We can use either single quotes or double quotes.
Example:
Output:
-Multiline Strings
You can assign a multiline string to a variable by using three quotes:
a ="""Good morning!
Hope all are doing well,
Welcome to the world of python."""
print(a)
Output:
28
Or three single quotes:
a = '''Good morning!
Hope all are doing well,
Welcome to the world of python.'''
print(a)
Note: in the result, the line breaks are inserted at the same position as in the code.
However, Python does not have a character data type, a single character is simply a string with a
length of 1.
Output:
-String Length
To get the length of a string, use the len() function.
a = "Hello, World!"
print(len(a))
Output:
13
-Check String
To check if a certain phrase or character is present in a string, we can use the keyword in.
29
Example:
Output:
True
Use it in an if statement:
Example:
Output:
-Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the keyword not in.
Example:
Output:
True
Use it in an if statement:
Example:
Output:
30
-Python - Slicing Strings
First, let’s know the indexing of python string:
String Slicing:
-In Python, the String Slicing method is used to access a range of characters in the String.
- One thing to keep in mind while using this method is that the string returned after
slicing includes the character at the start index but not the character at the last index.
Example:
b = "Hello, World!"
print(b[2:5])
Output:
Example:
b = "Hello, World!"
print(b[:5])
Output:
31
-Slice To the End
By leaving out the end index, the range will go to the end:
Example:
3.Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
Output:
-Negative Indexing
Use negative indexes to start the slice from the end of the string:
Example:
b = "Hello, World!"
print(b[-5:-2])
Output:
Upper Case:
Example: The upper() method returns the string in upper case:
a = "Hello, World!"
print(a.upper())
32
Lower Case:
Example: The lower() method returns the string in lower case:
a = "Hello, World!"
print(a.lower())
Example:The strip() method removes any whitespace from the beginning or the
end:
- Split String
The split() method returns a list where the text between the specified separator becomes the list items.
Example:The split() method splits the string into substrings if it finds instances
of the separator:
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
a = "Hello"
b = "World"
c = a + b
print(c)
Output:
a = "Hello"
b = "World"
c = a + " " + b
print(c)
33
Output:
Example:age = 36
txt = "My name is John, I am " + age
print(txt)
But we can combine strings and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and places them in the
Output:
The format() method takes unlimited number of arguments, and are placed
Example:
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))
Output:
34
-Python - Escape Characters
To insert characters that are illegal in a string, use an escape character.
double quotes:
Example: You will get an error if you use double quotes inside a string that is
The escape character allows you to use double quotes when you normally would not be allowed:
-Escape Characters
Code Result
\\ Backslash
\n New Line
\r Carriage Return
\t Tab
\b Backspace
\f Form Feed
35
PYTHON ARRAYS:
What is an Array in Python?
Creating an Array
Output:
36
- Complexities for Creation of Arrays:
In order to access the array items refer to the index number. Use the index operator [ ] to access
an item in a array. The index must be an integer.
This code demonstrates the use of indexing to access elements in arrays. The a[0]
expression accesses the first element of the array a, which is 1. The a[3] expression accesses
the fourth element of the array a, which is 4. Similarly, the b[1] expression accesses the
second element of the array b, which is 3.2, and the b[2] expression accesses the third
element of the array b, which is 3.3.
Output:
Elements can be removed from the array by using built-in remove() function but an
Error arises if element doesn’t exist in the set.
Remove() method only removes one element at a time, to remove range of elements, iterator
is used.
38
pop() function can also be used to remove and return an element from the array, but
by default it removes only the last element of the array, to remove element from a
specific position of the array, index of the element is passed as an argument to the
pop() method.
Note – Remove method in List will only remove the first occurrence of the searched
element.
This code demonstrates how to create, print, remove elements from, and access
elements of an array in Python. It imports the array module, which is used to work
with arrays. It creates an array of integers and prints the original array.
It then removes an element from the array and prints the modified array.
Finally, it removes all occurrences of a specific element from the array and prints
the updated array.
Output:
39
Python If ... Else
Python Conditions and If statements
Python supports the usual logical conditions from mathematics:
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
Example:
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
Output:
-Indentation
Python relies on indentation (whitespace at the beginning of a line) to define scope
in the code. Other programming languages often use curly-brackets for this purpose.
Example:
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
-Elif
40
The elif keyword is Python's way of saying "if the previous conditions were not true,
Example:
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Output:
-Else
The else keyword catches anything which isn't caught by the preceding conditions.
Example:
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Output:
Output:
41
-Short Hand If
If you have only one statement to execute, you can put it on the same line as the if statement.
a = 2
b = 330
print("A") if a > b else print("B")
-Nested If
You can have if statements inside if statements, this is called nested if statements.
Example:
Output:
42
-The pass Statement
if statements cannot be empty, but if you for some reason have an if statement with
Example:
a = 33
b = 200
if b > a:
pass
# having an empty if statement like this, would raise an error without the pass statement.
Python Functions:
A function is a block of code which only runs when it is called.
Creating a Function
In Python a function is defined using the def keyword:
Example:
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
Example:
def my_function():
print("Hello from a function")
my_function()
Arguments
Information can be passed into functions as arguments.
43
Arguments are specified after the function name, inside the parentheses.
You can add as many arguments as you want, just separate them with a comma.
The following example has a function with one argument (fname). When the function is
called, we pass along a first name, which is used inside the function to print the full name:
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
Output:
POSITIONAL ARGUMENTS:
Example:
Keyword Arguments:
Example:
Default Arguments:
If the value is not provided during the function call, the default value is used.
44
Example:
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
Example:
def add(*args):
return sum(args)
print(add(1, 2, 3)) # Output: 6
Example:
def person_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
Mutable objects (like lists, dictionaries) are passed by reference, meaning changes made
changes made inside the function do not affect the original object.
45
Example:
def modify_list(lst):
lst.append(4)
my_list = [1, 2, 3]
modify_list(my_list)
print(my_list) # Output: [1, 2, 3, 4]
Python has several functions for creating, reading, updating, and deleting files.
The key function for working with files in Python is the open() function.
In addition you can specify if the file should be handled as binary or text mode
Syntax
To open a file for reading it is enough to specify the name of the file:
46
f = open("demofile.txt")
Because "r" for read, and "t" for text are the default values, you do not need to specify them.
Note: Make sure the file exists, or else you will get an error.
The open() function returns a file object, which has a read() method for reading
Example:
Output:
If the file is located in a different location, you will have to specify the file path, like this:
47
-Read Only Parts of the File
By default the read() method returns the whole text, but you can also specify how
Example:
Output:
-Read Lines
You can return one line by using the readline() method:
Example:
Output:
By calling readline() two times, you can read the two first lines:
Example:
Output:
48
By looping through the lines of the file, you can read the whole file, line by line:
Example:
Output:
-Close Files
It is a good practice to always close the file when you are done with it.
Note: You should always close your files, in some cases, due to buffering, changes
made to a file may not show until you close the file.
49
"w" - Write - will overwrite any existing content
Output:
OUTPUT:
following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Example:
50
Result: a new empty file is created!
to delete it:
- Delete Folder
51
Note: You can only remove empty folders.
52