EXAMPLE OF BASIC CODING IN PYTHON PROGRAMING
Some basic examples in the Python programming language.
1. Variables and Data Types:
In Python, you can create variables to store values. Python has several built-in data types, including integers, floats, strings, and booleans.
# Variable assignment
name = "John"
age = 25
height = 1.75
is_student = False
# Printing variables
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is Student:", is_student)
2. Input and Output:
You can take user input using the input()
function and display output using the print()
function.
# Getting user input
user_name = input("Enter your name: ")
print("Hello, " + user_name + "!")
3. Conditional Statements:
Conditional statements allow you to make decisions in your code.
# Simple if-else statement
num = int(input("Enter a number: "))
if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")
4. Loops:
Loops are used to repeat a block of code.
# While loop
counter = 0
while counter < 5:
print("Count:", counter)
counter += 1
# For loop
for i in range(5):
print("Index:", i)
5. Functions:
Functions allow you to organize your code into reusable blocks.
# Simple function
def greet(name):
print("Hello, " + name + "!")
# Call the function
greet("Alice")
6. Lists:
Lists are a versatile data structure in Python to store multiple values.
# Creating a list
fruits = ["apple", "orange", "banana"]
# Accessing elements
print("First fruit:", fruits[0])
# Iterating through the list
for fruit in fruits:
print(fruit)