Comments
#This is a comment
print("Hello, World!")
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Variables
A variable is created the moment you first assign a value to it.
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0
VariableName
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
Assigning Muyltiple values
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Output Variables
x = "awesome"
print("Python is " + x)
x = "Python is "
y = "awesome"
z = x + y
print(z)
x = 5
y = "John"
print(x + y)
Built-in Data Types
In programming, data type is an important concept.
Variables can store data of different types, and different types can do different
things.
Python has the following data types built-in by default, in these categories:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
Python Numbers
There are three numeric types in Python:
int
float
complex
x = 1 # int
y = 2.8 # float
z = 1j # complex
print(type(x))
print(type(y))
print(type(z))
Python Casting
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
Strings are Arrays
a = "Hello, World!"
print(a[1])
Looping string
for x in "banana":
print(x)
len()
a = "Hello, World!"
print(len(a))
Check String
txt = "The best things in life are free!"
print("free" in txt)
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
Slicing String
b = "Hello, World!"
print(b[2:5])
b = "Hello, World!"
print(b[:5])
b = "Hello, World!"
print(b[2:])
Modify string
a = "Hello, World!"
print([Link]())
a = "Hello, World!"
print([Link]())
Try it Yourself »
The strip() method removes any whitespace from the beginning or the end:
a = " Hello, World! "
print([Link]()) # returns "Hello, World!"
a = "Hello, World!"
print([Link]("H", "J"))
a = "Hello, World!"
print([Link](",")) # returns ['Hello', ' World!']
Try it Yourself »
Concat
a = "Hello"
b = "World"
c = a + " " + b
print(c)
Format String
age = 36
txt = "My name is John, I am " + age
print(txt)
age = 36
txt = "My name is John, and I am {}"
print([Link](age))
quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print([Link](quantity, itemno, price))
quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print([Link](quantity, itemno, price))