Photo by DATAIDEA

Variables

  • Varibles are used to store values.
  • To create a variable, use the equal sign (=).

In the examples below, we create varibales name fruit and name and we assign them values 'mango' and 'viola' respectively

fruit = 'mango'
name = 'voila'

# printing out
print(name, ' likes ', fruit )
voila  likes  mango

Rules to consider

  • Spaces are not allowed eg
  • Can not start with number eg
  • Can not have special characters eg
  • Are case sensitive

Examples of good variable names

my_favorite_character = 'Stewie Griffin' # snake case
myFavoriteCharacter = 'Meg Griffin' # camel case
MyFavoriteCharacter = 'Brian Griffin' # Pascal case

Data Types

In this section of the tutorial, you will learn the most basic data types in Python

Numbers

These are two basic types of numbers and they are called: - integer(numbers without decimal places) - floating point numbers(numbers with decimal places)

# python numbers
# Integers
age = 45
population = 45000000
# Floating point numbers
height = 1.7
weight = 147.45

Strings

Strings are simply text. A string must be surrounded by single or double quotes

# Strings
name = 'Juma'
other_name = "Masaba Calvin"
statement = 'I love coding'

Single or double quotes?

Use single quotes when your string contains double quotes, or the vice versa.

# when to use which quotes
report = 'He said, "I will not go home"'

String Methods

text = 'shafara VEe'
capitalized_text = text.capitalize()
print('Capitalized:', capitalized_text)

upper_text = text.upper()
print('Upper text', upper_text)

lower_text = text.lower()
print('Lower case text:', lower_text)

corrected_text = text.replace('VEe', 'Viola')
print(corrected_text)

print('shafara' not in text)

Booleans

Boolean data type can onlyhave on fo these values: True or False

# Boolean
married = True
print(married)
True

Lists

  • A list is an ordered collection of data
  • It can contain strings, numbers or even other lists
  • Lists are written with square brackets ([])
  • The values in lists (also called elements) are separated by commas (,)
# Lists
names = ['juma', 'john', 'calvin']
other_stuff = ['mango', True, 38]

print(names)
print(other_stuff)
['juma', 'john', 'calvin']
['mango', True, 38]

Checking data types

To check the data type of an object in python, use type(object), for example, below we get the data type of the object stored in names

# Which data type
type(names)
list

Converting Types

# convert an integer to a string
age = 45
message = 'Peter Griffin is '+ str(age) + ' years old'

# Convert floating point to integer
pi = 3.14159
print(int(pi))
3

A few ads maybe displayed for income as resources are now offered freely. 🤝🤝🤝

Back to top