PYTHON PROGRAMMING

Python Basics for Beginners

Learn Python programming step by step with simple explanations, code examples, terminal outputs, and practice questions.

Beginner Friendly Python 3 Code & Output Practice Questions

01. Introduction to Python

Python is a popular programming language used in web development, automation, data analysis, artificial intelligence, and cybersecurity.

Python is beginner-friendly because its syntax is easy to read and understand.

Your First Python Program

The print() function displays information on the screen.

hello.py
PYTHON CODE
print("Hello, World!")
OUTPUT
Hello, World!

Python Comments

Comments help programmers explain their code. Python ignores comments while executing a program. A single-line comment starts with #.

comments.py
# This is a comment
print("Learning Python")
OUTPUT
Learning Python

Python Indentation

Indentation means adding spaces at the beginning of a line. Python uses indentation to group statements inside blocks such as if statements and loops.

indentation.py
if 5 > 2:
    print("Five is greater")
OUTPUT
Five is greater

Practice Questions — Python Basics

Question 1: Write a Python program that displays your name.

Show Solution
solution.py
print("My name is Alex")
OUTPUT
My name is Alex

Question 2: Write a program that prints two messages on separate lines.

Show Solution
solution.py
print("Hello")
print("Welcome to Python")
OUTPUT
Hello
Welcome to Python

02. Python Variables

A variable is a name that refers to a value. Variables allow us to store and use information inside a program.

Python does not require us to declare a variable's data type before assigning a value.

Example

variables.py
name = "John"
age = 20

print(name)
print(age)
OUTPUT
John
20

Changing Variable Values

A variable can be assigned a new value. The latest assigned value replaces its previous value.

change_value.py
age = 20
age = 25

print(age)
OUTPUT
25

Variable Naming Rules

Example: student_name is valid, but 2student is invalid.

Practice Questions — Variables

Question 1: Create variables for your name, age, and city. Print all three.

Show Solution
solution.py
name = "Alex"
age = 21
city = "Delhi"

print(name)
print(age)
print(city)
OUTPUT
Alex
21
Delhi

Question 2: Create a variable with value 10, change it to 50, and print it.

Show Solution
solution.py
number = 10
number = 50

print(number)
OUTPUT
50

03. Python Data Types

A data type tells us what kind of value a variable contains. Python supports different types of data, including numbers, text, collections, and Boolean values.

Common Python Data Types

Data Type Example Purpose
int 10 Whole numbers
float 10.5 Decimal numbers
complex 2 + 3j Complex numbers
str "Hello" Text
bool True True or False
list [1, 2, 3] Ordered, changeable collection
tuple (1, 2, 3) Ordered, unchangeable collection
dict {"name": "Alex"} Key-value pairs
set {1, 2, 3} Collection of unique elements
NoneType None Represents no value

Using type()

The type() function tells us the data type of a value.

datatypes.py
name = "Alex"
age = 20
percentage = 95.8
is_student = True

print(type(name))
print(type(age))
print(type(percentage))
print(type(is_student))
OUTPUT
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>

List, Tuple, Set, and Dictionary

collections.py
fruits = ["apple", "banana"]
numbers = (10, 20)
unique = {1, 2, 3}
student = {"name": "Alex", "age": 20}

print(fruits)
print(numbers)
print(sorted(unique))
print(student)
OUTPUT
['apple', 'banana']
(10, 20)
[1, 2, 3]
{'name': 'Alex', 'age': 20}
Remember: Lists can be changed after creation. Tuples cannot be changed after creation. Sets do not guarantee a fixed display order.

Practice Questions — Data Types

Question 1: Create an integer, float, and string. Display their types.

Show Solution
solution.py
a = 10
b = 5.5
c = "Python"

print(type(a))
print(type(b))
print(type(c))
OUTPUT
<class 'int'>
<class 'float'>
<class 'str'>

Question 2: Create a list containing three fruits and print it.

Show Solution
solution.py
fruits = ["apple", "mango", "banana"]
print(fruits)
OUTPUT
['apple', 'mango', 'banana']

04. Type Conversion in Python

Type conversion means changing a value from one data type to another.

For example, we can convert a string containing digits into an integer using int().

Example

conversion.py
number = "123"

print(type(number))

number = int(number)

print(type(number))
print(number + 10)
OUTPUT
<class 'str'>
<class 'int'>
133

Common Conversion Functions

Important: int("hello") causes an error because "hello" is not a valid integer.

Practice Questions — Type Conversion

Question 1: Convert the string "50" into an integer and add 25.

Show Solution
solution.py
number = "50"
number = int(number)

print(number + 25)
OUTPUT
75

Question 2: Convert 12 into a string and display its type.

Show Solution
solution.py
number = 12
text = str(number)

print(type(text))
OUTPUT
<class 'str'>

05. Input and Output in Python

The input() function accepts information entered by the user.

The print() function displays information on the screen.

Taking User Input

input.py
name = input("Enter your name: ")

print("Hello", name)
EXAMPLE TERMINAL SESSION
Enter your name: Alex
Hello Alex

Taking Number Input

The input() function returns a string. We use int() when we need to convert valid whole-number input into an integer.

numbers.py
num1 = int(input("First number: "))
num2 = int(input("Second number: "))

print("Sum:", num1 + num2)
EXAMPLE TERMINAL SESSION
First number: 10
Second number: 20
Sum: 30

Using sep in print()

The sep parameter controls the separator between values displayed by print().

separator.py
print(1, 2, 3, sep="-")
OUTPUT
1-2-3

Practice Questions — Input and Output

Question 1: Ask the user for their name and display a welcome message.

Show Solution
solution.py
name = input("Enter name: ")
print("Welcome", name)
EXAMPLE TERMINAL SESSION
Enter name: Alex
Welcome Alex

Question 2: Ask the user for two numbers and display their multiplication.

Show Solution
solution.py
a = int(input("First: "))
b = int(input("Second: "))

print("Result:", a * b)
EXAMPLE TERMINAL SESSION
First: 5
Second: 4
Result: 20

06. Arithmetic Operators

Arithmetic operators perform mathematical calculations such as addition, subtraction, multiplication, and division.

OperatorPurpose
+Addition
-Subtraction
*Multiplication
/Division
//Floor division
%Remainder
**Exponentiation

Example

arithmetic.py
a = 10
b = 3

print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)
OUTPUT
13
7
30
3.3333333333333335
3
1
1000
Remember: / performs normal division, // performs floor division, and % returns the remainder.

Practice Questions — Arithmetic

Question 1: Find the remainder when 25 is divided by 4.

Show Solution
solution.py
print(25 % 4)
OUTPUT
1

Question 2: Calculate 5 raised to the power of 3.

Show Solution
solution.py
print(5 ** 3)
OUTPUT
125

07. Assignment and Comparison Operators

Assignment Operators

Assignment operators assign or update values stored in variables.

assignment.py
number = 10
number += 5

print(number)

number *= 2

print(number)
OUTPUT
15
30

number += 5 means number = number + 5.

Comparison Operators

Comparison operators compare values and return True or False.

OperatorMeaning
==Equal to
!=Not equal to
>Greater than
<Less than
>=Greater than or equal to
<=Less than or equal to
comparison.py
a = 10
b = 20

print(a == b)
print(a != b)
print(a < b)
OUTPUT
False
True
True

Practice Questions — Assignment and Comparison

Question 1: Start with 20, subtract 5 using an assignment operator, and print the result.

Show Solution
solution.py
number = 20
number -= 5

print(number)
OUTPUT
15

Question 2: Check whether 50 is greater than 30.

Show Solution
solution.py
print(50 > 30)
OUTPUT
True

08. Logical, Identity, and Membership Operators

Logical Operators

Logical operators combine or reverse conditions.

logical.py
a = True
b = False

print(a and b)
print(a or b)
print(not a)
OUTPUT
False
True
False

Identity Operators

Identity operators check whether two variables refer to the same object.

identity.py
a = [1, 2]
b = a
c = [1, 2]

print(a is b)
print(a is c)
print(a == c)
OUTPUT
True
False
True

Here, a and b refer to the same list. The list stored in c has equal contents, but it is a different object.

Membership Operators

Membership operators check whether a value is present in a collection.

membership.py
fruits = ["apple", "banana", "mango"]

print("banana" in fruits)
print("grape" not in fruits)
OUTPUT
True
True

Practice Questions — Logical and Membership

Question 1: Check whether 10 is greater than 5 AND less than 20.

Show Solution
solution.py
number = 10

print(number > 5 and number < 20)
OUTPUT
True

Question 2: Check whether "Python" is present in a list of programming languages.

Show Solution
solution.py
languages = ["Python", "Java", "C"]

print("Python" in languages)
OUTPUT
True

09. Bitwise Operators and Binary Numbers

Computers represent information using binary digits called bits. A bit can have the value 0 or 1.

Binary to Decimal

Binary uses base 2, while decimal uses base 10.

For example, binary 10110 equals decimal 22.

binary.py
number = 0b10110

print(number)
print(bin(22))
OUTPUT
22
0b10110

Bitwise Operators

Bitwise operators work on the binary representation of integers.

OperatorMeaning
&Bitwise AND
|Bitwise OR
^Bitwise XOR
~Bitwise NOT
<<Left shift
>>Right shift

Example

bitwise.py
a = 5
b = 3

print(a & b)
print(a | b)
print(a ^ b)
print(~a)
print(a << 1)
print(a >> 1)
OUTPUT
1
7
6
-6
10
2
Remember: Python's bitwise NOT operator follows the rule ~n = -n - 1. Therefore, ~5 equals -6.

Practice Questions — Binary and Bitwise

Question 1: Convert decimal 10 into binary using Python.

Show Solution
solution.py
print(bin(10))
OUTPUT
0b1010

Question 2: Find the result of shifting 7 left by one bit.

Show Solution
solution.py
print(7 << 1)
OUTPUT
14

10. Beginner Python Projects

Now use the concepts you have learned to create small Python programs.

Project 1 — Sum of Two Numbers

This program asks the user for two numbers and displays their sum.

sum.py
num1 = int(input("First number: "))
num2 = int(input("Second number: "))

result = num1 + num2

print("Sum:", result)
EXAMPLE TERMINAL SESSION
First number: 10
Second number: 20
Sum: 30

Project 2 — Volume of a Sphere

The volume of a sphere is calculated using:

Volume = (4 / 3) × π × radius³

sphere.py
import math

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

volume = (4 / 3) * math.pi * radius ** 3

print("Volume:", round(volume, 2))
EXAMPLE TERMINAL SESSION
Enter radius: 3
Volume: 113.1

Project 3 — Celsius to Fahrenheit

This program converts a temperature from Celsius to Fahrenheit.

Fahrenheit = (Celsius × 9 / 5) + 32

temperature.py
celsius = float(input("Enter Celsius: "))

fahrenheit = (celsius * 9 / 5) + 32

print("Fahrenheit:", fahrenheit)
EXAMPLE TERMINAL SESSION
Enter Celsius: 25
Fahrenheit: 77.0

Final Practice Challenges

Challenge 1: Create a program that calculates the area of a rectangle using user input.

Show Solution
rectangle.py
length = float(input("Length: "))
width = float(input("Width: "))

area = length * width

print("Area:", area)
EXAMPLE TERMINAL SESSION
Length: 10
Width: 5
Area: 50.0

Challenge 2: Write a program that checks whether a number is even or odd.

Show Solution
even_odd.py
number = int(input("Enter number: "))

if number % 2 == 0:
    print("Even")
else:
    print("Odd")
EXAMPLE TERMINAL SESSION
Enter number: 7
Odd

Challenge 3: Write a program that converts kilometers into meters.

Show Solution
distance.py
km = float(input("Kilometers: "))

meters = km * 1000

print("Meters:", meters)
EXAMPLE TERMINAL SESSION
Kilometers: 2
Meters: 2000.0

Additional Python Learning Resources

You can learn more and practice Python using these resources.

Learning Tip: Try every question yourself before opening its solution. Reading code is helpful, but writing your own programs is the best way to improve.