Basics of Python¶
This tutorial covers essential Python concepts, including comments, writing code, and printing information. By the end, you’ll have a clear understanding of these foundational topics.
# This is a comment
Multi-Line Comments¶
Use triple quotes ('''
or """
) to create multi-line comments:
'''
This is also a comment
'''
'\nThis is also a comment\n'
# Creating a variable, most basic form
name = "Dan"
Writing Statements Over Multiple Lines¶
You can split a statement across multiple lines for better readability:
# Writing statements over multiple lines
number = (
1 + 2
+ 7
)
print(number)
10
Alternatively, use a backslash (\
) to indicate that a statement continues on the next line:
# Writing statements over multiple lines using backslash
new_number = 2 + 3 \
+ 10
print(new_number)
15
Writing Multiple Statements on One Line¶
You can write multiple statements on a single line using semicolons (;
):
# Put multiple statements on one line
num1 = 5; num2 = 3 - 2
# Printing a string
print("Hello World")
Hello World
Common Error: If you forget to enclose text in quotes, Python will throw an error because it will interpret the text as a variable name:
# This does not work because "Hello World" is not a variable or a valid data type
print(Hello World)
Cell In[8], line 2 print(Hello World) ^ SyntaxError: invalid syntax. Perhaps you forgot a comma?
Printing a Variable¶
You can print the value of a variable by passing its name to the print()
function:
# Printing a variable
word = "Hello World"
print(word)
Hello World
Printing Numbers¶
Python can print numbers like integers or floats directly:
# Printing a number
print(3.15)
3.15
Printing Multiple Values¶
You can print multiple values at once by separating them with commas:
# Printing multiple values
print(3.15, "This is pi", True)
3.15 This is pi True
# By default, `end='\n'` means a new line after the print statement
print("This is one line", end='\n')
print("This is another line")
This is one line This is another line
Customizing the end
Argument¶
You can change the behavior of print()
by modifying the end
argument:
# Changing the end argument
print("First line", end="---")
print("Second line")
First line---Second line
About the Author¶
This tutorial was created by Dan Kornas.
- GitHub: @dankornas
- LinkedIn: Daniel Kornas
- Twitter: @dankornas
If you have any questions or feedback, feel free to reach out or submit an issue in the AI Learning Hub GitHub repository.