0% found this document useful (0 votes)
6 views36 pages

Python Programming Basics Explained

test

Uploaded by

pratik.bhatt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views36 pages

Python Programming Basics Explained

test

Uploaded by

pratik.bhatt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Fundamentals

by:Hemant Mehta
Programming Language

Simple Definition:

A programming language is a tool that helps humans give instructions


to a computer in a way it can understand and follow. It acts as a link
between human thinking and computer functions, allowing us to
create software, websites, applications, and more.
What is Coding

Coding is the process of writing and structuring commands in a


programming language to instruct a computer to perform specific
tasks. It involves logic, problem-solving, and creativity, and is
fundamental to creating software and applications that power modern
technology.
Basics of Programming Language
● Every spoken language has its own Grammar and Vocabulary (For Eg: Hindi, English,
Gujarati etc) on similar lines we have Syntax & Commands in a programming
language.

● For Spoken Language: Vocabulary refers to the set of words known and used
within a language by a particular individual, community, or within a specific context
or domain.

● For Programming Language: Commands are similar to vocabulary, They are the
basic elements that a programmer uses to instruct the computer to perform specific
tasks.
Basics of Programming Language

● For Spoken Language: Grammar is a set of rules that govern how


words, phrases, and sentences are used in a language, both written and
spoken.

● For Programming Language: Syntax acts like the way Grammar acts,
the set of rules that govern the structure of a programming language's
symbols, punctuation, and words.
What is Python

Python is a high-level, interpreted programming language known for its


easy-to-read syntax and powerful capabilities.

Features
● Interpreted: Python code is executed line by line, which makes debugging easier.
● High-Level: Python abstracts away many complex details, making it easier for
beginners.
● Versatile: Used in various domains like web development, data science, AI,
automation, etc.
Why Learn Python?
Popularity: Python is one of the most widely used programming languages
in the world.
Community Support: A large community means lots of resources and help
available.
Real-World Applications: Python is used by companies like Google, NASA,
and Netflix.

Wide Applications: Web Development, Data Science & Data Analytics,


Artificial Intelligence & Machine Learning, Automation & Scripting, Software
Development, Creating Applications etc.
Python Syntax Comparison
● 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 uses indentation to indicate a block of code. Indentation refers


to the spaces at the beginning of a code line.
Python Data Types
Variables can store data of different types, and different types can do different
things.

Python has many data types built-in by default, some of them are given below:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict

You can get the data type of any object by using the type() function
Example:
x = 5
print(type(x))
Variables
● Variables are containers for storing data values
● Python has no command for declaring a variable. A variable
is created the moment you first assign a value to it
Example 1: Example 2:
x = 3 Name = “Alex”
y = “John” Age = 15
print(x) print(Name)
print(y) print(Age)
Naming Variables
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).

Rules for naming variables in python:

1) A variable name must start with a letter or the underscore character.

2)A variable name cannot start with a number.

3)A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _
).

4)Variable names are case-sensitive (age, Age and AGE are three different variables).

5) A variable name cannot be any of the Python keywords.


Naming Variables
Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

Illegal variable names: (Will Give Errors)


2myvar = "John"
my-var = "John"
my var = "John"
Print Command
The print() function is used in Python to display output on the screen. It can
print text, numbers, variables, and even the results of expressions.

Examples:
print("Hello, World!") Output: Hello World

print("hi", "\n", "John") Output: hi


John

print("hi", “\t” , "john") Output: hi john

age = 10
print("your age is =", age) Output: your age is = 10
Input Command
The input() function is used to take input from the user.
It pauses the program and waits for the user to type something and press Enter

Example1
name = input("Enter your name: ") Output: Enter your name:

Example 2
A = input(“Enter First Number”) Output: Enter First Number
B = input(“Enter Second Number”) Enter Second Number
Comments
● Comments can be used to explain Python code
● Comments can be used to make the code more readable
● Comments can be used to prevent execution when testing
code
● Comments starts with a #, and Python will ignore them
Comment Examples
Examples:
#This is an example of a comment
print("Hello, World!")

print("Hello, World!") #This is another way to write comment

#This is a comment
#written in
#more than just one line
print("Hello, World!")
Multiline Comments
Python will ignore string literals that are not assigned to a variable, you
can add a multiline string (triple quotes) in your code
Example:
""" This is a multi line comment
written in
more than just one line """

print("Hello, World!")
Conditional Statements
● Conditional statements are used in programming to make decisions
based on certain conditions.
● In Python, conditional statements allow the program to execute a
block of code only if a specific condition is true.
● These statements are fundamental in controlling the flow of a
program, enabling it to respond differently to various inputs or
situations.
Conditional Statements
Types:
● ‘ if ’ statement: Executes a block of code if the condition is true.
● ‘if-else’ statement: Executes one block of code if the condition is
true and another block if the condition is false.
● ‘if-elif-else’ statement: Checks multiple conditions, executing the
corresponding block of code for the first true condition. If none of
the conditions are true, the else block is executed.
Conditional Statements
if-else statements allow you to make decisions in your program.
Based on certain conditions, you can execute different blocks of code.
Basic Syntax:
if condition:
code to execute if condition is True
else:
code to execute if condition is False

Example Usage:
age = 15
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
Conditional Statements
When there are multiple conditions to be checked ‘elif’ keyword is used.

Example:
A = input(“Enter a number”)
if A > 0:
print(“The number entered is positive”)
elif A == 0:
print(“The number entered is a zero”)
else:
print(“The number entered is negative”)
List
● Lists are used to store multiple items in a single variable.
● Lists in Python are powerful tools that allow you to store and
manipulate collections of data efficiently.

Creating a list:
You can create a list by placing comma-separated values inside square
brackets [ ]

Example:
my_list = [1, 2, 3, "apple", True,"Alex","Alice", 40.359]
List
Creating a list:
It is also possible to use the list( ) constructor when creating a new list.

Example:
myList1 = list(("apple", "banana", "cherry")) # note the double
round-brackets

print(thislist)

Output:
['apple', 'banana', 'cherry']
List Indexing
● The position allocated to each element within a list is referred to as
the index of that element.
● In Python, the first element of a list is always assigned an index
number of 0, while the last element is assigned an index of -1
● This negative indexing allows easy access to elements from the
end of the list, with -1 referring to the last element, -2 to the second
last, and so on.
List Indexing
Example:
list1 = [ “Apple”, “Fish”, “Tiger”, “Dragon”, 50, False,
“Myna”]

● In this list1, the element "Apple" is located at index 0, "Fish" is at


index 1, "Tiger" at index 2, "Dragon" at index 3, and so forth.

● Similarly, the element "Myna" is at index -1, "False" is at index -2, and
the value 50 is at index -3, counting backward from the end of the
list.
Accessing List
Example:
list1 = [ “Apple”, “Fish”, “Tiger”, “Dragon”, 50, False, “Myna”]
print(list[3])

Output: Dragon

Explanation:
print(list1[3]): This command tells python to go in list1 and print the element
which is at index number 3

print(list1[-1]): This will give output ‘Myna’ as it is the last element in the list
Index Slicing
Slicing in Python allows you to access a range of elements from a list by
specifying a start and end index

Consider list1[ a : b ]
● Here a = Starting Index and b-1 = end index (Always 1 less than
specified value)
● Number assigned to starting index should always be smaller than end
index
Index Slicing
Example:
list1 = [ “Apple”, “Fish”, “Tiger”, “Dragon”, 50, False, “Myna”]
print(list1[1:6])

Output: ['Fish', 'Tiger', 'Dragon', 50, False]

Explanation:
[1:6] means we include elements from index 1 to index 5. The end index 6 is not
included because it is always 1 less than the end of the range.
So, the elements at indices 1, 2, 3, 4, and 5 are printed as the output.
Index Slicing
Example:
list1 = [ “Apple”, “Fish”, “Tiger”, “Dragon”, 50, False, “Myna”]
print(list1[:4])
print(list1[2:])
Output:
['Apple', 'Fish', 'Tiger', 'Dragon']
['Tiger', 'Dragon', 50, False, 'Myna']

Explanation:
[:4] If no number is specified before the colon, Python starts from the beginning
of the list and prints up to index 3.
[2:] If no number is specified after the colon, Python starts from the given
position (index 2) and prints up to the last element of the list.
Updating Lists
Updating a list means making changes to it after it has been created. This
can include:
● Adding new items to the list.
● Changing existing items in the list.
● Removing items from the list.
● Changing a part of the list by replacing a section with different items.

Basically, updating a list involves modifying its contents in some


way.
Updating Lists
1) Updating Elements by Index
my_list = [1, 2, 3]
my_list[1] = 20
my_list[2] = “Hi”
print(my_list)

Output: [1, 20,‘Hi’]

Explanation: New elements are added to the list at the specified index,
but this will replace the original elements at that position.
Updating Lists
2) Inserting Elements
my_list = [1, 2, 3]
my_list.insert(1, “Hello”)
my_list.insert(2, “World”)
print(my_list)

Output: [1,‘Hello’,’World’,2, 3]

Explanation: We use the `insert( )` method to add elements to the list at a


specific index. Unlike the last case, this method does not replace any of the
existing elements.
Updating Lists
3) Appending Elements
my_list = [1, 2, 3]
my_list.append(“Hello”)
print(my_list)

Output: [1, 2, 3, 'Hello']

Explanation: The `append( )` method always adds the element to the end
of the list. So, "Hello" is added at the end.
Updating Lists
4) Remove & Pop Method
In Python, both remove( ) and pop( ) are methods used to delete elements from
a list, but they function differently
remove(x):
Purpose: Removes the first occurrence of a specified element x from the list.
Usage: If the element x is found, it is removed from the list. If x is not in the list,
it raises a ValueError.

pop([i]):
Purpose: Removes the element at the specified index. If no index is specified, it
removes the last element in the list.
Usage: If the specified index is out of range, it raises an IndexError.
Updating Lists
4) Remove Method
Examples:
my_list = [“Alex”,“John”,“Alice”,”Stuart”]
my_list.remove(“John”)
print(my_list)

Output:[‘Alex’,’Alice’,’Stuart’]

Explanation: Here we have typed the name of the element which we wanted to
remove and the python did it for us. But if we would have made spelling
mistake of written an element which is not present in the list we would have got
error in the output.
Updating Lists
4) Pop Method
Examples:
my_list = [“Alex”,“John”,“Alice”,”Stuart”]
my_list.pop(1)
print(my_list)

Output:[‘Alex’,’Alice’,’Stuart’]

Explanation: In this case, we got the same result as before. However, this
time we specified the index number of the element we wanted to delete.

You might also like