Second Day At Workshop Python
After installing Python and setting up the virtual environment, the first program we usually write is:
print("Hello, World!")
1. Variables
A variable is a name used to store data in a program.
When we write a program, we need to store different values like name, age, marks, price, address, total amount, and so on. For that, we use variables.
Example:
name = "Ram"
age = 18
Here, name is a variable that stores "Ram".
age is a variable that stores 18.
We can print the values stored in variables using print().
Example:
name = "Ram"
age = 18
print(name)
print(age)
Output:
Ram
18
In Python, we do not need to write the data type manually. Python automatically understands the type of value.
For example:
name = "Sita"
age = 20
Python understands that "Sita" is text and 20 is a number.
A variable name should be meaningful.
Good variable names:
student_name = "Ram"
total_marks = 450
product_price = 500
Bad variable names:
a = "Ram"
x = 450
p = 500
These are not wrong, but they are not clear. Good variable names help us understand the program easily.
Question:
Write a program to store student name, age, and address. Then print all details.
Solution:
name = "Sita"
age = 19
address = "Pokhara"
print("Name:", name)
print("Age:", age)
print("Address:", address)
Output:
Name: Sita
Age: 19
Address: Pokhara
Explanation:
Here, we created three variables.
name stores the student name.
age stores the student age.
address stores the student address.
Then we used print() to display all values.
2. Data Types
Data type means the type of value stored in a variable.
Different types of data are used in programming. Some values are numbers, some are text, some are decimal numbers, and some are true or false values.
Common data types in Python are:
int means integer or whole number.
Example:
age = 20
float means decimal number.
Example:
price = 99.5
str means string or text.
Example:
name = "Ram"
bool means boolean value. It can be either True or False.
Example:
is_student = True
list means collection of multiple values.
Example:
marks = [80, 90, 85]
We can check the data type of any variable using type().
Example:
age = 20
price = 99.5
name = "Ram"
is_student = True
marks = [80, 90, 85]
print(type(age))
print(type(price))
print(type(name))
print(type(is_student))
print(type(marks))
Output:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
<class 'list'>
Question:
Write a program to create variables of different data types and print their types.
Solution:
name = "Hari"
age = 21
height = 5.7
passed = True
numbers = [10, 20, 30]
print(type(name))
print(type(age))
print(type(height))
print(type(passed))
print(type(numbers))
Output:
<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>
<class 'list'>
Explanation:
"Hari" is text, so its type is str.
21 is a whole number, so its type is int.
5.7 is a decimal number, so its type is float.
True is a boolean value, so its type is bool.
[10, 20, 30] is a list, so its type is list.
3. Input
Input means taking data from the user.
In real programs, values are not always fixed. Sometimes we need to ask the user to enter data.
For example, in a billing system, the user may enter product name, quantity, and price.
In Python, we use input() to take input from the user.
Example:
name = input("Enter your name: ")
print("Hello", name)
Output:
Enter your name: Ram
Hello Ram
Here, the program asks the user to enter a name. The entered value is stored in the variable name.
Important point:
input() always takes value as a string.
Example:
age = input("Enter your age: ")
print(type(age))
If the user enters 20, Python still treats it as string.
Output:
<class 'str'>
That is why we need type casting when we want to perform mathematical calculations.
Question:
Write a program to take name and city from the user and print them.
Solution:
name = input("Enter your name: ")
city = input("Enter your city: ")
print("Your name is", name)
print("You live in", city)
Example Output:
Enter your name: Ram
Enter your city: Kathmandu
Your name is Ram
You live in Kathmandu
Explanation:
The first input() takes the user's name.
The second input() takes the user's city.
Then both values are printed using print().
4. Type Casting
Type casting means converting one data type into another data type.
Sometimes data comes in one type, but we need it in another type.
For example, input() gives value as string. But if we want to add two numbers, we must convert them into integer or float.
Common type casting functions are:
int() converts value into integer.
float() converts value into decimal number.
str() converts value into string.
Example:
num = "10"
num = int(num)
print(num)
print(type(num))
Output:
10
<class 'int'>
Here, "10" was a string. After using int(), it became an integer.
Why type casting is needed:
a = input("Enter first number: ")
b = input("Enter second number: ")
print(a + b)
If user enters 10 and 20, output will be:
1020
This happens because both values are strings. Python joins strings using +.
Correct way:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(a + b)
Output:
30
Question:
Write a program to take two numbers from the user and print their sum.
Solution:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
total = a + b
print("Total is", total)
Example Output:
Enter first number: 10
Enter second number: 20
Total is 30
Explanation:
input() takes values from the user.
int() converts those values into numbers.
Then + adds the numbers.
Without int(), Python would join the values as strings.
5. Operators
Operators are symbols used to perform operations.
For example:
a = 10
b = 5
print(a + b)
Here, + is an operator.
It adds two numbers.
Common arithmetic operators are:
+ is used for addition.
- is used for subtraction.
* is used for multiplication.
/ is used for division.
// is used for floor division.
% is used to find remainder.
** is used for power.
Example:
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
Explanation:
10 + 3 gives 13.
10 - 3 gives 7.
10 * 3 gives 30.
10 / 3 gives decimal division result.
10 // 3 gives only the whole number part.
10 % 3 gives the remainder.
10 ** 3 means 10 to the power 3.
Question:
Write a program to take two numbers and perform addition, subtraction, multiplication, and division.
Solution:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
Example Output:
Enter first number: 20
Enter second number: 5
Addition: 25
Subtraction: 15
Multiplication: 100
Division: 4.0
Explanation:
The program takes two numbers from the user.
Then it uses different operators to perform calculations.
+ adds the values.
- subtracts the values.
* multiplies the values.
/ divides the values.
6. Conditional Statement
Conditional statement is used to make decisions in a program.
Sometimes we want to run code only when a condition is true.
For example:
If age is greater than or equal to 18, the person can vote.
Otherwise, the person cannot vote.
Example:
age = 18
if age >= 18:
print("You can vote")
else:
print("You cannot vote")
Output:
You can vote
Here, Python checks the condition:
age >= 18
If the condition is true, the code inside if runs.
If the condition is false, the code inside else runs.
Example with marks:
marks = 75
if marks >= 40:
print("Pass")
else:
print("Fail")
Output:
Pass
Question:
Write a program to check whether a number is even or odd.
Solution:
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
Example Output:
Enter a number: 7
Odd number
Explanation:
The % operator gives the remainder.
If a number is divided by 2 and the remainder is 0, the number is even.
For example:
8 % 2
gives 0, so 8 is even.
But:
7 % 2
gives 1, so 7 is odd.
7. For Loop
A for loop is used to repeat code.
When we want to do the same work again and again, we use loops.
Example:
for i in range(5):
print(i)
Output:
0
1
2
3
4
Here, range(5) gives numbers from 0 to 4.
The loop runs one time for each number.
First time, i is 0.
Second time, i is 1.
Third time, i is 2.
This continues until 4.
Example:
for i in range(1, 6):
print(i)
Output:
1
2
3
4
5
Here, range(1, 6) starts from 1 and stops before 6.
So it prints 1 to 5.
Example with step:
for i in range(1, 10, 2):
print(i)
Output:
1
3
5
7
9
Here:
1 is the starting value.
10 is the stopping value, but it is not included.
2 is the step value.
Question:
Write a program to print numbers from 1 to 10 using for loop.
Solution:
for i in range(1, 11):
print(i)
Output:
1
2
3
4
5
6
7
8
9
10
Explanation:
range(1, 11) starts from 1.
It stops before 11.
So the loop prints numbers from 1 to 10.
Each value is stored in i one by one and printed.
8. Iterable
An iterable is something that we can loop through.
In simple words, iterable means a value that gives items one by one.
Examples of iterables are:
String
List
Range
Tuple
Dictionary
A string is iterable because we can get each letter one by one.
Example:
name = "Ram"
for letter in name:
print(letter)
Output:
R
a
m
Here, Python reads the string letter by letter.
A list is also iterable.
Example:
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
mango
Here, Python reads the list item by item.
So, when we use a for loop, we mostly loop through an iterable.
Question:
Write a program to print each letter of the word Python.
Solution:
word = "Python"
for letter in word:
print(letter)
Output:
P
y
t
h
o
n
Explanation:
The word "Python" is a string.
A string is iterable.
So the for loop takes one letter at a time and prints it.
9. List
A list is used to store multiple values in one variable.
Example:
fruits = ["apple", "banana", "mango"]
Here, fruits is a list.
It stores three values.
Lists are useful when we have many related values.
Example:
marks = [80, 90, 75, 85]
Instead of creating many variables like this:
mark1 = 80
mark2 = 90
mark3 = 75
mark4 = 85
We can store all marks in one list.
marks = [80, 90, 75, 85]
Accessing list items:
List index starts from 0.
Example:
fruits = ["apple", "banana", "mango"]
print(fruits[0])
print(fruits[1])
print(fruits[2])
Output:
apple
banana
mango
Here:
fruits[0] gives "apple".
fruits[1] gives "banana".
fruits[2] gives "mango".
Adding item to list:
fruits = ["apple", "banana"]
fruits.append("mango")
print(fruits)
Output:
['apple', 'banana', 'mango']
append() adds a new item at the end of the list.
Removing item from list:
fruits = ["apple", "banana", "mango"]
fruits.remove("banana")
print(fruits)
Output:
['apple', 'mango']
remove() removes the given item from the list.
Looping through list:
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
mango
Question:
Write a program to find total marks from a list.
Solution:
marks = [80, 90, 75, 85]
total = 0
for mark in marks:
total = total + mark
print("Total marks:", total)
Output:
Total marks: 330
Explanation:
marks is a list.
At first, total is 0.
The for loop takes each mark from the list.
First, 80 is added to total.
Then, 90 is added.
Then, 75 is added.
Then, 85 is added.
Finally, the total becomes 330.
10. Function
A function is a reusable block of code.
When we write the same code again and again, our program becomes long and difficult to manage.
To solve this problem, we use functions.
A function is created using def.
Example:
def greet():
print("Hello")
greet()
Output:
Hello
Explanation:
def is used to define a function.
greet is the function name.
The code inside the function runs only when we call the function.
Here:
greet()
calls the function.
Why do we use functions?
We use functions to avoid repeating code.
We use functions to make code clean.
We use functions to divide a big program into small parts.
We use functions to reuse code many times.
Function with parameter:
A parameter is a value received by a function.
Example:
def greet(name):
print("Hello", name)
greet("Ram")
greet("Sita")
Output:
Hello Ram
Hello Sita
Explanation:
Here, name is a parameter.
When we call the function, we send a value.
In greet("Ram"), "Ram" is sent to the function.
So the function prints:
Hello Ram
Function with return:
return sends value back from the function.
Example:
def add(a, b):
return a + b
result = add(10, 20)
print(result)
Output:
30
Explanation:
The function receives two numbers.
It adds them.
Then it returns the answer.
The returned answer is stored in result.
Difference between print and return:
print() only displays the value.
return sends the value back so we can use it later.
Example:
def add(a, b):
return a + b
answer = add(10, 20)
final = answer + 50
print(final)
Output:
80
Here, the returned value is used again in another calculation.
Function Question 1:
Create a function to add two numbers.
Solution:
def add(a, b):
total = a + b
return total
answer = add(10, 20)
print("Sum is", answer)
Output:
Sum is 30
Explanation:
The function name is add.
It receives two values: a and b.
Inside the function, both values are added.
The result is returned using return.
Then the returned value is stored in answer.
Function Question 2:
Create a function to check whether a number is even or odd.
Solution:
def check_even_odd(num):
if num % 2 == 0:
return "Even"
else:
return "Odd"
number = int(input("Enter a number: "))
result = check_even_odd(number)
print(result)
Example Output:
Enter a number: 8
Even
Explanation:
The function receives a number.
Inside the function, we check:
num % 2 == 0
If the remainder is 0, the number is even.
Otherwise, the number is odd.
The function returns "Even" or "Odd".
Function Question 3:
Create a function to find total marks from a list.
Solution:
def calculate_total(marks):
total = 0
for mark in marks:
total = total + mark
return total
student_marks = [80, 90, 75, 85]
answer = calculate_total(student_marks)
print("Total marks:", answer)
Output:
Total marks: 330
Explanation:
The function receives a list of marks.
At first, total is 0.
The for loop goes through each mark.
Each mark is added to total.
Finally, the function returns the total marks.
Function Question 4:
Create a function to find the largest number from a list.
Solution:
def find_largest(numbers):
largest = numbers[0]
for number in numbers:
if number > largest:
largest = number
return largest
numbers = [10, 25, 7, 90, 45]
answer = find_largest(numbers)
print("Largest number is", answer)
Output:
Largest number is 90
Explanation:
The function receives a list of numbers.
At first, we assume the first number is the largest.
largest = numbers[0]
Then the for loop checks each number.
If any number is greater than the current largest number, we update the largest value.
At the end, the function returns the largest number.
Tricky Function Question:
What will be the output of this program?
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("apple"))
print(add_item("banana"))
print(add_item("mango"))
Output:
['apple']
['apple', 'banana']
['apple', 'banana', 'mango']
Explanation:
This is tricky because the default list items=[] is created only once.
It is not created again every time the function is called.
So every function call uses the same list.
First call:
add_item("apple")
The list becomes:
['apple']
Second call:
add_item("banana")
The same list becomes:
['apple', 'banana']
Third call:
add_item("mango")
The same list becomes:
['apple', 'banana', 'mango']
Correct way:
def add_item(item, items=None):
if items is None:
itexuu
items.append(item)
return items
print(add_item("apple"))
print(add_item("banana"))
print(add_item("mango"))
Output:
['apple']
['banana']
['mango']
Explanation:
Here, we used None instead of an empty list.
Every time the function is called without a list, a new empty list is created.
So old values are not reused.
Comments
Join the discussionNo comments yet. Be the first to comment.