Python

Python in 30 Days: Day 2 – Variables and Builtin Functions

 

Python in 30 Days: Day 2: Variables and Builtin Functions

Day 2:

Builtin Functions

Python comes with a large number of built-in functions. The built-in functions can be used without importation or configuration because they are globally available for your use. Print(), len(), type(), int(), float(), str(), input(), list(), dict(), min(), max(), sum(), sorted(), open(), file(), help(), and dir() are a few of the most frequently used built-in methods for Python. An extensive list of built-in Python functions is provided in the following table, which is derived from the Python manual.

Built-in Functions
abs() delattr() hash() memoryview() set()
all() dict() help() min() setattr()
any() dir() hex() next() slice()
ascii() divmod() id() object() sorted()
bin() enumerate() input() oct() staticmethod()
bool() eval() int() open() str()
breakpoint() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()

 

Let’s open the Python shell and start using some built-in function

Python has reserved words. We do not use reserved words to declare variables or functions. We will cover variables in the next section.

Variables

Variables store data in a computer’s memory. Many programming languages encourage the use of mnemonic variables. Variables with easily recognizable names are known as mnemonic variables. A variable is a place where data is kept in memory. When naming a variable, the first number, hyphens, and special characters are not permitted. Rather than using a short name (x, y, z), it is desirable to provide a variable with a more descriptive name (firstname, lastname, age, nationality).

Python Variable Name Rules

  • The variable name must start with a letter or the underscore character
  • The variable name cannot start with a number
  • The variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • The variable names are case-sensitive (firstname, Firstname, FirstName and FIRSTNAME) are different variables)
firstname
lastname
age
country
city
first_name
last_name
capital_city
_if # if we want to use reserved word as a variable
year_2022
year2022
current_year_2022
birth_year
num1
num2

Invalid variables names
first-name
first@name
first$name
num-1
1num

We will name our variables using the standard Python format, which is widely used by Python programmers. Python programmers name variables using the snake case (snake_case) convention. When a variable (such as first_name, last_name, engine_rotation_speed) contains more than one word, the underscore character is used after each word. Standard variable naming is demonstrated in the example below; if a variable name consists of more than one word, an underscore is needed.

It’s known as variable declaration when we provide a variable a certain data type. For example, in the example below, the variable first_name has my first name allocated to it. One type of assignment operator is the equal sign. Data is stored in the variable by assigning. Python’s equivalent of the mathematical equal sign is not equality.

Example:
# Variables in Python
first_name = 'Tech'
last_name = 'G'
country = 'India'
city = 'Delhi'
age = 25
is_married = True
skills = ['HTML', 'CSS', 'JS', 'React', 'Python']
person_info = {
   'firstname':'Tech',
   'lastname':'G',
   'country':'India',
   'city':'Delhi'
   }

Let us use the print() and len() built-in functions. The print function takes an unlimited number of arguments. An argument is a value that can be passed or put inside the function parenthesis, see the example below.

Example:

print('Hello, World!') # The text Hello, World! is an argument
print('Hello',',', 'World','!') # it can take multiple arguments, four arguments have been passed
print(len('Hello, World!')) # it takes only one argument

Let us print and also find the length of the variables declared at the top:

Example:

# Printing the values stored in the variables

print('First name:', first_name)
print('First name length:', len(first_name))
print('Last name: ', last_name)
print('Last name length: ', len(last_name))
print('Country: ', country)
print('City: ', city)
print('Age: ', age)
print('Married: ', is_married)
print('Skills: ', skills)
print('Person information: ', person_info)

Declaring Multiple Variables in a Line

Multiple variables can also be declared in one line:

Example:

first_name, last_name, country, age, is_married = 'Tech', 'G', 'India', 25, True

print(first_name, last_name, country, age, is_married)
print('First name:', first_name)
print('Last name: ', last_name)
print('Country: ', country)
print('Age: ', age)
print('Married: ', is_married)

Getting user input using the input() built-in function. Let us assign the data we get from a user into first_name and age variables. Example:

first_name = input('What is your name: ')
age = input('How old are you? ')

print(first_name)
print(age)

Data Types

There are several data types in Python. To identify the data type we use the type built-in function. I would like to ask you to focus on understanding different data types very well. When it comes to programming, it is all about data types. I introduced data types at the very beginning and it comes again because every topic is related to data types. We will cover data types in more detail in their respective sections.

Checking Data Types and Casting

  • Check Data types: To check the data type of certain data/variable we use the type Example:
# Different python data types
# Let's declare variables with various data types

first_name = 'Tech'     # str
last_name = 'G'       # str
country = 'India'         # str
city= 'Delhi'            # str
age = 250                   # int, it is not my real age, don't worry about it

# Printing out types
print(type('Tech'))     # str
print(type(first_name))     # str
print(type(10))             # int
print(type(3.14))           # float
print(type(1 + 1j))         # complex
print(type(True))           # bool
print(type([1, 2, 3, 4]))     # list
print(type({'name':'Tech','age':25, 'is_married':250}))    # dict
print(type((1,2)))                                              # tuple
print(type(zip([1,2],[3,4])))                                   # set
  • Casting: Converting one data type to another data type. We use int()float()str()list, and set When we do arithmetic operations string numbers should be first converted to int or float otherwise it will return an error. If we concatenate a number with a string, the number should be first converted to a string. We will talk about concatenation in the String section.

    Example:

# int to float
num_int = 10
print('num_int',num_int)         # 10
num_float = float(num_int)
print('num_float:', num_float)   # 10.0

# float to int
gravity = 9.81
print(int(gravity))             # 9

# int to str
num_int = 10
print(num_int)                  # 10
num_str = str(num_int)
print(num_str)                  # '10'

# str to int or float
num_str = '10.6'
print('num_int', int(num_str))      # 10
print('num_float', float(num_str))  # 10.6

# str to list
first_name = 'Tech'
print(first_name)               # 'Tech'
first_name_to_list = list(first_name)
print(first_name_to_list)            # ['T', 'e', 'c', 'h']

Numbers

Number data types in Python:

  1. Integers: Integer(negative, zero, and positive) numbers Example: … -3, -2, -1, 0, 1, 2, 3 …

  2. Floating Point Numbers(Decimal numbers) Example: … -3.5, -2.25, -1.0, 0.0, 1.1, 2.2, 3.5 …

  3. Complex Numbers Example: 1 + j, 2 + 4j, 1 – 1j

 Now do some exercises for your brain and muscles.

Exercises – Python in 30 Days: Day 2 – Variables and Builtin Functions

Exercises: Level 1

  1. Inside Pythonin30Days create a folder called day_2. Inside this folder create a file named variables.py
  2. Write a Python comment saying ‘Day 2: Python IN 30 Days Programming’
  3. Declare a first name variable and assign a value to it
  4. Declare a last name variable and assign a value to it
  5. Declare a full name variable and assign a value to it
  6. Declare a country variable and assign a value to it
  7. Declare a city variable and assign a value to it
  8. Declare an age variable and assign a value to it
  9. Declare a year variable and assign a value to it
  10. Declare a variable is_married and assign a value to it
  11. Declare a variable is_true and assign a value to it
  12. Declare a variable is_light_on and assign a value to it
  13. Declare multiple variables on one line

Exercises: Level 2

  1. Check the data type of all your variables using the type() built-in function
  2. Using the len() built-in function, find the length of your first name
  3. Compare the length of your first name and your last name
  4. Declare 5 as num_one and 4 as num_two
    1. Add num_one and num_two and assign the value to a variable total
    2. Subtract num_two from num_one and assign the value to a variable diff
    3. Multiply num_two and num_one and assign the value to a variable product
    4. Divide num_one by num_two and assign the value to a variable division
    5. Use modulus division to find num_two divided by num_one and assign the value to a variable remainder
    6. Calculate num_one to the power of num_two and assign the value to a variable exp
    7. Find the floor division of num_one by num_two and assign the value to a variable floor_division
  5. The radius of a circle is 30 meters.
    1. Calculate the area of a circle and assign the value to a variable name of area_of_circle
    2. Calculate the circumference of a circle and assign the value to a variable name of circum_of_circle
    3. Take the radius as user input and calculate the area.
  6. Use the built-in input function to get first name, last name, country, and age from a user and store the value to their corresponding variable names
  7. Run help(‘keywords’) in Python shell or in your file to check for the Python reserved words or keywords

<<Day1 I Day3>>

Tech G

View Comments

Recent Posts

Python in 30 Days: Day 30- Conclusions

Day 30 Conclusions In the process of preparing this material, I have learned quite a…

7 months ago

Python in 30 Days: Day 29 – Building an API

Day 29: Building API In this section, we will cover a RESTful API that uses HTTP…

7 months ago

Python in 30 Days: Day 28 – API

Day 28: Application Programming Interface (API) API API stands for Application Programming Interface. The kind…

7 months ago

Python in 30 Days: Day 27 – Python with MongoDB

Day 27: Python with MongoDB Python is a backend technology, and it can be connected…

7 months ago

Python in 30 Days: Day 26 – Python for web

Day 26: Python for Web Python is a general-purpose programming language, and it can be…

7 months ago

Python in 30 Days: Day 25 – Pandas

Day 25: Pandas Pandas is an open-source, high-performance, easy-to-use data structure, and data analysis tool…

7 months ago