DEV Community

Ahmed Gouda
Ahmed Gouda

Posted on • Originally published at ahmedgouda.hashnode.dev

Getting Started with Python

Hello World

What really happens when you run hello_world. py?

print("Hello Python World!")
Enter fullscreen mode Exit fullscreen mode

Output:

Hello Python World!
Enter fullscreen mode Exit fullscreen mode

When you run the file hello_world. py, the ending . py indicates that the file is a Python program. Your editor then runs the file through the Python interpreter, which reads through the program and determines what each word in the program means. For example, when the interpreter sees the word print followed by parentheses, it prints to the screen whatever is inside the parentheses.

Variables

Let’s try using a variable in hello_world. py.

message = "Hello Python World!"
print(message)
Enter fullscreen mode Exit fullscreen mode

Output:

Hello Python World!
Enter fullscreen mode Exit fullscreen mode

We’ve added a variable named message. Every variable is connected to a value, which is the information associated with that variable. In this case the value is the "Hello Python world!" text.

Adding a variable makes a little more work for the Python interpreter. When it processes the first line, it associates the variable message with the "Hello Python world!" text. When it reaches the second line, it prints the value associated with message to the screen.

You can change the value of a variable in your program at any time, and Python will always keep track of its current value.

message = "Hello Python World!"
print(message)

message = "Hello Python!"
print(message)
Enter fullscreen mode Exit fullscreen mode

Output:

Hello Python World!
Hello Python!
Enter fullscreen mode Exit fullscreen mode

Variables Are Labels

Variables are often described as boxes you can store values in. This idea can be helpful the first few times you use a variable, but it isn’t an accurate way to describe how variables are represented internally in Python. It’s much better to think of variables as labels that you can assign to values. You can also say that a variable references a certain value.

This distinction probably won’t matter much in your initial programs, but it’s worth learning earlier rather than later. At some point, you’ll see unexpected behavior from a variable, and an accurate understanding of how variables work will help you identify what’s happening in your code.

Strings

Because most programs define and gather some sort of data, and then do something useful with it, it helps to classify different types of data. The first data type we’ll look at is the string. Strings are quite simple at first glance, but you can use them in many different ways.

A string is a series of characters.

Anything inside quotes is considered a string in Python, and you can use single '' or double quotes "" around your strings like this:

"This is a string."
'This is also a string.'
Enter fullscreen mode Exit fullscreen mode

This flexibility allows you to use quotes and apostrophes within your strings:

'I told my friend, "Python is my favorite language!"'
"The language 'Python' is named after Monty Python, not the snake."
"One of Python's strengths is its diverse and supportive community."
Enter fullscreen mode Exit fullscreen mode

Changing Case in a String with Methods

One of the simplest tasks you can do with strings is change the case of the words in a string.

name = "ahmed gouda"
print(name.title())
Enter fullscreen mode Exit fullscreen mode

Output:

Ahmed Gouda
Enter fullscreen mode Exit fullscreen mode

In this example, the variable name refers to the lowercase string "ahmed gouda". The method title() appears after the variable in the print() call.

A method is an action that Python can perform on a piece of data.

The dot (.) after name in name.title() tells Python to make the title() method act on
the variable name. Every method is followed by a set of parentheses, because methods often need additional information to do their work. That information is provided inside the parentheses. The title() function doesn’t need any additional information, so its parentheses are empty.

The title() method changes each word to title case, where each word begins with a capital letter. This is useful because you’ll often want to think of a name as a piece of information. For example, you might want your program to recognize the input values Ahmed, AHMED, and ahmed as the same name, and display all of them as Ahmed.

Several other useful methods are available for dealing with case as well. For example, you can change a string to all uppercase or all lowercase letters.

name = "Ahmed  Gouda"
print(name.upper())
print(name.lower())
Enter fullscreen mode Exit fullscreen mode

Output:

AHMED GOUDA
ahmed gouda
Enter fullscreen mode Exit fullscreen mode

The lower() method is particularly useful for storing data. Many times you won’t want to trust the capitalization that your users provide, so you’ll convert strings to lowercase before storing them. Then when you want to display the information, you’ll use the case that makes the most sense for each string.

Using Variables in Strings

In some situations, you’ll want to use a variable’s value inside a string. For example, you might want two variables to represent a first name and a last name respectively, and then want to combine those values to display someone’s full name.

first_name = "ahmed"
last_name = "gouda"
full_name = f"{first_name} {last_name}"
print(full_name)
Enter fullscreen mode Exit fullscreen mode

Output:

ahmed gouda
Enter fullscreen mode Exit fullscreen mode

To insert a variable’s value into a string, place the letter f immediately before the opening quotation mark. Put braces around the name or names of any variable you want to use inside the string. Python will replace each variable with its value when the string is displayed.

These strings are called f-strings. The f is for format, because Python formats the string by replacing the name of any variable in braces with its value.

You can do a lot with f-strings. For example, you can use f-strings to compose complete messages using the information associated with a variable.

first_name = "ahmed"
last_name = "gouda"
full_name = f"{first_name} {last_name}"
print(f"Hello, {full_name.title()}!")
Enter fullscreen mode Exit fullscreen mode

Output:

Hello, Ahmed Gouda!
Enter fullscreen mode Exit fullscreen mode

You can also use f-strings to compose a message, and then assign the entire message to a variable.

first_name = "ahmed"
last_name = "gouda"
full_name = f"{first_name} {last_name}"
message = f"Hello, {full_name.title()}!"
print(message)
Enter fullscreen mode Exit fullscreen mode

This code displays the message Hello, Ahmed Gouda! as well, but by assigning the message to a variable we make the final print() call much simpler.

Adding Whitespace to Strings with Tabs or Newlines

In programming, whitespace refers to any nonprinting character, such as spaces, tabs, and end-of-line symbols. You can use whitespace to organize your output so it’s easier for users to read.

Character Combination Action
\t Add a tab to your text
\n Add a new line in a string
print("\tPython")
Enter fullscreen mode Exit fullscreen mode
    Python
Enter fullscreen mode Exit fullscreen mode
print("Languages:\nPython\nC\nRust")
Enter fullscreen mode Exit fullscreen mode
Languages:
Python
C
Rust
Enter fullscreen mode Exit fullscreen mode
print("Languages:\n\tPython\n\tC\n\tRust")
Enter fullscreen mode Exit fullscreen mode
Languages:
    Python
    C
    Rust
Enter fullscreen mode Exit fullscreen mode

Stripping White Spaces

Extra whitespace can be confusing in your programs. To programmers 'python' and 'python ' look pretty much the same. But to a program, they are two different strings. Python detects the extra space in 'python ' and considers it significant unless you tell it otherwise.

It’s important to think about whitespace, because often you’ll want to compare two strings to determine whether they are the same. For example, one important instance might involve checking people’s usernames when they log in to a website. Extra whitespace can be confusing in much simpler situations as well. Fortunately, Python makes it easy to eliminate extraneous whitespace from data that people enter.

Python can look for extra whitespace on the right and left sides of a string.

Method Action
rstrip() Remove the extra space from the right side
lstrip() Remove the extra space from the left side
strip() Remove the extra space from the both sides
>>> favorite_language = ' python '
>>> favorite_language
' python '
>>> favorite_language.rstrip()
' python'
>>> favorite_language.lstrip()
'python '
>>> favorite_language.strip()
'python'
>>> favorite_language
' python '
Enter fullscreen mode Exit fullscreen mode

The value associated with favorite_language contains extra whitespace at the both sides of the string. When you ask Python for this value in a terminal session, you can see the space. When the strip() method acts on the variable favorite_language, this extra space is removed. However, it is only removed temporarily. If you ask for the value of favorite_language again, you can see that the string looks the same as
when it was entered, including the extra whitespace. To remove the whitespace from the string permanently, you have to associate the stripped value with the variable name.

>>> favorite_language = ' python '
>>> favorite_language = favorite_language.strip()
>>> favorite_language
'python'
Enter fullscreen mode Exit fullscreen mode

To remove the whitespace from the string, you strip the whitespace from the string and then associate this new value with the original variable. Changing a variable’s value is done often in programming. This is how a variable’s value can be updated as a program is executed or in response to user input.

Experimenting with these stripping functions can help you become familiar with manipulating strings. In the real world, these stripping functions are used most often to clean up user input before it’s stored in a program.

Avoiding Syntax Errors with Strings

One kind of error that you might see with some regularity is a syntax error.

A syntax error occurs when Python doesn’t recognize a section of your program as valid Python code.

For example, if you use an apostrophe within single quotes, you’ll produce an error. This happens because Python interprets everything between the first single quote and the apostrophe as a string. It then tries to interpret the rest of the text as Python code, which causes errors.

message = "One of Python's strengths is its diverse community."
print(message)
Enter fullscreen mode Exit fullscreen mode

Output:

One of Python's strengths is its diverse community.
Enter fullscreen mode Exit fullscreen mode
message = 'One of Python's strengths is its diverse community.'
print(message)
Enter fullscreen mode Exit fullscreen mode

Output:

SyntaxError: invalid syntax
Enter fullscreen mode Exit fullscreen mode

The error occurs right after the second single quote. This syntax error indicates that the interpreter
doesn’t recognize something in the code as valid Python code. Errors can come from a variety of sources. You might see syntax errors often as you learn to write proper Python code. Syntax errors are also the least specific kind of error, so they can be difficult and frustrating to identify and correct. Your editor’s syntax highlighting feature should help you spot some syntax errors quickly as you write your programs.

Numbers

Numbers are used quite often in programming to keep score in games, represent data in visualizations, store information in web applications, and so on. Python treats numbers in several different ways, depending on how they’re being used. Let’s first look at how Python manages integers, because they’re the simplest to work with.

Integers

You can add (+), subtract (-), multiply (*), and divide (/) integers in Python.

>>> 2 + 3
5
>>> 3 - 2
1
>>> 2 * 3
6
>>> 3 / 2
1.5
Enter fullscreen mode Exit fullscreen mode

In a terminal session, Python simply returns the result of the operation. Python uses two multiplication symbols to represent exponents.

>>> 3 ** 2
9
>>> 3 ** 3
27
>>> 10 ** 6
1000000
Enter fullscreen mode Exit fullscreen mode

Python supports the order of operations too, so you can use multiple operations in one expression. You can also use parentheses to modify the order of operations so Python can evaluate your expression in the order
you specify.

>>> 2 + 3*4
14
>>> (2 + 3) * 4
20
Enter fullscreen mode Exit fullscreen mode

The spacing in these examples has no effect on how Python evaluates the expressions; it simply helps you more quickly spot the operations that have priority when you’re reading through the code.

Floats

Python calls any number with a decimal point a float. This term is used in most programming languages, and it refers to the fact that a decimal point can appear at any position in a number. Every programming language must be carefully designed to properly manage decimal numbers so numbers behave appropriately no matter where the decimal point appears.

For the most part, you can use decimals without worrying about how they behave. Simply enter the numbers you want to use, and Python will most likely do what you expect.

>>> 0.1 + 0.1
0.2
>>> 0.2 + 0.2
0.4
>>> 2 * 0.1
0.2
>>> 2 * 0.2
0.4
Enter fullscreen mode Exit fullscreen mode

But be aware that you can sometimes get an arbitrary number of decimal places in your answer.

>>> 0.2 + 0.1
0.30000000000000004
>>> 3 * 0.1
0.30000000000000004
Enter fullscreen mode Exit fullscreen mode

This happens in all languages and is of little concern. Python tries to find a way to represent the result as precisely as possible, which is sometimes difficult given how computers have to represent numbers internally.

Integers and Floats

When you divide any two numbers, even if they are integers that result in a whole number, you’ll always get a float.

>>> 4/2
2.0
Enter fullscreen mode Exit fullscreen mode

If you mix an integer and a float in any other operation, you’ll get a float as well.

>>> 1 + 2.0
3.0
>>> 2 * 3.0
6.0
>>> 3.0 ** 2
9.0
Enter fullscreen mode Exit fullscreen mode

Python defaults to a float in any operation that uses a float, even if the output is a whole number.

Underscores in Numbers

When you’re writing long numbers, you can group digits using underscores to make large numbers more readable.

>>> universe_age = 14_000_000_000
Enter fullscreen mode Exit fullscreen mode

When you print a number that was defined using underscores, Python prints only the digits.

>>> print(universe_age)
14000000000
Enter fullscreen mode Exit fullscreen mode

Python ignores the underscores when storing these kinds of values. Even if you don’t group the digits in threes, the value will still be unaffected. To Python, 1000 is the same as 1_000, which is the same as 10_00. This feature works for integers and floats.

Multiple Assignment

You can assign values to more than one variable using just a single line. This can help shorten your programs and make them easier to read; you’ll use this technique most often when initializing a set of numbers.

For example, here’s how you can initialize the variables x, y, and z to zero:

>>> x, y, z = 0, 0, 0
Enter fullscreen mode Exit fullscreen mode

You need to separate the variable names with commas, and do the same with the values, and Python will assign each value to its respectively positioned variable. As long as the number of values matches the number of variables, Python will match them up correctly.

Constants

A constant is like a variable whose value stays the same throughout the life of a program. Python doesn’t have built-in constant types, but Python programmers use all capital letters to indicate a variable should be treated as a constant and never be changed.

MAX_CONNECTIONS = 5000
Enter fullscreen mode Exit fullscreen mode

When you want to treat a variable as a constant in your code, make the name of the variable all capital letters.

Comments

Comments are an extremely useful feature in most programming languages. As your programs become longer and more complicated, you should add notes within your programs that describe your overall approach to the problem you’re solving. A comment allows you to write notes in English within your programs.

How Do You Write Comments?

In Python, the hash mark (#) indicates a comment. Anything following a hash mark in your code is ignored by the Python interpreter. For example:

# Say hello to everyone.
print("Hello Python people!")
Enter fullscreen mode Exit fullscreen mode

Python ignores the first line and executes the second line.

Hello Python people!
Enter fullscreen mode Exit fullscreen mode

What Kind of Comments Should You Write?

The main reason to write comments is to explain what your code is supposed to do and how you are making it work. When you’re in the middle of working on a project, you understand how all of the pieces fit together. But when you return to a project after some time away, you’ll likely have forgotten some of the details. You can always study your code for a while and figure out how segments were supposed to work, but writing good comments can save you time by summarizing your overall approach in clear English.

If you want to become a professional programmer or collaborate with other programmers, you should write meaningful comments. Today, most software is written collaboratively, whether by a group of employees at one company or a group of people working together on an open source project. Skilled programmers expect to see comments in code, so it’s best to start adding descriptive comments to your programs now. Writing clear, concise comments in your code is one of the most beneficial habits you can form as a new programmer.

When you’re determining whether to write a comment, ask yourself if you had to consider several approaches before coming up with a reasonable way to make something work; if so, write a comment about your solution. It’s much easier to delete extra comments later on than it is to go back and write comments for a sparsely commented program.

Important Note

Don’t try to write perfect code; write code that works, and then decide whether to improve your code for that project or move on to something new.

Discussion (0)