In this article you will learn different kinds of data and variables used in python. Also i will show you how to use these variable in python programming language.

Firstly, we need to create a python file. For that, create a file named “hello_world.py”. You will write your codes in this python file. After the create this file, write the following code to the first line of the program.

print("hello world")

When you run the above code, you should see the following output.

hello world

Let’s look at the closer to python program we wrote. “.py” at the end of the word “hello_world.py” specify this is a python file. Python is an interpreter programming language. Because of that, python runs the codes by interpreting line by line. For now, there is a line code in the program. By reading and interpreting the codes in the python program, it tries to understand what each of them means. For instance, there is “print” keyword in the first line of the program. Python reads the print word. Then it understands that this is a print function. It writes to the screen the parameters inside of the print function. Python interprets these codes but this causes slower to work according to other programming languages.

Variables

What is the variable and why we need to use these?

Variables are the objects that keep data inside of the computer memory. In other words, you can think of variables as labels. Each object must have a label or name. Likewise, each variable must have a name. We need to define types of variables in the c, c++, java programming languages. But, we don’t need to define types of variables in python programs. Because python is an interpreter language. Also, you can change, delete, or modify the variables later.

Let’s look at how to use variables through the python program we wrote. Add to the first line a new code and change the second line.

hello_world.py

message = "hello world"
print(message)

When you run the above code, you should see the same output as previously.

Output

hello world

We added a variable named “message” to the first line. Each variable has a value. In this situation, our variables name is “hello world“. We assignmented the “hello world” word to the “message” variable. Assignment operation makes with “=” operator in programming. If you want to change the variable value you should change the “hello world” word.

message = "hello world python"
print(message)

Output

hello world python

Using Variable Names

There are a few rules you should follow when you want to use variables. You can get errors when you don’t follow of some these rules. But, other rules help you to write easy, read, and understand the codes.

These rules are;

  • The variable names should contain only letter, number, and underscore. Variable names should start with letter or underscore but not a number. For instance,” _message”, “message_1” but not “1_message
  • Space characters shouldn’t use in variable names. If your variable has more than one word you should use underscore instead of a space character. For instance, use “my_message” don’t use “my message“.
  • Variable names must be short and understandable and not too long. For instance, “name” better than “n“, “student_name” better than “s_n“, “name” better than “my_first_name“. If you don’t want to use underscore in variable names, you can start the variable’s second word’s first letter with uppercase. For instance, “myMessage
  • Avoid using python keyword and function names in variable names.

Python Keywords

False      await      else       import     pass
None       break      except     in         raise
True       class      finally    is         return
and        continue   for        lambda     try
as         def        from       nonlocal   while
assert     del        global     not        with
async      elif       if         or         yield

Python 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()

if you don’t understand exactly don’t worry about it. You will make lots of mistakes while writing code. You will learn better with these mistakes. Let’s look at how to solve these errors.

message = "Hello Python Crash Course reader!"
print(mesage)

When you run this code, you will get an error message. This message shows us that there is an error in the second line and this error is a NameError. When you type the variable name incorrectly, you will receive the NameError message.

Traceback (most recent call last):
➊    File "hello_world.py", line 2, in <module>
➋      print(mesage)
➌ NameError: name 'mesage' is not defined

If you don’t know what type of variable is, python has a “type()” function for it. The following code is a type function example;

type(message)
str

Python Local and Global Variables

There are two kinds of variable define in python programming. These are local and global variables. If you want to define a global variable, there are two option. The first option is define a variable outside of the functions. The second option is defined with the global keyword. When you define a variable as global, you can access your global variable anywhere in the program.

number_1 = 100 # This is defined outside the function.
def calculate():
    print(number_1*2)
def calculate():
    number_1 = 50
print(number_1)

If you run this the above code you will get an error message.

NameError                                 Traceback (most recent call last)
<ipython-input-7-56e11bdbbd70> in <module>()
      2     number_1 = 50
      3 
----> 4 print(number_1)
NameError: name 'number_1' is not defined

If local variables defined inside the functions. But you don’t access local variables from outside of the functions. But if you define a variable inside as a global in function. You can access your variable from anywhere in your program.

number_1 = 100 # This is defined with pglobal keyword.
def calculate():
    global number_1
    print(number_1*2)