0% found this document useful (0 votes)
4 views11 pages

Python

The document provides an overview of basic Python concepts including the print() function, variables, input(), and conditional statements. It covers syntax, parameters, variable types, memory concepts, and how to handle user input and conditions in programming. Key features like formatted printing, escape characters, and loops are also discussed.

Uploaded by

Janani V
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)
4 views11 pages

Python

The document provides an overview of basic Python concepts including the print() function, variables, input(), and conditional statements. It covers syntax, parameters, variable types, memory concepts, and how to handle user input and conditions in programming. Key features like formatted printing, escape characters, and loops are also discussed.

Uploaded by

Janani V
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

1.

print()
2. variables
3. input()
4. Conditional Statements

print():
print() in Python is a built-in function used to display output to the console (terminal).

.1. Basic Syntax:


print(object(s), sep=' ', end='\n')

Object - The values you want to print e.g: hello, world


Separator(sep) - Separator string placed between multiple objects. Default is ' ' (a
space).
end - controls what happens after the line is printed. Default is '\n' (newline).

2. Simple Examples:

1. Print a string:
print("Hello", "World")
2. Print numbers:
print(28)
3. Print multiple values:
print("Age:", 21)

3. Important Parameters:

sep (separator)

Used to separate multiple values.


print("Python", "Java", "C++", sep=" - ") - O/P: `Python - Java - C++

end
Controls what is printed at the end (default is newline \n )

print("Hello"), end=' '


print("World")

o/p: Hello World`


4. Printing Variables

name = "Jan"
age = 21

print(name, age)

5. Formatted Printing

An f-string is a way to format strings in Python by placing an f before the string and using
{} to insert variables or expressions directly.

f-strings:

name = "Jan"
print(f"My Name is {name}")

6. Escape Characters

Escape characters in Python start with a backslash \ and let us include special characters
in strings—like newlines, tabs, or quotes.

Common Examples:

Escape Meaning Example Output


`\n` New line print("Hello\nWorld") Hello
World
`\t` Tab space print("A\tB") A B
`\"` Double quote print("She said \"Hi\"") She said "Hi"
`\\` Backslash print("C:\\Path") C:\Path

print("Hello\nWorld") # New line


print("Hello\tWorld") # Tab space

7. Printing Special Things


Print quotes:
print("He said, \"Hello\"") - O/P: He said, "Hello"

8. Printing formatted numbers


pi = 3.14159
print(f"{pi:.2f}")

o/p:
3.14

9. Printing raw strings

Raw strings ignore escape characters like \n or \t , making them ideal for file paths and
regex patterns.

print(r"C:\new_folder\test")

Avoids escape issues ( \n , \t )

10. Printing without newline

for i in range(5):
print(i, end=" ")

o/p:
0 1 2 3 4

Variables:
What is a Variable?

A variable is a container used to store data.

name = "Jan"
age = 20

Here:

name stores a string


age stores a number

Rules for Naming Variables:


Allowed:

my_name = "Jan"
age2 = 21
_user = "admin"
Not allowed:

2age = 20 # starts with number ❌


my-name = "x" # hyphen not allowed ❌

Use:

letters (a-z, A-Z)


numbers (0–9)
underscore _

1. Dynamic Typing:
Python decides the type automatically:

x = 10 # int
x = "Hello" # now string

No need to declare type like in Java/C++

2. Data Types in Variables:

name = "Jan" # str


age = 20 # int
height = 5.7 # float
is_student = True # bool

3. Multiple Assignments:
a, b, c = 1, 2, 3
x = y = z = 100

4. Type Checking:

x = 10
print(type(x))

o/p:
<class 'int'>

5. Type Conversion

Type conversion means changing a value from one data type to another—like converting a
string to an integer.
Types of Conversion

Type Description Example


Implicit Python auto-converts during operations `3` `+` `4.5` → `7.5` (int → float)
Explicit You manually convert using functions `int("5")` → `5` (str → int)

Common Conversion Functions

int("10") # string to integer


float("3.14") # string to float
str(100) # integer to string
bool(0) # integer to boolean → False

Examples:

x = "10"
y = int(x) # convert to integer

num = 5
print(str(num)) # convert to string

6. Variable Scope (basic idea)

Variable scope refers to where a variable can be accessed or modified in a program—


based on where it’s defined.

Types of Scope

Scope Description Example


Local Inside a function; not accessible outside def fun():
x=5
Global Outside all functions; accessible everywhere x = 10
Enclosed In nested functions (nonlocal) def outer():
def inner():
Built-in Predefined names like print, len print("Hello")

Scope defines the visibility of variables—local for functions, global for the whole file, and
enclosed for nested functions.
x = 10 # global

def test():
y = 5 # local

7. Memory Concept

Memory in Python refers to how data is stored and managed during program execution—
especially variables, objects, and references.

🧠 Memory Concepts in Python


Concept Description Example Code Output /
Behavior
RAM - Temporary storage where x = 10 x is stored in
Python keeps variables during RAM
execution
- Python stores variables and
objects in RAM while running
Variable A name that points to a name = "Janani" name refers to a
memory location holding data string in memory
Reference Python uses references to a = [1, 2]; b = a b points to the
access objects, not direct same list as a
memory addresses
Garbage Python automatically deletes x = 100; x = None 100 is garbage
Collection unused objects to free memory collected if
unused
Mutable vs Mutable objects can change in list = [1, 2]; List changes in
Immutable memory; immutable ones [Link](3) place (mutable)
cannot
id() Returns the memory reference x = 5; Shows memory
Function (identity) of an object print(id(x)) location of x

Python manages memory using references and automatic garbage collection, storing
variables in RAM during execution.

a = 10
b = a

Both refer to same value


input()
What is input() ?

input() is used to take user input from the keyboard.

name = input("Enter your name: ")


print(name)

Whatever user types → stored as a string

Important Rule:
input() always returns a string

age = input("Enter age: ")


print(type(age))

o/p:
<class 'str'>

1. Converting Input:

Integer input
age = int(input("Enter age: "))

Float input

price = float(input("Enter price: "))

Example:

name = input("enter your name: ")


age = int(input("enter your age: "))

print(f"My name is {name} and I'm {age} years old")

2. Multiple Inputs:

a, b = input("Enter two numbers: ").split()


print(a, b)

Still strings!
3. Convert them:

a, b = map(int, input("Enter two numbers: ").split())


print(a + b)

The map() function in Python applies a given function to every item in an iterable.

4. Using split() :

data = input("Enter values: ").split()


print(data)

Input:
10 20 30
Output:
['10', '20', '30']

5. Taking list input

nums = list(map(int, input().split()))


print(nums)

1. input() → takes the string "10 20 30" .


2. .split() → splits into list of strings: ["10", "20", "30"] .
3. map(int, ...) → converts each string to integer: [10, 20, 30] .
4. list(...) → makes it a list object.
5. print(nums) → prints the list.
O/P: [10, 20, 30]

Conditional Statements
What are Conditionals?
They allow your program to choose what to do based on conditions.

Example:

If marks > 50 → Pass


Else → Fail

1. if Statement:
age = 18

if age >= 18:


print("You can vote")

Runs only if condition is True

2. if-else :

age = 16

if age >= 18:


print("Adult")
else:
print("Minor")

3. if-elif-else (Multiple Conditions):

marks = 85

if marks >= 90:


print("A Grade")
elif marks >= 75:
print("B Grade")
elif marks >= 50:
print("C Grade")
else:
print("Fail")

4. Comparison Operators:

Operator Meaning
== Equal
!= Not equal
> Greater than
< Less than
Operator Meaning
>= Greater or equal
<= Less or equal

5. Logical Operators:

age = 20
has_id = True

if age >= 18 and has_id:


print("Allowed")

Operator Meaning
and Both true
or At least one true
not Reverse

6. Nested if :

age = 20
if age >= 18:
if age >= 21:
print("Can drink (in some countries)")

7. Short-hand (Ternary Operator):

age = 18
result = "Adult" if age >= 18 else "Minor"
print(result)

8. Using input() with Condition:

age = int(input("Enter age: "))

if age >= 18:


print("Eligible")
else:
print("Not eligible")
9. Truthy & Falsy:

if 0:
print("Hello") # won't run

if 1:
print("Hi") # runs

False values:

0 , None , False , "" , []

Loops
What is a Loop?

A loop is used to repeat a block of code multiple times.

Example:

Print numbers 1 to 10
Process a list
Repeat tasks automatically

You might also like