Towards AI Can Help your Team Adopt AI: Corporate Training, Consulting, and Talent Solutions.

Publication

A Crash Course on Python — Part-1
Latest   Machine Learning

A Crash Course on Python — Part-1

Last Updated on July 25, 2023 by Editorial Team

Author(s): Adeel

Originally published on Towards AI.

Photo by Xiaole Tao on Unsplash

In this series, I will cover the basics of python programming. It gives you an introductory level studies to the basic concepts including data types, loops, conditions, built-in data structures and importing modules. If you are new to programming and want to learn python from scratch, this is for you.

What Python is?

Python is just another language much like other languages as C, C++ and java. It is simple to use and is available for windows, macOS and Unix operating systems. Python is a very-high-level language, it has high-level data types built in, such as lists and dictionaries. Along with some built in data types, it has some pre-defined collection of modules that can make your work even faster.

Unlike java, python is an interpreted language which means that it can save you a significant amount of time during program execution. The program written in python are much shorter in structure from C and C++ as they use the high-level data types for complex operation, statement grouping is done through indentation rather than brackets and no variable declarations are necessary.

Python Interpreter

Python is a programming language and a software package called interpreter. An interpreter is a kind of program that executes other programs. In other words, an interpreter is a layer of software logic between the code you write and the computer hardware you are working on. The python installation details vary for different operation systems, and you can find more details on the following website: https://www.python.org/downloads/.

In the interactive mode the three greater-than signs (>>>) are used for the primary prompt. and for continuation lines three dots (…) are used for the secondary prompt.

(base) finder@ - - ~ % python
Python 3.9.12 (main, Apr 5 2022, 01:53:17)
[Clang 12.0.0 ] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print("hello world")
hello world
>>> deja_vu = True
>>> if deja_vu:
print("I have already seen this!")

I have already seen this!
>>>

Python Comments, Types and Operations

Comments in Python start with the hash character # and ends where the physical line ends.

The comments can appear at start of a line or code, but it cannot be included in string literal.

>>> # this is a comment
>>> text = "# this is not a comment"
>>> print(text)
# this is not a comment

In most of the lower-level programming languages such as C or C++; objects or data structures are implemented to represent the components in your application domain. The process in often tedious and error prone. However, python provides built-in types and usually there are rare occasions where you would have to implement your own objects. The python core data types are represented in the below table. Most of these types you would be familiar if you have used other languages.

Object Types

Numbers : 123, 3,145

Strings: ‘hello world’, “Monty Python”

Lists: [1,2,3], [‘a’,’b’,’c’]

Dictionaries: {‘Game’:’Cricket’, ‘Food’:’Biryani’}

Tuples: (1,’spam’)

Sets: Set(‘abc’)

Numbers

Most of the data types are straight forward and are seen in many different programming languages. Numbers can include integer types and floating-point numbers.

>>> 2 + 2
4
>>> 2.5 + 2.5
5.0

In the above code example the first calculation is between two integers (2 + 2) which also return an integer (4) and the second is in between floating-point numbers (2.5 + 2.5) and that returns a floating-point number (5.0). The operators +, -, * and / work just like in most other languages (for example C); parentheses (()) can be used for grouping.

The division operator also returns a floating-point number. To do floor division and get an integer result you can use the // operator; to calculate the remainder you can use %:

>>> 20/3 # returns a float
6.666666666666667
>>> 20 // 3 # discards fractional part
6
>>> 20 % 3 # returns remainder part
2

It is also possible to use the ** operator to calculate powers and the equal sign (=) is used to assign a value to a variable.

>>> numb = 2
>>> numb **3
8

There is also a special variable in interactive mode (variable _), the last printed expression is assigned to this variable. Let’s now use all these operators and variables to run a simple example in python.

>>> item_price = 100
>>> tax = 15.0
>>> total_price = item_price + tax
>>> total_price
115.0
>>> price_without_tax = _ - tax
>>> price_without_tax
100.0

In addition to int and float, Python also supports Decimals, Fractions, and Complex numbers.

Strings

Python can also manipulate strings and are enclosed by (‘…’) or double quotes (“…”). Whereas \ is used to escape quotes, \n is used for newline and 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. Note that strings are immutable aka an object that has a fixed value and cannot be altered.

>>> 'deja vu'
'deja vu'
>>> 'i didn\'t had deja vu'
"i didn't had deja vu"
>>> print('name \n hello world')
name
hello world
>>> print(r'name \n hello world')
name \n hello world

Like Numbers, Strings also support different operators. The + operator is used for concatenation and string can be repeated by using the * operator.

>>> print ('i had three times ' + 'deja vu ' *3 )
i had three times deja vu deja vu deja vu

There is no special character type in Python and Strings can be indexed with the first character having index 0. Indices can also be negative numbers and in that case the count starts from right. The negative indices start from -1. Attempting to use an index that is too large will result in an error.

>>> word = 'deja vu'
>>> word[0]
'd'
>>> word[5]
'v'
>>> word[100]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> word[-1]
'u'

Strings also support a very important operation aka slicing. Slicing is used to obtain substrings from a string. In case, you omit the first index, the slicing starts from 0 and if you omit the last index, the slicing is done till the size of string.

The out-of-range slice values are also handled by Python in a suitable way.

>>> word[0:4] # starts from 0 and excludes the 4th index
'deja'
>>> word[0:4]
'deja'
>>> word[5:]
'vu'
>>> word[0:100]
'deja vu'

Lists

List is also another compound data type that python supports. It is used to group together values. The values in a list are separated by comma and are in between square brackets. List can contain items with different and same type. The slicing method that we have seen before can also be applied to List as well. The slice method returns a shallow copy of the list.

>>> prime = [2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> print(prime)
[2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> prime [:]
[2, 3, 5, 7, 11, 13, 17, 19, 23]
>>> print ("first prime", prime[0:1])
first prime [2]
Unlike strings, Lists are mutable and can be altered.
>>> prime = [0, 3, 5, 7, 11, 13, 17, 19, 23] # 0 is not a prime number
>>> prime [0] = 2 # replace the wrong value
>>> print (prime)
[2, 3, 5, 7, 11, 13, 17, 19, 23]

There are multiple built-in methods that Lists support. The list below shows a non-exhaustive list of those methods.

append()

Used to add an element at the end of list

clear()

Used to remove all the elements from the list

copy()

Used to return a copy of list

count()

Used to return the number of elements with specified values

insert()

Used to add an element at a specified position

sort()

Used to sort the list

pop()

Used to remove the element at a specified position

>>> prime = [2, 3, 5, 7, 11, 13, 17, 19]
>>> prime.append(23)
>>> print (prime)
[2, 3, 5, 7, 11, 13, 17, 19, 23]

List also can contain other lists and in that way, we can create nested list. The below example shows a nested list. The sublist is at index 0 and we can access the elements of that list by two square brackets.

>>> nestedList = [1, 2, ['hello', 1], 3]
>>> print (nestedList)
[1, 2, ['hello', 1], 3]
>>> subList = nestedList[2]
>>> element = nestedList[2][0]
>>> print ("sublist", subList)
sublist ['hello', 1]
>>> print("Element", element)
Element hello

I hope you understood some of the basic concepts of python programming. I will continue this series and will cover more advanced topics.

Until next time. Happy Coding…

Join thousands of data leaders on the AI newsletter. Join over 80,000 subscribers and keep up to date with the latest developments in AI. From research to projects and ideas. If you are building an AI startup, an AI-related product, or a service, we invite you to consider becoming a sponsor.

Published via Towards AI

Feedback ↓