0% found this document useful (0 votes)
5 views18 pages

Python Beginners Guide

This document is a comprehensive guide for beginners learning Python, covering fundamental topics such as variables, data types, functions, conditions, loops, and classes. Each section includes definitions, examples, and practice questions to reinforce understanding. The guide emphasizes hands-on learning through coding examples and quizzes.

Uploaded by

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

Python Beginners Guide

This document is a comprehensive guide for beginners learning Python, covering fundamental topics such as variables, data types, functions, conditions, loops, and classes. Each section includes definitions, examples, and practice questions to reinforce understanding. The guide emphasizes hands-on learning through coding examples and quizzes.

Uploaded by

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

🐍

Python for Beginners


A Complete Guide with Examples & Practice Questions
─────────────────────────────────
Topics Covered:
• Variables & Data Types
• Methods & Functions
• Loops
• Conditions (if/else)
• Classes & Objects

Learn by doing — every concept has examples & quiz questions!


Chapter 1: Variables & Data Types
A variable is like a box where you store information. You give the box a name, and put something inside it.
Python figures out the type automatically!

1.1 Variables
Think of a variable like a label on a jar. You name the jar, and put something in it.
EXAMPLE
# Creating variables
name = "Zaid" # stores text
age = 22 # stores a number
height = 5.9 # stores a decimal number
is_student = True # stores True or False

# Printing them
print("Name:", name)
print("Age:", age)
OUTPUT
Name: Zaid
Age: 22

1.2 Data Types


Python has several built-in data types. Here are the most important ones for beginners:

int — Whole Numbers


Used for counting things, like age, score, number of items.
score = 100
items = 5
print(type(score)) # Output: <class 'int'>

float — Decimal Numbers


Used when you need precision, like price, temperature, measurements.
price = 49.99
temperature = 36.6
print(type(price)) # Output: <class 'float'>

str — Text (String)


Used for words, sentences, names. Always wrap in quotes.
city = "Mumbai"
greeting = "Hello, World!"
print(len(city)) # Output: 6 (number of letters)

bool — True or False


Used for yes/no decisions. Only two possible values: True or False.
is_raining = False
has_ticket = True
print(type(is_raining)) # Output: <class 'bool'>

list — Collection of Items


Like a shopping list — holds multiple values in order.
fruits = ["apple", "banana", "mango"]
numbers = [1, 2, 3, 4, 5]
print(fruits[0]) # Output: apple (index starts at 0)
print(fruits[2]) # Output: mango

dict — Key-Value Pairs


Like a real dictionary — you look up a word (key) to get its meaning (value).
student = {
"name": "Zaid",
"age": 22,
"grade": "A"
}
print(student["name"]) # Output: Zaid
print(student["grade"]) # Output: A

💡 Tip: You can check the type of any variable using: print(type(variable_name))

Practice Questions

Q1. What is the data type of: x = "Hello"?

✅ Answer: str (string) — because it is text inside quotes.

Q2. What is the data type of: y = 3.14?

✅ Answer: float — because it has a decimal point.


Q3. How do you store the value 100 in a variable called score?

✅ Answer: score = 100

Q4. fruits = ["apple", "banana", "mango"] — What does fruits[1] give you?

✅ Answer: "banana" — List indexing starts at 0, so index 1 is the second item.

Q5. Write code to create a dictionary with your name and age.

✅ Answer: person = {"name": "Your Name", "age": 20}


Chapter 2: Methods & Functions
A function is a reusable block of code that does a specific job. Instead of writing the same code again and again,
you write it once inside a function and call it whenever needed.

2.1 Defining a Function


Use the def keyword to create a function. Think of it like writing a recipe — define it once, use it many times.
EXAMPLE
# Define the function
def greet():
print("Hello! Welcome to Python!")

# Call the function


greet()
greet() # Can be called multiple times
OUTPUT
Hello! Welcome to Python!
Hello! Welcome to Python!

2.2 Functions with Parameters


Parameters are inputs you send into a function. Like ingredients you give to a recipe.
def greet_person(name):
print("Hello,", name, "!")

greet_person("Zaid")
greet_person("Riya")
OUTPUT
Hello, Zaid !
Hello, Riya !

2.3 Functions that Return a Value


Functions can send a result back using the return keyword.
def add(a, b):
return a + b

result = add(5, 3)
print("Sum:", result) # Output: Sum: 8

# You can also use the return value directly


print(add(10, 20)) # Output: 30
2.4 Built-in Functions
Python comes with many ready-made functions. You don't need to define these — they're already available!
# print() — displays output
print("Hello")

# len() — counts items


print(len("Python")) # Output: 6

# type() — shows data type


print(type(42)) # Output: <class 'int'>

# int(), float(), str() — convert types


print(int("5") + 3) # Output: 8

# input() — take input from user


name = input("Enter your name: ")

2.5 Methods (Functions on Objects)


Methods are functions that belong to a specific data type. You call them using a dot (.) after the variable.
# String methods
text = "hello world"
print([Link]()) # Output: HELLO WORLD
print([Link]()) # Output: Hello World
print([Link]("world", "Python")) # Output: hello Python

# List methods
fruits = ["apple", "banana"]
[Link]("mango") # adds to end
print(fruits) # Output: ['apple', 'banana', 'mango']
[Link]('banana') # removes item
print(fruits) # Output: ['apple', 'mango']

💡 Tip: Difference: A function stands alone (print, len). A method is attached to an object using a dot
([Link](), [Link]()).

Practice Questions

Q1. What keyword is used to define a function in Python?

✅ Answer: def — short for 'define'.

Q2. Write a function called square that returns the square of a number.

✅ Answer: def square(n): return n * n


Q3. What does "Python".upper() return?

✅ Answer: "PYTHON" — the upper() method converts all letters to uppercase.

Q4. What is the difference between a parameter and an argument?

✅ Answer: A parameter is the variable name in the function definition (def greet(name)). An
argument is the actual value you pass when calling the function (greet("Zaid")).

Q5. Write a function add_three that takes 3 numbers and returns their sum.

✅ Answer: def add_three(a, b, c): return a + b + c


Chapter 3: Conditions (if / elif / else)
Conditions let your program make decisions. Think of it like a traffic light — IF green, go. ELIF yellow, slow down.
ELSE, stop!

3.1 The if Statement


Runs a block of code ONLY if the condition is True.
EXAMPLE
age = 18

if age >= 18:


print("You can vote!")
OUTPUT
You can vote!

3.2 if / else
If the condition is True, do this. Otherwise, do that.
marks = 45

if marks >= 50:


print("Passed!")
else:
print("Failed. Try again!")
OUTPUT
Failed. Try again!

3.3 if / elif / else


For multiple conditions, use elif (else if). Python checks each condition in order and stops at the first True one.
score = 75

if score >= 90:


print("Grade: A")
elif score >= 75:
print("Grade: B")
elif score >= 60:
print("Grade: C")
else:
print("Grade: F")
OUTPUT
Grade: B
3.4 Comparison Operators
These are used inside conditions to compare values:
# == means equal to
print(5 == 5) # True

# != means NOT equal to


print(5 != 3) # True

# > greater than, < less than


print(10 > 7) # True
print(3 < 1) # False

# >= greater than or equal, <= less than or equal


print(5 >= 5) # True

3.5 Logical Operators


Combine multiple conditions using and, or, not.
age = 20
has_id = True

# and — BOTH must be True


if age >= 18 and has_id:
print("Entry allowed")

# or — at least ONE must be True


is_weekend = False
is_holiday = True
if is_weekend or is_holiday:
print("Shop is closed")

# not — reverses True/False


is_raining = False
if not is_raining:
print("Go for a walk!")

💡 Tip: Indentation is very important in Python! The code inside an if block must be indented (use 4
spaces or Tab).

Practice Questions

Q1. What keyword handles the 'otherwise' case in a condition?

✅ Answer: else — it runs when none of the if/elif conditions are True.
Q2. Write code to check if a number is positive, negative, or zero.

✅ Answer: if n > 0: print('Positive') elif n < 0: print('Negative') else: print('Zero')

Q3. What is the difference between = and == in Python?

✅ Answer: = assigns a value to a variable (x = 5). == compares two values to check if they are equal (x
== 5 gives True or False).

Q4. What does the and operator do?

✅ Answer: It returns True only when BOTH conditions are True. If even one is False, the result is
False.

Q5. Write a condition to check if a person's age is between 13 and 17 (teenager).

✅ Answer: if age >= 13 and age <= 17: print('Teenager')


Chapter 4: Loops
Loops let you repeat code automatically. Instead of writing print() 100 times, you write it once inside a loop and
it runs 100 times!

4.1 The for Loop


Use a for loop when you know how many times you want to repeat something, or when looping over a list.
EXAMPLE — LOOP THROUGH A LIST
fruits = ["apple", "banana", "mango"]

for fruit in fruits:


print("I love", fruit)
OUTPUT
I love apple
I love banana
I love mango

4.2 for loop with range()


range() generates a sequence of numbers. Perfect for repeating something a specific number of times.
# range(5) gives: 0, 1, 2, 3, 4
for i in range(5):
print("Count:", i)

# range(1, 6) gives: 1, 2, 3, 4, 5
for i in range(1, 6):
print(i)

# range(0, 10, 2) gives: 0, 2, 4, 6, 8


for i in range(0, 10, 2):
print(i) # even numbers

4.3 The while Loop


A while loop keeps running AS LONG AS the condition is True. It's like saying: 'Keep doing this UNTIL something
changes.'
count = 1

while count <= 5:


print("Count is:", count)
count = count + 1 # very important! or it loops forever

print("Done!")
OUTPUT
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Done!

4.4 break and continue


break — Stops the loop immediately. continue — Skips the current step and goes to the next.
# break example — stop at 3
for i in range(1, 10):
if i == 4:
break # stops loop when i is 4
print(i) # prints 1, 2, 3

# continue example — skip 3


for i in range(1, 6):
if i == 3:
continue # skips number 3
print(i) # prints 1, 2, 4, 5

4.5 Nested Loops


A loop inside another loop. The inner loop runs completely for each step of the outer loop.
for i in range(1, 4): # outer loop
for j in range(1, 4): # inner loop
print(i, "x", j, "=", i*j)
OUTPUT
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
2 x 1 = 2
...(continues)

💡 Tip: Use for when you know the number of repetitions. Use while when you repeat until a
condition changes.

Practice Questions

Q1. What does range(1, 5) produce?

✅ Answer: 1, 2, 3, 4 — range() stops BEFORE the last number.


Q2. Write a for loop to print numbers 1 to 10.

✅ Answer: for i in range(1, 11): print(i)

Q3. What keyword stops a loop immediately?

✅ Answer: break — it exits the loop as soon as it is reached.

Q4. Write a while loop that prints even numbers from 2 to 10.

✅ Answer: n = 2 while n <= 10: print(n) n += 2

Q5. What happens if you forget to update the counter in a while loop?

✅ Answer: It creates an infinite loop — the condition never becomes False, and the program keeps
running forever. Always make sure the loop variable changes!
Chapter 5: Classes & Objects
A class is like a blueprint. An object is the actual thing built from that blueprint. Think of a class as the design of a
car, and an object as a real car built from that design.

5.1 Creating a Class


Use the class keyword. Every class usually has a special method called __init__ which runs automatically when
you create an object.
EXAMPLE
class Dog:
# __init__ is the constructor — sets up the object
def __init__(self, name, breed):
[Link] = name # object's own variable
[Link] = breed

def bark(self):
print([Link], "says: Woof!")

def info(self):
print(f"Name: {[Link]}, Breed: {[Link]}")

5.2 Creating Objects


An object is a specific instance made from a class.
# Create two Dog objects
dog1 = Dog("Bruno", "Labrador")
dog2 = Dog("Max", "Poodle")

# Call their methods


[Link]() # Output: Bruno says: Woof!
[Link]() # Output: Max says: Woof!
[Link]() # Output: Name: Bruno, Breed: Labrador
OUTPUT
Bruno says: Woof!
Max says: Woof!
Name: Bruno, Breed: Labrador

5.3 self — What is it?


self refers to the current object. When you call [Link](), Python automatically passes dog1 as self. That's how
the method knows which dog to work with.
class Person:
def __init__(self, name, age):
[Link] = name # [Link] belongs to THIS object
[Link] = age
def introduce(self):
print(f"Hi! I am {[Link]} and I am {[Link]} years old.")

p1 = Person("Zaid", 22)
p2 = Person("Riya", 20)
[Link]() # Hi! I am Zaid and I am 22 years old.
[Link]() # Hi! I am Riya and I am 20 years old.

5.4 Class Attributes vs Instance Attributes


Class attributes are shared by ALL objects. Instance attributes are unique to each object.
class Student:
school = "Python Academy" # Class attribute — same for all

def __init__(self, name, marks):


[Link] = name # Instance attribute — unique per object
[Link] = marks

s1 = Student("Ali", 90)
s2 = Student("Sara", 85)

print([Link]) # Python Academy


print([Link]) # Python Academy (same!)
print([Link]) # Ali
print([Link]) # Sara (different!)

5.5 Inheritance — Reusing Classes


A child class can inherit all properties and methods from a parent class, and add its own on top.
class Animal:
def __init__(self, name):
[Link] = name

def breathe(self):
print([Link], "breathes air.")

class Cat(Animal): # Cat inherits from Animal


def meow(self):
print([Link], "says: Meow!")

c = Cat("Whiskers")
[Link]() # Inherited from Animal!
[Link]() # Cat's own method
OUTPUT
Whiskers breathes air.
Whiskers says: Meow!

💡 Tip: Remember: class is the blueprint, object is the real thing. __init__ sets up each object, self
refers to the object itself.
Practice Questions

Q1. What is the purpose of __init__ in a class?

✅ Answer: It is the constructor — a special method that runs automatically when you create an
object. It sets up the object's initial attributes/data.

Q2. What does self mean inside a class method?

✅ Answer: self refers to the current object (instance) of the class. It lets methods access and modify
the object's own data.

Q3. Create a class Car with attributes brand and speed, and a method drive() that prints a message.

✅ Answer: class Car: def __init__(self, brand, speed): [Link] = brand [Link] =
speed def drive(self): print([Link], 'is driving at', [Link], 'km/h')

Q4. What is inheritance in Python?

✅ Answer: Inheritance lets a child class automatically get all properties and methods from a parent
class. This avoids code repetition.

Q5. What is the difference between a class attribute and an instance attribute?

✅ Answer: A class attribute is shared by ALL objects (defined directly in the class). An instance
attribute is unique to EACH object (defined inside __init__ using self).
Quick Reference — Python Cheat Sheet
A handy summary of everything covered in this guide. Keep this page bookmarked!

Variables & Types


x = 10 # int
y = 3.14 # float
name = "Zaid" # str
flag = True # bool
nums = [1,2,3] # list
info = {"a":1} # dict

Functions
def function_name(param1, param2):
# code here
return result

result = function_name(val1, val2)

Conditions
if condition1:
# code
elif condition2:
# code
else:
# code

Loops
# for loop
for item in collection:
# code

# for with range


for i in range(start, stop, step):
# code

# while loop
while condition:
# code
# update counter!

Classes
class ClassName:
class_attr = 'shared'

def __init__(self, param):


self.instance_attr = param

def method(self):
return self.instance_attr

obj = ClassName('value')
[Link]()

Common Built-in Functions


print(x) # display output
input('msg') # get user input
len(x) # length of string/list
type(x) # check data type
int(x) # convert to integer
float(x) # convert to float
str(x) # convert to string
range(n) # generate numbers 0 to n-1
list(x) # convert to list

Operators Summary
# Arithmetic
+ - * / # add, subtract, multiply, divide
** # power (2**3 = 8)
% # modulus/remainder (10%3 = 1)
// # floor division (7//2 = 3)

# Comparison
== != > < >= <=

# Logical
and or not

🎉 Congratulations on completing Python for Beginners! 🎉


Keep practicing, keep building — happy coding!

You might also like