0% found this document useful (0 votes)
8 views1 page

Basic Python Programming Guide

This document provides an introduction to basic Python programming, covering key features, installation, print statements, string manipulation, data types, operators, conditional statements, loops, functions, and exercises for practice. It emphasizes the importance of code readability and variable naming conventions while offering practical examples and exercises to reinforce learning. Additionally, it includes links to external resources and sample programs for further exploration.
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)
8 views1 page

Basic Python Programming Guide

This document provides an introduction to basic Python programming, covering key features, installation, print statements, string manipulation, data types, operators, conditional statements, loops, functions, and exercises for practice. It emphasizes the importance of code readability and variable naming conventions while offering practical examples and exercises to reinforce learning. Additionally, it includes links to external resources and sample programs for further exploration.
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

+91 9150140490 WRITTEN BY

-LOGESHWARAN.R

basic

python

programming

Logeswaran R

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

its simplicity and readability. Some of its key features include:


Easy-to-read synta
Dynamic typin
Object-oriented programming suppor
Extensive standard librar
Interpreted nature, allowing for rapid development and testing
Python is a high-level, interpreted programming language known for

its simplicity and readability. Some of its key features include:


Example Program (Hello World):
print("Hello, world!")

Installing Python
You can download and install Python from the official website

([Link]

Once installed, you can use a text editor or an Integrated Development

Environment (IDE) such as PyCharm, VSCode, or IDLE for coding.

Logeswaran R

Python Print Statement


The print statement in Python is used to output data to the standard

output device, typically the console. It can be used to display text,

variables, and expressions.

Sin gle and Double Quotes


Both single (') and double (") quotes can be used to define strings in

Python.

Escape Characters
Escape characters are used to represent characters that are difficult or

impossible to type directly. They are preceded by a backslash \.

Logeswaran R

r g o ae a o
St in C nc t n ti n
String concatenation is the process of combining strings into one.

Exercise Programs
Exercise 1: Print Your Name

Exercise 2: Print a Quote with Escaped Characters

Exercise 3: Concatenate Strings

Logeswaran R

Exercise 4: Print Numbers with Tabs

These exercises cover basic usage of printing in Python, including

different types of quotes, escape characters, and string concatenation.

They help reinforce understanding through practical examples.

Indentation Error
Indentation error occurs when the spaces or tabs used for indentation in

Python code are incorrect. Python uses indentation to define the

structure of code blocks such as loops, conditional statements, and

function definitions.

C orrect Method:

Logeswaran R

Syntax Error
Syntax error occurs when the Python interpreter encounters code that

violates the syntax rules of the language. It may be due to misspelled

keywords, missing punctuation, or incorrect use of language features

C orrect Method:

Input From User


The input() function is used to take user input from the console. When

used within the print() function, it prompts the user for input and

displays the provided message.

Logeswaran R

Exercise Program

len()
T he len() function is used to get the length of a string, list, tuple, or any

iterable object. When used within the print() function, it displays the length

of the specified object.

Exercise Program

Logeswaran R

Variables in Python
Variables in Python are used to store data values. They can be assigned

different data types and can be manipulated throughout the program


Variables are containers for storing data values
They can hold different types of data such as numbers,
strings, lists, etc
Variable names are case-sensitive and must follow certain
naming rules.

ar a le Naming Rules
V i b
Variable names can contain letters, digits, and underscores
They must start with a letter or an underscore (but it's
recommended to start with a letter)
Variable names cannot start with a digit
They cannot contain spaces or special characters except
underscores
Python keywords cannot be used as variable names
Variable names should be descriptive and meaningful.

Logeswaran R

C amel Case:
In camel case, the first letter of each word is capitalized except
for the first word, and there are no spaces between words
Example: myVariableName, firstName, totalAmount
Sn k C sa e a e:
In snake case, words are lowercase and separated by
underscores (_)
Example: my_variable_name, first_name, total_amount
Pascal Case (or Capitalized Words):
In Pascal case, also known as capitalized words, the first letter of
each word is capitalized and there are no spaces between
words
Example: MyVariableName, FirstName, TotalAmount
These naming conventions are not strict rules enforced by Python, but they
are widely used in the Python community to write readable and
understandable code. It's important to choose one convention and stick to
it consistently within your codebase to maintain code consistency and
readability.

Logeswaran R

Exercise Programs
Prompt for User Details:

Calculate Area of a Rectangle:

Logeswaran R
Swapping Two variables

B and Name enerator G

Logeswaran R

Data Types
Data types in Python represent different types of data such as integers,

floating-point numbers, strings, lists, tuples, dictionaries, etc. ere's a brie H f

explanation of common data types in Python along with exercise program s

and their outputs


nteger (int): Represents hole numbers ithout an decimal point
I w w y

loating point ( loat): Represents numbers ith a decimal point or in


exponential orm
F - f w

String (str): Represents a se uence o characters enclosed ithin


uotes ( or )
q f w

q '' ""

ist (list): Represents an ordered collection o items hich can be o


di erent data t pes
L f , w f

ff y

uple (tuple): Represents an ordered collection o items similar to a


list but immutable (cannot be modi ied)
T f ,

, f

Dictionar (dict): Represents a collection o ke alue pairs here


each ke is associated ith a alue
y f y-v , w

y w v

oolean (bool): Represents rue or alse


B T F

Sets (set): Collections o uni ue elements and the are unordered f q , y .

Logeswaran R
Int

F loat

St in r g

L ist

Logeswaran R
T u ple

Dicti n o ar y

B oolean

S ts e

Logeswaran R
Exercise
Check Data Type:

Calculate Total Cost:

Convert Temperature:

Logeswaran R

len() in numbers

Logeswaran R
Exercise

Logeswaran R

Operators
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like

addition, subtraction, multiplication, division, etc.

Logeswaran R

Precedence
Parentheses (): Parentheses are used to explicitl speci the order o
operations Expressions inside parentheses are e aluated irst
y fy f

. v f

Exponentiation **: Exponentiation has the highest precedence among


arithmetic operators
Unar Arithmetic Operators: Unar plus + and unar minus are
applied to indi idual operands be ore other arithmetic operations
y y y -

v f

Multiplication * Di ision / loor Di ision // and Modulus %: hese


operators are e aluated next rom le t to right
, v , F v , T

v , f f

Addition + and Subtraction -: hese operators are e aluated last


among arithmetic operators rom le t to right
T v

, f f

Comparison Operators: Comparison operators (< <= > >= == !=)


ha e lo er precedence than arithmetic operators
, , , , ,

v w

ogical Operators: ogical operators (not and or) ha e the lo est


precedence among all operators
L L , , v w

3 ** 2 is evaluated first (exponentiation), resulting in 9


2 * 9 is evaluated next (multiplication), resulting in 18
10 + 18 is evaluated (addition), resulting in 28
28 - 1 is evaluated (subtraction), resulting in the final result of 27.

Logeswaran R
Exercise

C omparison Operators
Comparison operators are used to compare two values and return a

Boolean result (True or False).

Logeswaran R
L ogical Operators
Logical operators are used to combine conditional statements

F-Strings
F -strings allow you to embed Python expressions directly inside string

literals by prefixing the string with 'f' or 'F'. You can include variables,

expressions, or function calls within curly braces {} inside the string, and

they will be evaluated at runtime

Logeswaran R
Excersice
Life Calc

T ip Calculator

[Link]
tip_calculator.py

Logeswaran R
round()
T he round() function in Python is used to round a number to a specified

number of digits after the decimal point (by default, it rounds to the nearest

integer). ere are some sample programs demonstrating the usage of the

round() function:

f ormat()

Logeswaran R
I er g Multiple Values:
ns tin

S peci ing Order o


fy f I er o :
ns ti n

F ormat Speci ications: f

Logeswaran R

N amed Arguments (P thon 3 y .6 +):

C onditional Statements
Conditional statements in Python allow you to execute different blocks of

code based on whether a condition is true or false. The most common

types of conditional statements in Python are the if, elif (else if), and else

statements. ere's an explanation along with sample programs and

exercise programs:

S ample Program Logeswaran R

Exercise

Logeswaran R

[Link]
bmi_calcultor.py

N st e ed If

Logeswaran R
Exercise
Leap Year

T reasure Island
[Link]
treasure_island.py
Love calculator
[Link]
love_calculator.py

Logeswaran R

M ultiline String
A multiline string in Python is a string that spans multiple lines and is

enclosed within triple quotes (""" """ or ''' '''). Multiline strings are often used

for docstrings (documentation strings) or for representing long blocks of

text. ere's an example:


H

R andomi ation z

Logeswaran R
G enerating Random Numbers

Shuffling Sequences

Choosing Random Elements

G enerating Random Floats

Logeswaran R
Steps

Exercise
Heads/Tails
[Link]
heads_or_tails.py

List Operations
Append: Add an element to the end of the list using the append()
method
Insert: nsert an element at a speci ic index using the insert() method
I f

Extend: Extend the list b appending elements rom another list using
the extend() method
y f

Remo e: Remo e the irst occurrence o a alue using the remo e()
method
v v f f v v

Pop: Remo e and return an element at a speci ic index using the pop()
method
v f

ndex: ind the index o the irst occurrence o a alue using the
index() method
I F f f f v

Count: Count the number o occurrences o a alue using the count()


method
f f v

Sort: Sort the list using the sort() method


Re erse: Re erse the order o elements in the list using the re erse()
method
v v f v

Logeswaran R

Logeswaran R

Exercise
Find the sum of all elements in a list:

Logeswaran R
Remove duplicates from a list:

Concatenate two lists:

Check if a list is empty:

F ind the second largest element in a list:

Who pay the bill? DIY

Logeswaran R
Rock Paper Scissor
[Link]
rock_paper_scissor.py
Name List Check
[Link]
name_list_check.py

Loops

For oop L

A for loop is used for iterating over a sequence (e.g., a list, tuple, string, etc.).

While oop L

A while loop executes a block of code as long as a condition is true.

Logeswaran R
Exercise
Write a program to calculate the sum of all numbers from 1 to 10 using a for
loop.

Write a program to find the factorial of a number using a while loop.

Write a program to count the number of vowels (a, e, i, o, u) in a given


string using a for loop.

Logeswaran R
Write a program to print the Fibonacci series up to 10 terms using a while
loop.

B reak
T he break statement is used to exit a loop prematurely, before its
normal completion
It's often used when a certain condition is met and there's no need to
continue looping.

o
C ntinu e
T he continue statement is used to skip the rest of the code inside a
loop for the current iteration, and the loop continues with the next
iteration
It's useful when you want to skip certain iterations based on a
condition.

Logeswaran R

Exercise
Write a program to find the smallest number in a list of integers using a for
loop and break statement.

Write a program to print numbers from 1 to 20, but skip multiples of 3


using a for loop and continue statement.

Logeswaran R

Sum of all Even Numbers

i u ame
F zz B zz G

[Link]
[Link]
Password enerator G

[Link]
password [Link] G

Logeswaran R

Functions
Functions in Python are blocks of reusable code that perform a specific

task. They help in organizing code, making it more readable, and reducing

redundancy
e
D finiti n o:
In Python, functions are defined using the def keyword followed by the

function name and parentheses ( ).

You can also specify parameters inside the parentheses if the function

needs input values.

The body of the function is indented.

C alling:
Once a function is defined, you can call it by using its name followed by

parentheses ( ).

If the function takes parameters, you need to provide arguments when

calling it.

Logeswaran R
Example

Exercise
[Link]
lang en mode python menu worlds 2Fmenus 2Freeborg_intr
o_en.json name urdle 201 url worlds 2Ftutorial_en 2Fhurdl
= & = & = % %

[Link]
& =H % & = % %

Import
To import functions from another file in Python, you can use the import
statement.

Logeswaran R
Hangman
[Link]
main/hangman

F uncti n o Parameters and Arguments:


Parameters are the variables listed inside the parentheses in the
function definition
Arguments are the values passed to the function when it is called

Exercise
Write a function called add that takes two numbers as arguments and
returns their sum. Then, call this function with different numbers and print
the result.

Logeswaran R
Write a function called power that takes two numbers as arguments - a
base and an exponent - and returns the result of raising the base to the
exponent. Call this function with different numbers and print the result.

Positional Arguments

K e ord Arguments
yw

Logeswaran R
Excersice
Prime number check
[Link]
main/[Link]
Cipher Text
[Link]
ceaserCipher

Dictionaries
Dictionary Definition
A dictionary is defined using curly braces {}
Each key-value pair is separated by a colon : and pairs are separated
by commas.

Accessing Values
You can access the value associated with a key by specifying the key
inside square brackets [].

Adding, Updating, and emoving Items R

You can add new key-value pairs, update existing values, and remove
items from a dictionary using various methods.

Logeswaran R
Dictionary ethods M

Python provides many built-in methods to work with dictionaries, such


as keys(), values(), items(), get(), etc.

Example

Logeswaran R

N st e ed Dictionaries
A nested dictionary is a dictionary where the values can themselves be
dictionaries
You can have dictionaries within dictionaries to represent data in a
nested structure.

Accessing Values:
You can access values in nested dictionaries by chaining square
brackets [].

Adding, Updating, and Removing Items:


Similar to regular dictionaries, you can add, update, and remove items
from nested dictionaries.

Logeswaran R

It erating O er Nested Dictionaries:v

You can iterate over nested dictionaries using nested loops or list
comprehensions.

Example

Exercise
[Link]
[Link]

Logeswaran R

M Ultiple eturn Values R

Python allows a function to return multiple values by combining them


into a tuple
You can return any number of values from a function, separated by
commas
When a function returns multiple values, they are packed into a tuple
and returned
You can then unpack the tuple into separate variables when calling
the function.

T he calculate_stats function takes a list of numbers as input and


calculates the total, average, maximum, and minimum values
It returns these values as a tuple
When calling the function, we unpack the tuple into separate
variables (total, avg, max_num, min_num)
We then print out the calculated statistics.

Logeswaran R
Exercise
Exercise 1: Write a function called get_circle_info that takes the radius of a
circle as input and returns its circumference and area.

Exercise 2: Write a function called get_student_info that takes a dictionary


containing student information (name, age, grade) as input and returns
these values separately.

Logeswaran R
Calculator
[Link]
main/calculator

Print
T he print statement is used to display output on the console
It s primarily used for debugging purposes or to provide information to
'
the user.
e r
R tu n
T he return statement is used to exit a function and return a value back
to the caller
It's used when you want the result of a function to be used in further
computation or stored in a variable.

Scope
Local Scope
Variables defined inside a function have a local scope
They are accessible only within the function where they are defined.

Logeswaran R

Enclosing (or Nonlocal) Scope


This scope is applicable to nested functions
Variables defined in the enclosing function are accessible in the
nested function

Global Scope
Variables defined outside of any function or block have a global
scope
They are accessible from anywhere in the program.

Logeswaran R
Built-in Scope
T his scope includes all the names that are preassigned in Python
T hese names include built-in functions and built-in exception names.

Exercise

Global
When a variable is defined inside a function without using the global
keyword, it is considered local to that function by default
If you want to modify a global variable from within a function, you need
to use the global keyword to explicitly declare the variable as global.

Logeswaran R

ASCII ART
p : patorjk com/so t are/taag/
htt s //
p d pla &h=2& =2& = lurVision%20ASC &t=M %20Game
. f w

# = is y v f B II y

You might also like