Python Variable Examples

This post contains python variable examples. You can start with first example and work your way through rest of the programs. For each program the solution is provided after the source code.

Advertisements
Advertisements

You must try to write the program yourself and compare the results later.

Program 1: Write a program to display the value of variables

Solution:

# filename: greetings.py 
# program to display values of variables

greeting = "Happy Diwali"
print(greeting)

memberID = 343
print("MemberID is",memberID)

Output:

Happy Diwali
MemberID is 343

Program 2: Writing a program to find the area of a rectangle where length of the rectangle is 120 units and breadth is 40 units.

Solution:

# filename : rectangle_area.py
# write a program to find the area of a rectangle with length = 120 units and breadth = 40 units.

length = 120
breadth = 40
area_rectangle = length * breadth
print("Area =",area_rectangle)

Output:

Area= 4800

Program 3: Write a program to display total marks in 3 subjects – Math, English, and Science and include comments to explain your code.

Solution:

# filename : total_marks.py
# write a program to display total marks in 3 subjects - Math, English, and Science and include comments to explain your code.

# marks in three subjects for a student
Math = 77
English = 100
Science = 233

# compute total marks by adding all subject marks

Total_Marks = 77 + 100 + 233

# print total marks 

print("Total Marks","=",Total_Marks)

Output:

Total Marks = 410

Program 4: Python treat every value as an object by assigning a unique ID number. Write a program using function “id()” to display the object unique id.

Solution:

# filename : find_object_id.py
# Write a program to display object unique id using function id()

num = 30
print(id(num))

name = "Ram"
print(id(name))

Output:

1802659376
43805184

Advertisements

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.