01. Computer programming and Python fundamentals

Arindam BaidyaArindam Baidya
10 min read

Python

  • Easy and intuitive programming language

  • Free and open source

  • Can be widely used for a variety of tasks

To create a Python file, need to use .py extension.

To run a Python script use python3 <file_name.py>

Print function - print()

>>> print("Hello future python programmer!")
Hello future python programmer!
  • The word print here, is a function name.

Function

  • A part of the code that is used to cause an effect or evaluate a value.

Functions come from

  • Python (built-in function): As in this case we never told python that it should print something to the console,when we used the print function. It already knew this, since it’s a built in function.

  • Modules: A Function can also come from one or more of Python’s modules.

  • User-created or own code

>>> print("Hello future python programmer!")

Here, ("Hello future python programmer!") - this is called arguments, In this case we passed a string in print function as an argument.

  • The quotes tell python, that the text between them is not codes, and should not be executed. Python should take it as it is.

Function execution

  1. Checks the existence of a function name

  2. Checks that the argument passed is legal

  3. Jumps into the function

  4. Executes the function

  5. Returns to the code

  6. Resumes the execution

Multiple lines at once

>>> print("Hello future Python programmer!");\
... print("Python is a great language");\
... print("String don't get executed as code")
Hello future Python programmer!
Python is a great language
Strings don't get executed as code

Note: There cannot be more than one instruction on a line in Python.

Longer sentence separated with newline character

>>> print("Hello, \nfuture python programmer!")
Hello, 
future python programmer!

Here, n stands for new line, and the backslash \ lets python know that the next character after the backslash has a special meaning. → This prints the sentence with the new line.

More control over the output (end, sep)

  • Python allow passing special arguments to the print function, namely keyword arguments.

  • e.g., end

  • The keyword argument end determines the characters that the print function sends to the output once it reaches the end of the positional arguments.

end

>>> print("Hello!", end="");\
... print("Python is a great language")
Hello!Python is a great language
>>> print("Hello!", end="!");\
... print("Python is a great language")
Hello!!Python is a great language
>>> print("Hello!", end="❤");\
... print("Python is a great language")
Hello!❤Python is a great language
  • Previously, we saw that invoking the print function on two lines meant that their output was also printed on two lines using the newline character at the positional arguments.

  • In this case, we are using end Keywords instead of new line charecter to print both lines in a single line.

sep

This keywords allow to control how Python separates the outputted arguments. Which is a space by default.

>>> print("Hello", "future", "Python", "programmer!", sep="-")
Hello-future-Python-programmer!
>>> print("Hello", "future", "Python", "programmer!", sep="❤")
Hello❤future❤Python❤programmer!

Combining sep and end

>>> print("Hii", "Hello", sep="! ", end="❤\n")
... print("So", "enjoying Python?", sep=", ", end="😊")

Hii! Hello❤
So, enjoying Python?😊

print()

  • Built-in function: can be used without importing it.

  • Allows us to print values to the console.

  • We can invoke it with parentheses.

  • We can pass the value we want to print as arguments between the parentheses.

  • The backslash \ tells Python that the next character has a special meaning (e.g. \n).

  • Keywords arguments such as sep and end can be used to format the output.

Literals

A literal is data which values are determined by the literal itself. For example, the number 200, the string “Hello”, or the number -67. Any other data such as name, C, age, or print are not literals. We don’t know what value they have or what they’re suppose to represent.

Literal types:

  1. Integers

    • Octal numbers

    • Hexadecimal numbers

  2. Floating point numbers

  3. Strings

  4. Booleans

Integer:

The number that doesn't have a fraction. eg. 200, 1268945, -90, 1_000_000

  • The underscore in 1 million are just a way for developers to make large numbers more readable, but they aren’t necessary.

Octal numbers:

The integer number starting with 0o (zero-'o') known as an octal number.

0o123 = (1 × 8²) + (2 × 8¹) + (3 × 8⁰) = (1 × 64) + (2 × 8) + (3 × 1) = 64 + 16 + 3 = 83

Hexadecimal numbers:

The integer number starting with 0x (zero-'x') known as a hexadecimal number.

0x123 = (1 × 16²) + (2 × 16¹) + (3 × 16⁰) = (1 × 256) + (2 × 16) + (3 × 1) = 256 + 32 + 3 = 291

Floating point number:

It is a non-empty decimal fraction.

eg. 48.68, 58.2, -89.0, 856.2

  • Numbers with more decimals can also be written with E in order to represent the number in a more economical form.
1e-13 = 0.0000000000001 (that’s 13 zeros after the decimal point before the 1)

Strings:

# Basic string with double quotes
"hello"

# Basic string with single quotes
'hello'

# Double quotes outside, single quotes inside (no need to escape)
"hello! 'Python' is cool"

# Single quotes outside, double quotes inside (no need to escape)
'hello! "Python" is cool'

# Double quotes outside, escaped double quotes inside
"hello! \"Python\" is cool"

Booleans:

True, False, or 1, 0

True --> 1
Flase --> 0

Summary

Operators

Arithmetic operators

Python has seven type arithmetic operators.

Exponential ( ** )

>>> print(2 ** 3)
8
>>> print(2. ** 3.)
8.0
>>> print(2 ** 3.)
8.0
>>> print(2. ** 3)
8.0

It takes one base and one exponent. If both numbers are integers, the result will be an integer. If one of the values is a floating-point number, the result will be a float.

Multiplication ( * )

>>> print(2 * 3)
6
>>> print(2. * 3.)
6.0
>>> print(2 * 3.)
6.0
>>> print(2. * 3)
6.0

Division ( / )

>>> print(10 / 2)
5.0
>>> print(10. / 2)
5.0
>>> print(10 / 2.)
5.0
>>> print(10. / 2)
5.0

Python always returns float when dividing values.

Floor division ( // )

>>> print(10 // 2)
5
>>> print(10. // 2.)
5.0
>>> print(10 // 2.)
5.0
>>> print(10. // 2)
5.0

The floor division operator also rounds the values towards the lesser integer value.

>>> print(6. / 4)
1.5
>>> print(6. // 4)
1.0
>>> print(6. / -4)
-1.5
>>> print(6. // -4)
-2.0

Modulo ( % )

>>> print(4 % 2)
0
>>> print(5 % 2)
1

Addition ( + )

>>> print(6 + 4)
10
>>> print(6. + 4)
10.0
>>> print(6. + 4.)
10.0

Subtraction ( - )

>>> print(6 - 4)
2
>>> print(6. - 4)
2.0
>>> print(6. - 4.)
2.0

minus ( - ) operator is also a unary operator. We can use the minus operator to specify that the value should be negative.

>>> print(-6 - 6)
-12
>>> print(10 - -6)
16

We can use as many operators in an expression, we want.

>>> print(10 - 6 ** 7 / 9 * 23 + 1)
-29

This is the priority list of operators in case of multiple operators used in an expression. And it is goes to left to right in case of the same priority level operator.

>>> print(2 * (2 + 3))
10

In case of sub-expression, the sub-expression always calculates first.

Variables

  • Variables allow us to store values

      >>> amount_of_apples = 2
      >>> cost_of_apple = 5
      >>> print(amount_of_apples * cost_of_apple) 
      10
    
  • A variable is a valid name (letter, digits(Not at starting), underscore, not a reserved keyword)

  • Python is a dynamically typed: variable name can be redeclared

      >>> cost_of_apple = cost_of_apple + 2
      >>> print(amount_of_apples * cost_of_apple)
      14
    
  • We can use shortcut operators in order to cleanly redeclare a variable

      >>> cost_of_apple += 2 
      >>> print(amount_of_apples * cost_of_apple) 
      14
    

Comments

>>> amount_of_apples = 2 # Amount in basket
# The cost of an apple in USD
# Should always be an integer
>>> cost_of_apple = 5
  • Comments allow us add information for humans to the code

  • A comment is created by a # followed by text

  • A multi-line comment should have a # in front of every line

  • Don’t write unnecessary comments, write self-documenting code instead

Input ( input() )

  • Prompts the user to input some data from the console

  • It accepts an optional parameter that can be used in order to write a message before the user input

  • Always returns a string

  • A program that doesn’t use any input function, is called a deaf program

>>> favorite_color = input("What is your favorite color? ")
What is your favorite color? blue
>>> print("Your favorite color is " + favorite_color)
Your favorite color is blue

Error:

In Python3, whatever you enter as input, the input() function converts it into a string.

>>> age = input("What is your age? ")
What is your age? 25
>>> print(age - 10)
TypeError: unsupported operand type(s) for -: 'str' and 'int'
>>> print(int(age) - 10) # Type casting
15

The input() method returns string value. So, if we want to perform arithmetic operations, we need to cast the value first.

String Operations

  • We can use + in order to concatenate two strings

  • We can use * in order to repeat a string a certain number of times

  • With the str function, we can type cast a number into a string

Concatenating strings

>>> print(10 + 2)
12
>>> print("Hello" + " " + "there!")
Hello there!

Repeating a string

>>> print(10 * 2)
20
>>> print("ha" * 5)
hahahahaha # 5 times "ha"
>>> print("ha" * 0)
"" # Empty string
>>> print("ha" * -1)
"" # Empty string

Type cast to string

>>> print(int("22"))
22
>>> print(str(22))
"22"
# Define the cost of a single apple
cost_of_apple = 2

# Prompt the user to input the number of apples they want
amount_of_apples = input("How many apples do you want? ")

# Calculate the total cost by converting the input to an integer and multiplying by the cost per apple
total_sum = cost_of_apple * int(amount_of_apples)

# Print the total amount the user has to pay, converting the total_sum to a string for concatenation
print("You have to pay: " + str(total_sum))
  • All string methods return new values. They do not change the original string.

Comparison operators

Equal ( == )

>>> print(2 == 2)
True
>>> print(2 == 4)
False
>>> print("Hello!" == "Hello!")
True
>>> print("Hello!" == "Goodbye!")
False
>>> print(4 == (2 * 2))
True

Not equal ( != )

>>> print(2 != 2)
False
>>> print(2 != 4)
True
>>> print("Hello!" != "Hello!")
False
>>> print("Hello!" != "Goodbye!")
True
>>> print(4 != (2 * 2))
False

Greater than ( > )

>>> print(4 > 3)
True
>>> print(2 > 4)
False
>>> print(2 > 2)
False
>>> cost_of_apple = 2
>>> cost_of_banana = 3
>>> print(cost_of_apple > cost_of_banana)
False

Greater than or equal to ( >= )

>>> print(4 >= 2)
True
>>> print(2 >= 4)
False
>>> print(2 >= 2)
True

Smaller than ( < )

>>> print(4 < 2)
False
>>> print(2 < 4)
True
>>> print(2 < 2)
False
>>> cost_of_apple = 2
>>> cost_of_banana = 3
>>> print(cost_of_apple < cost_of_banana)
True

Smaller than or equal to ( <= )

>>> print(4 <= 2)
False
>>> print(2 <= 4)
True
>>> print(2 <= 2)
True

References

KodeKloud

0
Subscribe to my newsletter

Read articles from Arindam Baidya directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Arindam Baidya
Arindam Baidya