Hi Everyone!
Welcome to my Course Learning of Python Programming.
In this course, we are going to learn how to do programming in python.
I am a python developer for a long time, and I’m so excited to share my knowledge of this awesome programming Language.
This course is designed for both beginner and professional, and also helpful for everyone who wish to learn the Python programming language.
With python, you can do Almost Anything Like basic programming, build web applications, desktop application, do scientific computations,Artificial intelligence and even more popular skill like machine learning.
Some of the major topics we will discuss include installing python, learning the syntax and basic features of the python, and developing a console application.
This course is a getting started course for developing python application, and you don’t need prior experience with python at all.
By the End of this course, you’ll know the basic of python programming and be ready to develop your own applications.
This course is a getting started course for developing python application, and you don’t need prior experience with python at all.
Some of the(thi?) major topics we will cover include installing python on every major operating system learning the syntax and basic features of the languages, developing a console application and converting it into a web app, and creating executable file and setup wizard from our python app.
By the End of this course, you’ll know the basic of python programming and be ready to develop applications on your own.
From Here, continue learning by dividing into python framework and libraries with courses on
Django for web development.
TensorFlow for AI
SciPy for scientific calculations
And PyQt for cross-platform desktop application.
I hope you’ll join me on this journey to learn Python with the python: Getting started courses at CodersArts.
In this series of python learning. We will discuss the following topics
First Program Hello, World!
Variables and Types
Basic Operators
Conditions
Loops
Functions
Lists
String Formatting
String Operations
Dictionaries
Modules and Packages
Classes and Objects
I hope you’ll enjoy on this journey to learn Python programming
Introduction of Python Language
Python is a good programming language for beginners. Because it is easy-to-read and learn and Writing programs in Python takes less time than in some other languages.
There are no type declarations of variables, parameters, functions, or methods in source code. This makes the code short and flexible, and you save the compile-time type checking of the source code. Python tracks the types of all values at runtime and flags code that does not make sense as it runs.
Features of Python
Interpreted Language
Python is an interpreted language. Interpreted languages do not need to be compiled to run.
This means that a programmer can change the code and quickly see the results.
Python is slower than a compiled language like C, because it is not running machine code directly.
High-level language
It is a high-level language, which means a programmer can focus on what to do instead of how to do it.
Object-oriented programming
Like C++,Java and others Object-oriented programming (OOP) Python also support OOP that is based on the concept of "objects", which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods
Multi-paradigm programming language
Supports more than one programming paradigm to allow programmers to use the most suitable programming style and associated language constructs for a given job. Like Declarative programming,Distributed programming,Functional programming etc.
Large Standard Library
Python provides rich set of module and functions for rapid application development. like Scipy used for scientific computing and technical computing. SciPy contains modules for optimization, linear algebra, integration, interpolation, special functions etc.
NumPy provides basic numerical routines
GUI Programming Support
Graphical user interfaces can be developed using Python.like Tkinter, JPython etc.
Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, Unix and Macintosh etc. So, we can say that Python is a portable language.
What are the differences? Python 2.x and Python 3.x
Python 2
Python 2.x is legacy
The final 2.x version 2.7 release came out in mid-2010 and after that no major version of 2.0 released. After that. 3.x is under active development and has already seen over five years of stable releases, including version 3.3 in 2012, 3.4 in 2014, 3.5 in 2015, and 3.6 in 2016. This means that all recent standard library improvements, for example, are only available by default in Python 3.x.
Maintained but no new features.
End of life(EOL) 2020.
Still default on many systems.
In this syntax to print statement write as:
Print “Hello World"
Python 3
Python 3.x is the present and future of the language.
Python 3.0 was released in 2008.
New Features Being Added
Unicode supported by default
In this syntax to print statement write as
>>>Print(“Hello World”)
Hello World
Throughout this course, we will work with python 3 and use the latest version is 3.6.4
So let’s go ahead and install it.
Installing Python
Simply, open your favorite browser, in address bar type www.python.org.
From there, go to downloads and clicks on python 3.6.14 or whatever latest python 3 version is there when you are watching this. The website will recognize which operating system you are using, so you don’t have to worry about selecting windows specially anywhere. Once the download finishes, open the setup file.
Make sure to check the Add python 3.6 to path option in the installer then click on install now. Follow all instruction and install carefully.
If You’re using Linux ,open terminal then
First Type
Sudo apt-get install python3
And second
Sudo apt–get install idle3
Python Vs Others
Just for printing Hello world we write these lines of code
Java
// Java Hello World
Public class HelloWorld {
Public static void main(String args[]){
System.out.println(“Hello World”);
}
}
Hello World
Python 3
>>>print(“Hello World”)
Hello World
Other Example to print hello world
>>>print(“Hello World”)
Hello World
>>>var=”Hello World”
>>>print(var)
Hello World
>>>print(“Hello\tworld”) // ‘\t’ for tab
Hello world
>>>print(“Hello\t\tworld”) // ‘\t’ for tab
Hello world
>>>print(“Hello\nworld”) // ‘\n’ for new line
Hello
world
Let’s write some arithmetic operation and see the language’s flavor and style
>>>3 + 3
6
>>>3 * 9
27
>>>X = 5 * 10
50
Introduction about IDLE
This is a little bit info about python integrated development environment.
And the sign start with “>>>” is called primary prompt or input prompt.
Comments in Python start with the hash character, #, and extend to the end of the physical line. A comment may appear at the start of a line or following whitespace or code, but not within a string literal. A hash character within a string literal is just a hash character. Since comments are to clarify code and are not interpreted by Python, they may be omitted when typing in examples.
Some examples:
# this is the first comment
>>>var = 1 # and this is the second comment
>>>text = "# This is not a comment because it's inside quotes."
Variables and Assignments
In this will go over a few basic of variables and its assignments.
So, the very first question comes in mind that, what is a variable?
A variable is a reserved location in a computer memory to store values.
We can store different data types, such as integers, floating point numbers, and strings in a variable.
If you do not understand these data types, don't worry about it.We will cover in future lessons.
In Python, we do not explicitly declare data type of a variables.
Python automatically reserves the memory space for each variable when you assign a value to a variable.
Naming Convention of python variables
Variable name is case sensitive (X and x two different variable names)
Can contains letters, numbers, and underscores
Can’t start with a number, i.e. x1 is valid but not 1x
We cannot use a keyword as variable name, function name or any other identifier. Keywords are the reserved words in Python
Best practice for Variable Name
Select a meaningful name instead of short name. first_name is better than fname.
Maintain the length of a variable name. First_name_and_last_name-It’s too long?
Be consistent; FirstName or First_name
Start a variable name with an underscore(_) character for a special case
Python Assignment Statements
The equal sign (=) is used to assign values to variables.
Valid Syntax:
>>><variable name> = <expr> or values
>>>name = ”Python”
>>>Age = 100
Invalid syntax:
>>>“python”=name
>>>“100”=Age
Multiple Assignment
In Python, you can assign a single value to more than one variables simultaneously.
For example
>>>var1 = var2 = var3 = 10
Here, an integer object is created with the value 10, and all three variables are assigned to the same memory location.
You can also assign multiple objects to multiple variables.
For example
>>>var1,var2,var3 = 10,20,"abcd"
Here, two integer objects with values 10 and 20 are assigned to variables var1 and var2 respectively, and one string object with the value "Hello" is assigned to the variable var3.
You can reuse variable names by simply assigning a new value to them :
>>>X=”Abcd”
>>>Print(X)
>>>X=10
>>>Print(x)
Swap variables values in so simple
Python swap values in a single line and this applies to all objects in python.
Syntax:
var1, var2 = var2, var1
Example:
>>> x =5
>>> y =10
>>>print(x)
5
>>>print(y)
10
>>> x, y = y, x
>>>print(x)
10
>>>print(y)
5
Variable Type
Python is completely object oriented, and not "statically typed". You do not need to declare variables before using them, or declare their type. Every variable in Python is an object.
This tutorial will go over a few basic types of variables.
Numbers
Python supports two types of numbers - integers and floating point numbers. (It also supports complex numbers, which will not be explained in this tutorial).
To define an integer, use the following syntax:
>>>num = 7
>>>print(num)
To define a floating point number, you may use one of the following notations:
>>>myfloat = 7.0
>>>print(myfloat)
>>>myfloat = float(7)
>>>print(myfloat
Variable Types
These are different types of variables in python
The first one is String that in Python is identified by str.
The second one is called a floating point number.
And the third one is an Integer symbol is int,
And the last one is a Boolean type, which means there's only two possible answer yes or no, or True or False.
Let’s go through each type one by one
String(str)
String is a group of characters and it’s defined either with a single quote or a double quotes.
Go to editor and see examples
>>>String1 = 'hello'
>>>print(String1)
>>>String2 = “hello”
>>>print(String2)
>>>String1 = ‘Don't do this’
>>>print(String1)
>>>String2 = "Don't worry about apostrophes"
>>>print(String2)
Float (float)
A=7/2
Integer(int)
A=5
B= 2 * 3
Print(A,B)
String and utility methods
Hi there!
In this lesson I’m going to explain string and the methods supported by string in python.
Concatenation
In order to merge two strings into a single object, you may use the “+” operator.
>>>str1 = “Hello”
>>>str2 = “World”
>>>str1 + str2
Capitalize the String
>>>“hello”.capitalize()
HELLO
Replacing character in string
>>>“hello”.replace(“e”,”a”)
HaLLO
Check all character in string is alphabets
>>>“hello”.isalpha()
True
Check the string is numeric or not
>>>“1234”.isdigit() #“Useful when converting to int
True
Split the string with given parameter
>>>“Hello,world,pyhon”.split(“,”)
[“Hello”,”world”,”python”]
String Format Function
>>>msg=”Hello world”
>>>name=”Codersarts”
>>>“{0} welcome to Learning python. I am {1} ”.format(msg,name)
Hello world welcome to Learning python. I am Codersarts
The numbers within curly brackets indicates positions in format() functions from left to right direction. {0} Refers to variable msg and {1} indicated to name. Indexing usually start with 0.
“{0} welcome to Learning python. I am {1} ”.format(msg,name) .
Python String Interpolation
Python 3.6 added new string interpolation method called literal string interpolation and introduced a new literal prefix f. This new way of formatting strings is powerful and easy to use. It provides access to embedded Python expressions inside string constants.
>>>greeting=“Hello World”
>>>name =“Python”
>>>print(f”{greeting}! This is {name}”)
When we will run this code, the output will be
Hello World! This is Python
The prefix f tells Python to restore the value of two string variable greeting and name inside braces {}.
The string interpolation is powerful as we can embed arbitrary Python expressions and even can do inline arithmetic with it.
Example 2:
>>>x=6
>>>y=5
>>>print(f'{x} multiply {y} is {x * y}.')
and if you run this we will get this result
6 multiply 5 is 30.
Which one you should use? The choice as always is yours. I personally like the string interpolation, but the format function is also pretty powerful.
There are also some other interesting string properties like string slicing, but I think you’ve had enough of strings for now. Let’s move on to Boolean and None.
Boolean and None
Boolean is type which store True or False value
For declaring Boolean variables, simply type the variable name and assign True or False value to it.
For instance, if someone ask do you know python
You answer would be yes or No in python True or False
>>>Var1=True
>>>Var2=False
>>>Int(var1)=1
>>>Int(var2)=0
>>>Str(var2)=”False”
>>>Not_found=None
Print () function in python
In this, I am going to talk about print () function.
Ok, Let’s get started.
Print () function in python is used to write output to different sources .That means you can see output on console or can write in file.
The general syntax of print function is
print (value1, ..., sep=' ', end='\n', file=sys.stdout, flush=False).
Let’s see one by one with example.
1. By default, python adds a space between the output. If you have single variable or string you can just write
print(“Hello”)
And for multiple output on screen you can use comma between output items.
Like
print (“Hello”, “world”).
2. You can separate the output using the comma delimiter. Like
print (“Hello”,” Python”,sep=’,’)
3. By default, print goes to a new line at the end. You can change this by using the keyword “end” as shown in the example below.
>>>print(“Hello”,“Python”, sep=',',end='!!\n')
4. For example, you can print the letters in the word "python" and all the letters will come in a new line.
>>>for i in"python":
>>>print(i)
p
y
t
h
o
n
5. You can change this default implementation. You can have a colon : between the letters instead of a new line.
>>>for i in"python":
>>>print(i,end=":")
p:y:t:h:o:n:
6. The output of the print function is send to the standard output stream (sys.stdout) by default. By redefining the keyword parameter "file" we can send the output into a different stream e.g. sys.stderr or a file:
>>> fh = open("data.txt","w")
>>> print("42 is the answer, but what is the question?", file=fh)
>>> fh.close()
7. Print string N Times without loop:If you want to print a specific string (a sequence of characters such as letters, punctuation marks, numbers, and letters) N number of times. The (asterisk) * operator performs repetition on strings.
Example 1
Print(“Hello”*5)
Print(“Hello\n”*5)
Numbers
You can type any expression whatever you want, it acts like as simple calculator.
You can do addition (+), subtraction (-), multiplication (*) and division (/) just like in most other languages C, C++, Java etc.
Parentheses (()) is used for grouping the expression. For Instance:
>>>2+2
4
>>>50-5*6
20
>>>(50-5*6)/4
5.0
>>>8/5# division always returns a floating point number
1.6
1. The integer numbers (e.g. 2, 4, 20) have type int,
2. the ones with a fractional part (e.g. 5.0, 1.6) have type float.
3. Division (/) always returns a float.
4. To do floor division and get an integer result (discarding any fractional result) you can use the // operator;
5. to calculate the remainder you can use %:
>>>17/3# classic division returns a float
5.666666666666667
>>>
>>>17//3# floor division discards the fractional part
5
>>>17%3# the % operator returns the remainder of the division
2
>>>5*3+2# result * divisor + remainder
17
6. With Python, it is possible to use the ** operator to calculate powers
>>>5**2# 5 squared
25
>>>2**7# 2 to the power of 7
128
8. The equal sign (=) is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt:
>>>width=20
>>>height=5*9
>>>width*height
900
9. If a variable is not “defined” (assigned a value), trying to use it will give you an error:
>>>n# try to access an undefined variable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'n' is not defined
10. There is full support for floating point; operators with mixed type operands convert the integer operand to floating point:
>>>4*3.75-1
14.0
12. In interactive mode, the last printed expression is assigned to the variable _. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations, for example:
>>>tax=12.5/100
>>>price=100.50
>>>price*tax
12.5625
>>>price+_
113.0625
>>>round(_,2)
113.06
Using Python Strings
In this I am going to talk each and every aspect of string in python,so please watch this video at the end; You’ll feel much confident in python string concepts, okay so, let’s start.
Besides numbers, Strings can be expressed in several ways in python. They can be enclosed in single quotes ('...') or double quotes ("...") with the same result. \ can be used to escape quotes:
>>>'Hello Python'# single quotes
'Hello Python'
>>>'doesn\'t'# use \' to escape the single quote...
"doesn't"
>>>"doesn't"# ...or use double quotes instead
"doesn't"
>>>'"Yes," I know.'
'"Yes," I Know.'
>>>"\"Yes,\" I know."
'"Yes," I know.'
>>>'"Isn\'t," she said.'
'"Isn\'t," she said.'
The print() function produces a more readable output, by omitting the enclosing quotes and by printing escaped and special characters:
>>>'"Isn\'t," she said.'
'"Isn\'t," she said.'
>>>print('"Isn\'t," she said.')
"Isn't," she said.
>>>s='First line.\nSecond line.'# \n means newline
>>>s# without print(), \n is included in the output
'First line.\nSecond line.'
>>>print(s)# with print(), \n produces a new line
First line.
Second line.
If you don’t want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote:
>>>print('C:\some\name')# here \n means newline!
C:\some
ame
>>>print(r'C:\some\name')# note the r before the quote
C:\some\name
String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''. End of lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the end of the line. The following example:
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
produces the following output (note that the initial newline is not included):
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
Strings can be concatenated (glued together) with the + operator, and repeated with *:
>>># 3 times 'un', followed by 'ium'
>>>3*'un'+'ium'
'unununium'
Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated.
>>>'Py''thon'
'Python'
This feature is particularly useful when you want to break long strings:
>>>text=('Put several strings within parentheses '
... 'to have them joined together.')
>>>text
'Put several strings within parentheses to have them joined together.'
This only works with two literals though, not with variables or expressions:
>>>prefix='Py'
>>>prefix'thon'# can't concatenate a variable and a string literal
...
SyntaxError: invalid syntax
>>>('un'*3)'ium'
...
SyntaxError: invalid syntax
If you want to concatenate variables or a variable and a literal, use +:
>>>prefix+'thon'
'Python'
Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one:
>>>word='Python'
>>>word[0]# character in position 0
'P'
>>>word[5]# character in position 5
'n'
Indices may also be negative numbers, to start counting from the right:
>>>word[-1]# last character
'n'
>>>word[-2]# second-last character
'o'
>>>word[-6]
'P'
Note that since -0 is the same as 0, negative indices start from -1.
In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain substring:
>>>word[0:2]# characters from position 0 (included) to 2 (excluded)
'Py'
>>>word[2:5]# characters from position 2 (included) to 5 (excluded)
'tho'
Note how the start is always included, and the end always excluded. This makes sure that s[:i] + s[i:] is always equal to s:
>>>word[:2]+word[2:]
'Python'
>>>word[:4]+word[4:]
'Python'
Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.
>>>word[:2]# character from the beginning to position 2 (excluded)
'Py'
>>>word[4:]# characters from position 4 (included) to the end
'on'
>>>word[-2:]# characters from the second-last (included) to the end
'on'
One way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:
+---+---+---+---+---+---+
|P|y|t|h|o|n|
+---+---+---+---+---+---+
0123456
-6-5-4-3-2-1
The first row of numbers gives the position of the indices 0…6 in the string; the second row gives the corresponding negative indices. The slice from i to j consists of all characters between the edges labeled i and j, respectively.
For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. For example, the length of word[1:3] is 2.
Attempting to use an index that is too large will result in an error:
>>>word[42]# the word only has 6 characters
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
However, out of range slice indexes are handled gracefully when used for slicing:
>>>word[4:42]
'on'
>>>word[42:]
''
Python strings cannot be changed — they are immutable. Therefore, assigning to an indexed position in the string results in an error:
>>>word[0]='J'
...
TypeError: 'str' object does not support item assignment
>>>word[2:]='py'
...
TypeError: 'str' object does not support item assignment
If you need a different string, you should create a new one:
>>>'J'+word[1:]
'Jython'
>>>word[:2]+'py'
'Pypy'
The built-in function len() returns the length of a string
>>>s='supercalifragilisticexpialidocious'
>>>len(s)
34
Like strings (and all other built-in sequence type), lists can be indexed and sliced:
>>> student_names[0]
'Ram'
>>> student_names[-1]
'Arjun'
>>> student_names[:2]
['Ram', 'Krishna']
All slice operations return a new list containing the requested elements. This means that the following slice returns a new (shallow) copy of the list:
>>> student_names[:]
['Ram', 'Krishna', 'Arjun']
>>> student_names[1:]
['Krishna', 'Arjun']
Lists also support operations like concatenation:
>>> student_names + ["Bhisma","Karna"]
['Ram', 'Krishna', 'Arjun', 'Bhisma', 'Karna']
You can also add new items at the end of the list, by using the append() method (we will see more about methods later):
>>> cubes=[1,8,27]
>>> cubes.append(64) # add the cube of 4
>>> cubes.append(5 ** 3) # and the cube of 5
>>> cubes
[1, 8, 27, 64, 125]
Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]
The built-in function len() also applies to lists:
>>> letters = ['a', 'b', 'c', 'd']
>>> len(letters)
4
It is possible to nest lists (create lists containing other lists), for example:
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'
>>>x[1][0]
1
List of Development Services
Web Development
Mobile App Development
IPhone Application Development
Android Application Development
React Native App Development
Flutter App Development
JavaScript Development
Java Application Development
Python Django Development Services
Python Development Services
Technology We Are Working
MongoDB Development Service