Python Day 2: Quick Commands
1. Print a Message:
print("Hello, TM Nexus Community!")
2. Basic Arithmetic:
5 + 3
# Perform addition (+), subtraction (-), multiplication (*), and division (/) directly in the shell.
3. Define a Variable:
x = 10
print(x)
4. Create a List:
my_list = [1, 2, 3, 4, 5]
print(my_list)
5. Loop Through a List:
for item in my_list:
print(item)
6. Define a Function:
def greet(name):
return f"Hello, {name}!"
print(greet("TM Nexus Community"))
7. Import a Module:
import math
print(math.sqrt(16))
8. String Formatting:
# Formatting strings for cleaner output.
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.") # Using f-strings
9. For Looping with a Range:
i = 0
j = 5
for i in range(j):
print(i) # Prints numbers from 0 to 4
10. Conditional Statements:
10.1 If Statement:
# The if statement is used to test a condition.
age = int(input("Enter your age: "))
if age >= 18:
print("You are an adult.")
10.2 If-Else Statement:
# The if-else statement allows you to execute one block of code if the condition is true and another if it's false.
age = int(input("Enter your age: "))
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
10.3 Elif Statement:
# The elif statement (short for "else if") is used to check multiple conditions.
score = int(input("Enter your score: "))
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D")
11. While Loop:
# The while loop repeats as long as a specified condition is true.
count = 0
while count <= 5:
print(count)
count += 1 # This is equivalent to count = count + 1
12. Lists and Operations:
# Lists can store multiple items in a single variable
my_list = [1, 2, 3, 4, 5]
# Append an item to the list
my_list.append(6)
print(my_list)
# Remove an item from the list
my_list.remove(3)
print(my_list)
13. Dictionaries:
# Dictionaries store data values in key-value pairs.
my_dict = {
"name": "Alice",
"age": 25,
"city": "Wonderland"
}
print(my_dict)
# Accessing values
print(my_dict["name"])
14. User Input:
# To get input from the user, you can use the input() function.
name = input("Enter your name: ")
print(f"Hello, {name}!")
15. Exception Handling:
# Handling errors and exceptions to make code more robust.
try:
# Code that may cause an exception
num = int(input("Enter a number: "))
print(num)
except ValueError:
# Code to handle the exception
print("That's not a valid number!")
« Previous
Next »