0% found this document useful (0 votes)
10 views

Lab 4

The document outlines a lab session for the Fundamentals of Programming course, focusing on data types, type casting, arithmetic operations, user input, string manipulations, and comparison operations in Python. It provides detailed explanations of arithmetic operators, data types, type checking, type casting, and includes multiple examples and tasks for students to practice. The lab aims to enhance students' understanding of basic programming concepts and their application in Python.

Uploaded by

Hamza Afzal
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)
10 views

Lab 4

The document outlines a lab session for the Fundamentals of Programming course, focusing on data types, type casting, arithmetic operations, user input, string manipulations, and comparison operations in Python. It provides detailed explanations of arithmetic operators, data types, type checking, type casting, and includes multiple examples and tasks for students to practice. The lab aims to enhance students' understanding of basic programming concepts and their application in Python.

Uploaded by

Hamza Afzal
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
You are on page 1/ 9

National University of Sciences and Technology

Military College of Engineering – Civil Engineering


Wing
Fundamentals of Programming
CS 114

Course Title Fundamentals of Programming CS 114


Session Lab 4
Objective To introduce students to data types, type casting, arithmetic
operations, user input, string manipulations, and Comparison
operations.
Topics  Datatypes
 Input statement
 Datatype conversion
 Arithmetic operators
 Comparison operators

Arithmetic Operators in Python


Python provides several arithmetic operators for performing mathematical operations.

Arithmetic Operators:
Operator Description Example (a = 10, b = 3) Result
+ Addition a + b 13
- Subtraction a - b 7
* Multiplication a * b 30
/ Division a / b 3.33
// Floor Division a // b 3
% Modulus (Remainder) a % b 1
** Exponentiation a ** b 1000

Example 1:

x = 15
y = 4

print("Addition:", x + y) # Output: 19
print("Subtraction:", x - y) # Output: 11
print("Multiplication:", x * y) # Output: 60
print("Division:", x / y) # Output: 3.75
print("Floor Division:", x // y) # Output: 3
print("Modulus:", x % y) # Output: 3
print("Exponentiation:", x ** y) # Output: 50625

Output:
Addition: 19

Subtraction: 11

Multiplication: 60

Division: 3.75

Floor Division: 3

Modulus: 3

Exponentiation: 50625

Precedence of Arithmetic Operators in Python

Operator Description
** Exponentiation Operator
%, *, /, // Modulos, Multiplication, Division, and Floor Division
+, – Addition and Subtraction operators

Arithmetic operators in Python follow the standard mathematical order of operations, also known
as BODMAS/BIDMAS rules:

1. Brackets
2. Orders (exponentiation, **)
3. Division and Multiplication (/, *, //, %)
4. Addition and Subtraction (+, -)

Input from the User


input () function first takes the input from the user and converts it into a string.When the input
function is called it stops the program and waits for the user’s input. When the user presses enter,
the program resumes and returns what the user typed. Input should be stored in variable to
retrieve it later.

Example 2:

Name = input("Enter your name: ")


print("Hello,", name)
Output:

Enter your name: ali


Hello, ali

What are Data Types?


When we write a program, we work with different types of information—numbers, text,
true/false values, and more. In Python, each piece of information belongs to a data type, which
tells Python how to store and process it.

Think of data types like different kinds of boxes:

 A number box stores numbers.


 A text box stores words or sentences.
 A true/false box stores yes/no answers.
 A list box stores multiple things together.

Python automatically assigns a data type to each value based on what we write.

Data Types in Python


Python has several built-in data types that are used to store different kinds of values.

Common Data Types in Python:

 Integer (int) → Whole numbers (e.g., 5, 100, -20)


 Floating-point (float) → Numbers with decimals (e.g., 5.5, 3.14, -0.99)
 String (str) → Text values enclosed in quotes (e.g., "Hello", 'Python')
 Boolean (bool) → True or False values
 List (list) → A collection of items (e.g., [1, 2, 3], ["apple", "banana"])
 Tuple (tuple) → Similar to lists but immutable (e.g., (1, 2, 3))
 Dictionary (dict) → Key-value pairs (e.g., {"name": "John", "age": 25})

For today we will look into first four types. Others will be explained later in advanced sessions.

Checking the Data Type

Python provides the type() function to check the data type of a variable.

Example 3: checking datatype

# int
a = 9
print(type(a))
# float
b = 5.4
print(type(b))
# complex
c = 3 + 9j
print(type(c))
#string
x = "Hello World"
print(type(x))
y= " "
print(type (y))
# bool
print(type(True))
print(type(False))

Output:

<class 'int'>

<class 'float'>

<class 'complex'>

<class 'str'>

<class 'str'>

<class 'bool'>

<class 'bool'>

Strings must be written in inverted commas.

Example 4: strings vs other datatypes

a = 9
print(a,type(a))
# float
a = "9"
print(a,type(a))

b = 5.4
print(b,type(b))
b = "5.4"
print(b,type(b))
# complex
c = 3 + 9j
print(c, type(c))
c = "3 + 9j"
print(c, type(c))
# bool
d=True
print(d, type(d))
d="True"
print(d, type(d))

Output:

9 <class 'int'>

9 <class 'str'>

5.4 <class 'float'>

5.4 <class 'str'>

(3+9j) <class 'complex'>

3 + 9j <class 'str'>

True <class 'bool'>

True <class 'str'>

The type of the returned object from input() will always be <class ‘str’>. We will need to change the
type of input in order to manipulate it.

Example 5:

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


print(type(age))

Output:

Enter your age: 20


<class 'str'>

Type Casting (Converting Data Types)


Python allows conversion between different data types using type casting.

Common Type Conversion Functions:

 int() → Converts to an integer


 float() → Converts to a floating-point number
 str() → Converts to a string
 bool() → Converts to a Boolean

Example 6: String to int

a = "100" # String
b = int(a) # Convert string to integer
print(b)
print(type(b))

Output:

100
<class 'int'>

Example 7: Float to integer will truncate decimal part.

x = 5.8
y = int(x) # Convert float to integer
print(y) # Output: 5

Output:

Example 8:

num = 100
text = "The number is " + str(num)
print(text) # Output: The number is 100

Output:

The number is 100


Implicit Type Casting (Automatic Conversion)

1. Python automatically converts some types (implicit conversion).


2. We can also manually convert types (explicit conversion) using casting functions as
discussed above

Python automatically converts smaller types into larger types when needed.

Example 9:

pi = 3.14
whole_number = int(pi)

print(whole_number) # Output: 3

Output:

Example 10:

num1 = input("Enter a number: ") # Always a string


num2 = input("Enter another number: ")

sum_result = int(num1) + int(num2) # Convert to int before adding


print("Sum:", sum_result)

Output:

Enter a number: 1

Enter another number: 2

Sum: 3

Boolean Values and Comparison Operators


Boolean values are True or False, often used in conditions.

Comparison Operators:
Operator Meaning Example (a = 5, b = 3) Result
== Equal to a == b False
!= Not equal to a != b True
> Greater than a > b True
< Less than a < b False
>= Greater than or equal a >= b True
<= Less than or equal a <= b False

Example 11:

x = 10
y = 20

print(x > y)
print(x == 10)
print(y != x)
Output:

False

True

True

Example 12: Calculate Average

num1 = int(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))

# Calculate the average


average = (num1 + num2) / 2

# Display the result


print("The average of", num1, "and", num2, "is:", average)

Output:

Enter the first number: 2

Enter the second number: 3.6

The average of 2 and 3.6 is: 2.8

Example 13: Calculate Area of triangle

# Take input from the user


base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))

# Calculate the area


area = 0.5 * base * height

# Display the result


print("The area of the triangle is:", area)

Output:

Enter the base of the triangle: 34

Enter the height of the triangle: 23.4

The area of the triangle is: 397.79999999999995


Tasks
Note: All example output should display you name and cms_id in first line
1. Compile all the examples to get familiar with syntax and take screenshot of the output.
2. Write a program to that take two values from user and then perform the arithmetic
operations Addition, subtraction, multiplication, division, exponentiation and display
the result on the screen
3. Write a program to assign values to two variables by assignment statement. Swap the
values of both the variables:
4. Write a program to input the numeric value to a variable named “year” from user.
Calculate the number of months and print on the screen. NOTE: year is the number of
years for example 5, 6, it is not like 2025
5. Write a program which calculates the Kinetic Energy K.E= ½ m m and v are the inputs
entered by the user
6. If the marks obtained by a student in five different subjects are input through the
keyboard, find out the aggregate marks and percentage marks obtained by the student.
Assume that the maximum marks that can be obtained by a student in each subject is
100.
7. Temperature of a city in Fahrenheit degrees is input through the keyboard. Write a
program to convert this temperature into Centigrade degrees. C = (F-32) /1.8
8. If a five-digit number is input through the keyboard, write a program to calculate the
sum of its digits. (Hint: Use the modulus operator ‘%’)
Sample output: enter a 5 digit single number: 12423 Sum of all digits of the number is
12 NOTE : Your input is a single number not 5 different inputs

Conclusion

You might also like