Introduction to Python: Unlocking Simplicity in Programming
Nidhi Gahlawat
Software Engineer at Microsoft | Writing on Medium | SDE Intern'22 at Visa | NSUT'23 | AWS Udacity scholar'21
In my first year of college, there was a subject called “Computer Programming” which included an introduction to C and Python. Although I knew C++ from school, I dreaded Python back then. It wasn’t my first programming language, but I still had preconceived notions about it.
Fast forward 2 years, I was teaching Python to my younger brother who has Python in his school curriculum. And now I can say, it’s a very simple, easy to understand and quite straightforward (qualities which are rare to find in people, just kidding, or am I?) language.
This article is for all the people who dread this programming language or are?new to programming.
Installation
Now, to write code and run it you can use PyCharm, Visual Studio Code or online compilers like Programiz.
“Hello, world!”
Trust me, learning “Hello, world” as the first program is a tradition you mustn’t break. And, in Python, it’s very easy.
print("Hello, world")
The above line prints hello world using a very straightforward way.
Variables
Say you want to store some value so that you can later access and manipulate it in your program. You need variables for that. If you are aware of other programming languages, you’d know that we need to explicitly write the type of variable (string, integer etc.) but in Python, you don’t need to specify the type. That’s why Python is a dynamically typed language.
Example:
name = "Shaun"
age = 23
print(name, age)
Variable naming rules:
Comments
Comments are used to describe the lines of code. The comments are ignored by the compiler/interpreter while processing the program.
You can use?#?for one-line comments and lines enclosed by?"""?for comments spanning multiple lines.
# this is a single line comment
"""
This is a
multi-line
comment
"""
Input and output
You can take input from the user using?input()?. The input from the user is by default taken as a string data type. So, if you want to have an integer or other datatype, you can use conversion.
name = input("Enter your name ")
print(type(name))
age = int(input("Enter your age "))
print(type(age))
print(name, age)
For input as “Nidhi” and 20, you can see that without conversion the data type is a string. And after taking age and converting it to int, the data type is int.
Control structures
x = int(input("Enter a number "))
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
2. Loops:?Loops allow you to execute the same block of code repeatedly.
i. For loop: A?for?loop is used to iterate over a sequence (such as a list, string, or range) or other iterable objects. We will learn more about lists and strings.?range(start,end,steps)?is used to generate a sequence of numbers.
start?specifies the starting value of the range (inclusive)
stop?specifies the ending value of the range (exclusive)
step?specifies the step or increment value between the numbers.
"""
this will print numbers from 0 to 9,
as range with 1 argument assumes 0 as the start,
and generates numbers from 0 to end-1
"""
for i in range(10):
print(i)
"""
this will print numbers from 5 to 9,
as range with 2 argument generates numbers from start to end-1
"""
for i in range(5,10):
print(i)
"""
this will print numbers from 2 to 9 in an alternate manner,
as range with 3 argument generates numbers from start to end-1
while skipping "step" numbers
"""
for i in range(2,10,2):
print(i)
ii. While loop: allows you to repeatedly execute a block of code as long as a certain condition is true.
count = 0
while count < 5:
print("Count:", count)
count += 1
领英推荐
Data Types
Python has several built-in datatypes. These are needed to store different kinds of data and are chosen according to the need.
Numeric Types
x = 10 # int type
pi = 3.14 # float type
Boolean
bool: Represents either?True?or?False?(used for logical operations).
is_minor = False
String
str: Represents a sequence of characters (e.g., "Hello", 'Python', "42")
name = "Alice"
job = "Software Engineer"
Sequence Types:
fruits = ["apple", "banana", "orange", "mango"]
mixed = [10, "hello", True, 3.14]
empty_list = []
print(fruits)
# accessing elements, the index 0 means first position in the list
print(fruits[0])
# changing elements
fruits[0] = "blueberry"
print(fruits)
# adding elements to the end using 'append'
fruits.append("melon")
print(fruits)
# removing elements from list
fruits.remove("banana") # remove will remove the first occurence of banana, if it doesn't exist it will throw error
print(fruits)
# printing all of them
print("All fruits:")
for fruit in fruits:
print(fruit)
Look at each output and notice how the operation worked.
# creating a tuple
fruits = ("apple", "banana", "orange", "mango")
# accessing elements of tuple
print(fruits[0])
print(fruits[2])
# fruits[0] = "blueberry" # Raises a TypeError since tuples are Immutable
# Tuple length, same can be used for lists
print(len(fruits))
# Checking if an element is in a tuple
print("apple" in fruits) # Output: True
print("blueberry" in fruits) # Output: False
# printing all of them
print("All fruits:")
for fruit in fruits:
print(fruit)
Dictionary
dict?represents a collection of key-value pairs. This is used when we have unique keys which need to be paired with values. For example: In a class, the roll numbers are unique and can be paired with the name of the students.
# Creating a dictionary
data = {1:'Anya', 2:'Daksh', 3:'Maya', 4:'Virat'}
# Accessing values using key
print(data[2])
# Modifying values
data[2] = "Dharam"
print(data)
# Adding a new key-value pair
data[6] = "Shalini"
# Removing a key-value pair
del data[3]
# Checking if a key exists
if 5 in data:
print("The key 5 exists in the dictionary.")
else:
print("The key 5 doesn't exist in the dictionary")
# Getting the number of key-value pairs
print(len(data)) # Output: 4
# Iterating over keys
for key in data:
print(key, data[key])
# Iterating over values
for val in data.values():
print(val)
# Iterating over key-value pairs
for key, value in data.items():
print(key, value)
Set
set?represents an unordered collection of unique elements (e.g., {1, 2, 3}). It is useful when you want to store a collection of items without any duplicates and don't require the order of the elements.
You can perform intersection, union and difference operations on two sets.
# Creating a set
my_set = {1, 2, 3, 4, 5}
# Adding elements to a set
my_set.add(6)
my_set.update([7, 8, 9])
# Removing elements from a set
my_set.remove(3)
my_set.discard(10)
# Checking if an element exists in a set
if 2 in my_set:
print("2 is present in the set.")
# Getting the number of elements in a set
print(len(my_set))
# Iterating over a set
for element in my_set:
print(element)
# Set operations
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Union of two sets
union_set = set1.union(set2)
print(union_set)
# Intersection of two sets
intersection_set = set1.intersection(set2)
print(intersection_set)
# Difference of two sets
difference_set = set1.difference(set2)
print(difference_set)
# Symmetric difference of two sets
symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set)
None
None represents the absence of a value or a null value. It is often used to indicate the absence of a meaningful result or to initialize a variable that may be assigned a value later.
val = None
print(val, type(val))
val = 24
Functions
Functions are blocks of code that can be used whenever we need to perform the same operation or task. For example, you might want to calculate the average of numbers again and again in parts of your program, instead of calculating each time you can define it in a function and call it each time you need an average.
A function is defined using?def?keyword followed by the name of the function having?()?containing the optional parameters. Parameters are variables passed to the function so that they can be used in the function to perform the task.
In the program, we can use the function by calling it using its name followed by arguments inside the parenthesis.
# Defining a function
def greet():
print("Hello, there!")
# Calling a function
greet()
# Function with parameters
def greet_name(name):
print("Hello, " + name + "!")
# Calling a function with arguments
greet_name("Alice")
greet_name("Bob")
# Function with a return value
def average(a, b, c):
return (a + b + c)/3
# Calling a function and storing the result
result = average(5, 3, 4)
print("The average is:", result)
Conclusion
This was an introduction to the fundamentals of Python like variables, comments, data types and functions. Part 2 with?Object-oriented programming (OOP)?concepts and?File handling?in Python coming soon. Stay tuned!