A Crash Course on Python — Part-2
Last Updated on July 25, 2023 by Editorial Team
Author(s): Adeel
Originally published on Towards AI.
Welcome back to the series of python programming. In my previous blog, I explained some fundamental concepts of python programming. In this series, we will move forward with some other useful concepts.
So, lets Start…
Control Flow Statements
Like other languages, Python also uses different control flow statements. These statements are a little different in syntax. The most common control flow statement is the ‘if’ statement. The if statement can have zero or more elif parts and the else statement is optional. Note that in the below example, input is used to take values from the user.
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
The for statement is python is different from C as it does not provide the iteration step and halting condition. The for statement in python iterates over items of any sequence.
friends = ['arslan','tauseef','irfan']
for friend in friends:
print("My friend name is:" + friend)
Output:
My friend name is:arslan
My friend name is:tauseef
My friend name is:irfan
To iterate over a sequence of numbers, the built-in function range() can be used. The argument in the range function is not the end point of the range and is not considered in the sequence.
for i in range(3):
print(i)
Output:
0
1
2
The range() function also supports other arguments, such as the step size and start and end of the sequence.
for i in range(3, 10, 3):
print(i)
Output:
3
6
9
The range() and length() functions can be combined in specific ways to iterate over the indices of a sequence.
friends = ['arslan','tauseef','irfan']
for i in range(len(friends)):
print(i, friends[i])
Output:
0 arslan
1 tauseef
2 irfan
However, in the majority of cases, we use the enumerate(iterable, start=0) function to iterate over a list.
fabcourses = ['Machine Learning', 'Programming', 'Deep Learning']
list(enumerate(fabcourses))
Output:
[(0, 'Machine Learning'), (1, 'Programming'), (2, 'Deep Learning')]
The break statement in python is used in the same way as in C. It is used to break out of the innermost enclosing of loop i.e., for or while.
while True:
line = input('> ')
if line == 'done':
break
print(line)
print('Done!')
Output:
> done
Done!
On the other hand, the continue statement continues with the next iteration of the sequence.
while True:
line = input('> ')
if line[0] == '#':
continue
if line == 'done':
break
print(line)
print('Done!')
Output:
> #
> done
Done!
Functions
In programming, functions are a sequence of statements that perform a specific computation. Function in python is created using the def keyword followed by the function name and the parameter list in parenthesizes. Python does not support curly brackets to start and end the body of a function and hence the statements in the function body should be indented.
def myfunc(company, monthlyRevenue):
name = company
revenue= monthlyRevenue
print("Company name is: " + name, "\nRevenue in dollars is: " + str(revenue))
#calling function
myfunc("Squareknot", 100000)
Output:
Company name is: Squareknot
Revenue in dollars is: 100000
The function in python can also use default values for one or more arguments. In that case, there are fewer arguments to specify a value for during a function call.
def student(firstname, lastname ='Azaan', standard ='PlayGroup'):
print(firstname, lastname, 'studies in', standard, 'Standard')
#Function call
student("Muhammad")
Output:
Muhammad Azaan studies in PlayGroup Standard
Python also supports an anonymous inline function that consists of a single expression. The function is known as the lambda function. The syntax to create such as function is lambda [parameters]: expression. The below lambda function gets a string and converts it into upper case.
str1 = 'python programming'
# lambda returns a function object
upper = lambda string: string.upper()
print(upper(str1))
Output:
PYTHON PROGRAMMING
Tuples
Python supports a variety of built-in data structures. Tuples are another one of them. Unlike Lists, Tuples are immutable and usually contain a heterogeneous sequence of items. Tuples are enclosed by brackets (however, you can sometimes skip the brackets for the creation of tuples). Tuples are immutable, so in case anyone wants to store the latitude and longitude of their home in a data structure, tuples can be used.
targetClass = (0,1,2,3,4)
print(targetClass)
print(type(targetClass))
Output:
(0, 1, 2, 3, 4)
<class 'tuple'>
Sets
A Set object in python is an unordered list of elements with no duplicate elements. It also supports different mathematical operations like union and intersection. To create a set curly bracket or the set( ) function is used.
friends = {'irfan', 'tauseef', 'arslan', ‘arslan’}
print(friends)
Output: {'irfan', 'arslan', 'tauseef'}
type (friends)
Output: set
Dictionaries
Dictionaries are one of the most powerful data structures that python supports and can be thought of as key value pairs. Unlike sequences, dictionaries are indexed by a range of keys rather than numbers. The keys can be of immutable types like strings and numbers. As discussed previously, tuples are immutable data structures and hence can be used as a key for dictionaries.
tel = {'Adeel': 4098, 'Tauseef': 4139}
tel['Arslan'] = 4127
print(tel)
print(list(tel))
print(sorted(tel))
Output:
{'Adeel': 4098, 'Tauseef': 4139, 'Arslan': 4127}
['Adeel', 'Tauseef', 'Arslan']
['Adeel', 'Arslan', 'Tauseef']
Looping works elegantly in dictionaries. To get both the keys and the values, items( ) function is used.
for k,v in tel.items():
print (k,v)
Output:
Adeel 4098
Tauseef 4139
Modules
A module is a file containing python definitions and statements that can be imported into other python programs. The module can define different functions and classes. It makes the code logically understandable and less complex. In python, we can import a module using the following statement: import module. In the below example, we have imported a module sqrt from the math library.
from math import sqrt
print(sqrt(16))
Output:
4.0
So that was it for this blog. I hope you understand the fundamental concepts of python programming. If you want to read more about python, data science, or machine learning, please do follow me on medium.
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