Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Python emick.ghimire@gmail.

com

Python: Beginners
Python
Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.
It is used for:
i) web development (server-side),
ii) software development
iii) mathematics
iv) 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.

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.

Advantages of Python Programming Language:

1
Python emick.ghimire@gmail.com

1. Presence of third-party modules: Python has a rich ecosystem of third-party


modules and libraries that extend its functionality for various tasks.
2. Extensive support libraries: Python boasts extensive support libraries like
NumPy for numerical calculations and Pandas for data analytics, making it
suitable for scientific and data-related applications.
3. Open source and large active community base: Python is open source, and it
has a large and active community that contributes to its development and provides
support.
4. Versatile, easy to read, learn, and write: Python is known for its simplicity and
readability, making it an excellent choice for both beginners and experienced
programmers.
5. User-friendly data structures: Python offers intuitive and easy-to-use data
structures, simplifying data manipulation and management.
6. High-level language: Python is a high-level language that abstracts low-level
details, making it more user-friendly.
7. Dynamically typed language: Python is dynamically typed, meaning you don’t
need to declare data types explicitly, making it flexible but still reliable.
8. Object-Oriented and Procedural programming language: Python supports
both object-oriented and procedural programming, providing versatility in coding
styles.
9. Portable and interactive: Python is portable across operating systems and
interactive, allowing real-time code execution and testing.
10. Ideal for prototypes: Python’s concise syntax allows developers to prototype
applications quickly with less code.
11. Highly efficient: Python’s clean design provides enhanced process control, and it
has excellent text processing capabilities, making it efficient for various
applications.
12. Internet of Things (IoT) opportunities: Python is used in IoT applications due to
its simplicity and versatility.
13. Interpreted language: Python is interpreted, which allows for easier debugging
and code development.
Disadvantages of Python Programming Language:
1. Performance: Python is an interpreted language, which means that it can be
slower than compiled languages like C or Java. This can be an issue for
performance-intensive tasks.
2. Global Interpreter Lock: The Global Interpreter Lock (GIL) is a mechanism in
Python that prevents multiple threads from executing Python code at once. This
can limit the parallelism and concurrency of some applications.

2
Python emick.ghimire@gmail.com

3. Memory consumption: Python can consume a lot of memory, especially when


working with large datasets or running complex algorithms.
4. Dynamically typed: Python is a dynamically typed language, which means that
the types of variables can change at runtime. This can make it more difficult to
catch errors and can lead to bugs.
5. Packaging and versioning: Python has a large number of packages and libraries,
which can sometimes lead to versioning issues and package conflicts.
6. Lack of strictness: Python’s flexibility can sometimes be a double-edged sword.
While it can be great for rapid development and prototyping, it can also lead to
code that is difficult to read and maintain.
7. Steep learning curve: While Python is generally considered to be a relatively
easy language to learn, it can still have a steep learning curve for beginners,
especially if they have no prior experience with programming.

Applications:
1. GUI-based desktop applications: Python is used to develop graphical user
interface (GUI) applications.
2. Graphic design, image processing, games, and scientific/computational
applications: Python is employed in graphics, games, and scientific computing.
3. Web frameworks and applications: Popular web frameworks
like Django and Flask are built using Python.
4. Enterprise and business applications: Python is used for various business
applications, including data analysis and automation.
5. Operating systems: Python is used in the development of operating systems and
system tools.
6. Education: Python is commonly used for teaching programming and computer
science.
7. Database access: Python provides libraries for accessing and managing databases.
8. Language development: Python is used to create and develop new programming
languages.
9. Prototyping: Python is ideal for quickly prototyping software and applications.
10. Software development: Python is used for general-purpose software
development.
11. Data science and machine learning: Python is a primary language for data
science and machine learning tasks.
12. Scripting: Python is widely used for writing scripts to automate tasks and
processes.

3
Python emick.ghimire@gmail.com

Structure of Python Program


The typical structure of a python program include 3 parts
Import statements
// import statements are used to include library files to the python program
Function definitions
//This section include the definitions of various functions written in Python
Program
Program statements
// This section include the set of statements for solving the given problem.

Execute Python Syntax


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:
C:\Users\Your Name>python myfile.py
1. Python Comments
i. Comments can be used to explain Python code.
ii. Comments can be used to make the code more readable.
iii. Comments can be used to prevent execution when testing code.

Creating a Comment
Comments starts with a #, and Python will ignore them:
Example: #This is a comment
print("Hello, World!")

or
print("Hello, World!") #This is a comment

4
Python emick.ghimire@gmail.com

Comments can be placed at the end of a line, and Python will ignore the rest of
the line:
2. Python 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
Example:
Var = "Geeksforgeeks"
print(Var) output: Geeksforgeeks
Rules for Python variables
• 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.

3. Python Data Type


Built-in Data Types
Python has the following data types built-in by default, in these categories:
Text type str
Numeric types int,float,complex
Sequence Types list,tuple,range
Mapping types dict
Set Types Set,frozenset
Boolean Type bool
Binary Type Bytes,bytearray,memoryview
None Type NoneType

5
Python emick.ghimire@gmail.com

Python Identifier
Identifier is a name given to various programming elements such as a variable,
function, class, module or any other object.
Following are the rules to create an identifier.
1. The allowed characters are a-z, A-Z, 0-9 and underscore (_)
2. It should begin with an alphabet or underscore
3. It should not be a keyword
4. It is case sensitive
5. No blank spaces are allowed.
6. It can be of any size Valid identifiers
examples : si, rate_of_interest, student1, ageStudent Invalid identifier examples : rate of
interest, 1student, @age
Python Keywords
Keywords are the identifiers which have a specific meaning in python, there are 33
keywords in python. These may vary from version to version.
False None True and as assert break class continue def del elif else except finally for from
global if import in is lambda nonlocal not or pass raise return try while with
false true none return pass import while
and as class not else return
del assert finally in continue nonlocal
def elif if is except rise
try while for from lambda with yield
Python Numbers
Number data type stores Numerical Values. Number data type stores Numerical Values.
These are of three different types:
a) Integer & Long
b) Float/floating point
c) Complex
1.1) Integers are the whole numbers consisting of + or – sign like 100000, -99, 0, while
writing a large integer value
e.g. age=19
salary=20000
1.2 Floating Point: Numbers with fractions or decimal point are called floating point
numbers. A floating point number will consist of sign (+,-) and a decimal sign(.)

6
Python emick.ghimire@gmail.com

e.g. temperature= -21.9,


growth_rate= 0.98333328
The floating point numbers can be represented in scientific notation such as
-2.0X 105 will be represented as -2.0e5
2.0X10-5 will be 2.0E-5
1.3 Complex: Complex number is made up of two floating point values, one each for real
and imaginary part. For accessing different parts of a variable x we will use x.real and
x.imag.Imaginary part of the number is represented by j instead of i, so 1+0j denotes zero
imaginary part.
Example
>>> x = 1+0j
>>> print x.real, x.imag
1.0 0.0
2. None: This is special data type with single value. It is used to signify the absence of
value/false in a situation. It is represented by None.
3. Sequence: A sequence is an ordered collection of items, indexed by positive integers.
Three types of sequence data type available in Python are Strings, Lists & Tuples.
3.1 String: is an ordered sequence of letters/characters. They are enclosed in single
quotes (‘’) or double (“”).
Example
>>> a = 'Ram'
>>>a=”Ram”
3.2 Lists: List is also a sequence of values of any type. Values in the list are called
elements / items. The items of list are accessed with the help of index (index start from
0). List is enclosed in square brackets.
Example
Student = [“Ajay”, 567, “CS”]
3.3 Tuples: Tuples are a sequence of values of any type, and are indexed by integers.
They are immutable i.e. we cannot change the value of items of tuples . Tuples are
enclosed in ().
Student = (“Ajay”, 567, “CS”)

7
Python emick.ghimire@gmail.com

4. Sets: Set is an unordered collection of values, of any type, with no duplicate entry. Sets
are immutable.
Example
s = set ([1,2,3,4])

5. Dictionaries: Dictionaries store a key – value pairs, which are accessed using key.
Dictionary is enclosed in curly brackets.
Example
d = {1:'a', 2:'b', 3:'c'}
6. Literals: A literal is a constant that appear directly in a program and this value does
not change during the program execution i.e. remain fixed.
Example:
Num1=5
Principle_amount= 5000.00
Here 5 and 5000.00 are literals. Python support the following literals
Numeric literals
String Literals
Special Literals
Collection Literals

Operators: Operators are special symbols which represents specific operations. They are
applied on operand(s), which can be values or variables. Same operator can behave
differently on different data types.
Operators when applied on operands form an expression.
Python divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators

Python Arithmetic Operators

8
Python emick.ghimire@gmail.com

Arithmetic operators are used with numeric values to perform common mathematical
operations:
Operator Description Syntax
+ Addition: adds two operands x+y
– Subtraction: subtracts two operands x–y
* Multiplication: multiplies two operands x*y
/ Division (float): divides the first operand by the second x/y
// Division (floor): divides the first operand by the second x // y
% Modulus: returns the remainder when the first operand is divided by the second
x%y
** Power: Returns first raised to power second x ** y

Python Assignment Operators


Assignment operators are used to assign values to variables:

9
Python emick.ghimire@gmail.com

Python Comparison Operators


It is also called Relational Operators.
Comparison operators are used to compare two values:
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Python Logical Operators
Logical Operators give the logical relationship based upon the truth table

10
Python emick.ghimire@gmail.com

11

You might also like