0% found this document useful (0 votes)
139 views19 pages

Introduction to Python Programming

Python is a versatile programming language created by Guido van Rossum in 1991, widely used for web development, software development, and data analysis. Its popularity stems from its readability, simplicity, and support for multiple programming paradigms. The document covers Python's installation, syntax, variable handling, and output methods, along with practical examples and assignments for learners.

Uploaded by

erioluwadaniel8
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
139 views19 pages

Introduction to Python Programming

Python is a versatile programming language created by Guido van Rossum in 1991, widely used for web development, software development, and data analysis. Its popularity stems from its readability, simplicity, and support for multiple programming paradigms. The document covers Python's installation, syntax, variable handling, and output methods, along with practical examples and assignments for learners.

Uploaded by

erioluwadaniel8
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON PROGRAMMING LANGUAGE

Introduction
Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.
It is used for Web development (server-side, Software development, Mathematical experiments System
scripting etc.

Uses of Python
The python programming language can be used:
1. on a server to create web applications.
2. alongside software to create workflows.
3. to connect database systems and read/ modify files.
4. to handle big data and perform complex mathematics.
5. for rapid prototyping, or for production-ready software development.

The Popularity of Python Programming Language


Python is an exceptionally popular programming language, consistently ranking among the top choices
globally. This is so because: It works on different Operating systems /platforms (Windows, Mac, Linux,
Raspberry Pi, etc.), It has a simple syntax similar to the English language, Python syntax allows developers
to write programs with fewer lines than some other programming languages. Python runs on an
interpreter system, meaning that code can be executed as soon as it is written. Thereby making
prototyping very quick. Python can be treated in a procedural way, an object-oriented way or a functional
way.
The most recent major version of Python is Python 3, which we shall be using in this class. It is possible
to write Python in an Integrated Development Environment, such as Thonny, Pycharm, Netbeans or
Eclipse which are particularly useful when managing larger collections of Python files. However, there
are text editors like VScode that can be used to run python codes

Python Syntax compared to other programming languages


1. Python was designed for readability, and has some similarities to the English language with influence
from mathematics.
2. Python uses new lines to complete a command, as opposed to other programming languages which
often use semicolons or parentheses.
3. Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions
and classes. Other programming languages often use curly-brackets for this purpose.
Example of a Python Code
print("Hello, World!")

Output
Hello, World!
PYTHON INSTALLATION
Many PCs and Macs will have python already installed.
To check if you have python installed on a Windows PC, search in the start bar for Python or run the
following on the Command Line ([Link]):

To check if you have python installed on a Linux or Mac, then on linux open the command line or on Mac
open the Terminal and type:

If you find that you do not have Python installed on your computer, then you can download it for free
from the following website: [Link]

Python Quickstart
Python is an interpreted programming language; this means that as a developer you write Python (.py)
files in a text editor and then put those files into the python interpreter to be executed.

Let's write our first Python file, called [Link], which can be done in any text editor:

Simple as that. Save your file. Open your command line, navigate to the directory where you saved your
file, and run:

The output should be:


Congratulations, you have written and executed your first Python program.

Python Version
To check the Python version of the editor, you can find it by importing the sys module:

Example
Check the Python version of the editor:
import sys
print([Link])

Output
3.12.3 (main, Apr 10 2024, 05:33:47) [GCC 13.2.0]

The Python Command Line


To test a short amount of code in python sometimes it is quickest and easiest not to write the code in a
file. This is made possible because Python can be run as a command line itself.

Type the following on the Windows, Mac or Linux command line:

Or, if the "python" command did not work, you can try "py":

From there you can write any python code, including our hello world example from earlier.

Which will write "Hello, World!" in the command line:


Whenever you are done in the python command line, you can simply type the following to quit the
python command line interface:

Assignment
1. Who developed Python Programming Language?
2. What is the file extension for Python files?
3. Which type/paradigm of Programming does Python support?
4. Is Python case sensitive when dealing with identifiers? Explain.
5. Is Python code compiled or interpreted? Explain after making proper research.
6. What will be the value of the following Python expression?
print(4 + 3 % 5)
7. What is used to define a block of code in Python language?
8. Which keyword is used for function in Python language?
9. What special character is used to give single-line comments in Python?
10. Write out the function that can help us to find the version of python that we are currently working
on
EXECUTE PYTHON SYNTAX
As we learned earlier, Python syntax can be executed by writing directly in the Command Line:

Or by creating a python file on the server, using the .py file extension, and running it in the Command
Line:

PYTHON INDENTATION
Indentation refers to the spaces at the beginning of a code line. Where in other programming languages
the indentation in code is for readability only, the indentation in Python is very important.
Python uses indentation to indicate a block of code.
Example
if 5 > 2:
print("Five is greater than two!")
Output
Five is greater than two!

Python will give you an error if you skip the indentation. This type of error is called the Syntax Error
Example
if 5 > 2:
print("Five is greater than two!")
Output
IndentationError: expected an indented block

The number of spaces is up to you as a programmer, the most common use is four, but it has to be at
least one.
Example
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
Output
Five is greater than two!
Five is greater than two!
You have to use the same number of spaces in the same block of code, otherwise Python will give you
an error
Example
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")
Output
File "demo_indentation2_error.py", line 3
print("Five is greater than two!")
^
IndentationError: unexpected indent

PYTHON VARIABLES
In Python, variables are created when you assign a value to it
Example
x = 5 (This is an integer variable and it is written as int)
y = "Hello, World!" (This is a string variable and it is written or represented as str)
z= 8.56 (This is a float variable and it is written or represented as float)
please note that Python has no command for declaring a variable.

COMMENTS
Python has commenting capability for the purpose of in-code documentation. As a programmer
comments are an important aspects of computer programming as they enable the readability of codes
and thereby making the maintenance of software easy.

Comments are nonexecutable lines of a program.


Comments start with a # (the ash character), and Python will render the rest of the line as a comment

Example
#This is a comment.
print("Hello, World!")

Output
Hello, World!

PYTHON STATEMENTS
A computer program is a list of "instructions" to be "executed" by a computer. In a programming
language, these programming instructions are called statements.
The following statement prints the text "Python is fun!" to the screen:
print("Python is fun!")
In Python, a statement usually ends when the line ends. You do not need to use a semicolon (;) like in
many other programming languages (for example, Java or C).

Many Statements
Most Python programs contain many statements. The statements are executed one by one, in the same
order as they are written:

Example
print("Hello World!")
print("Have a good day.")
print("Learning Python is fun!")

Example explained
From the example above, we have three statements:
print("Hello World!")
print("Have a good day.")
print("Learning Python is fun!")
The first statement is executed first (print "Hello World!").
Then the second statement is executed (print "Have a good day.").
And at last, the third statement is executed (print "Learning Python is fun!").

Semicolons (Optional, Rarely Used)


Semicolons are optional in Python. You can write multiple statements on one line by separating them
with ; but this is rarely used because it makes it hard to read.

Example
print("Hello"); print("How are you?"); print("Bye bye!")

However, if you put two statements on the same line without a separator (newline or ;), Python will give
an error

Example
print("Python is fun!") print("Really!")

Result:
SyntaxError: invalid syntax

Best practice: Put each statement on its own line so your code is easy to understand.
PYTHON OUTPUT / PRINT
By now, You have already learned that you can use the print() function to display text or output values

print("Hello World!")

You can use the print() function as many times as you want. Each call prints text on a new line by default

Example
print("Hello World!")
print("I am learning Python.")
print("It is awesome!")

Double Quotes
Text in Python must be inside quotes. You can use either " double quotes or ' single quotes

Example
print("This will work!")
print('This will also work!')

If you forget to put the text inside quotes, Python will give an error:

Example
print(This will cause an error)
Result:
SyntaxError: invalid syntax.

Print Without a New Line


By default, the print() function ends with a new line. If you want to print multiple words on the same line,
you can use the end parameter.

Example
print("Hello World!", end=" ")
print("I will print on the same line.")
Output
Hello World! I will print on the same line.

Note that we add a space after end=" " for better readability.
PYTHON OUTPUT NUMBERS
You can also use the print() function to display numbers. However, unlike text, we don't put numbers
inside double quotes.
Example
print(3)
print(358)
print(50000)

You can also do math inside the print() function


Example
print(3 + 3)
print(2 * 5)

Mix Text and Numbers


You can combine text and numbers in one output by separating them with a comma
Example
print("I am", 35, "years old.")

Assignment
1. Indentation in Python is for readability only. (True or False)

PYTHON COMMENTS
Comments can be used to explain Python code. Comments can be used to make the code more readable.
Comments can be used to prevent execution when testing code.

Creating a Comment
Comments starts with a #, and Python will ignore them.

Example
#This is a comment
print("Hello, World!")

Comments can be placed at the end of a line, and Python will ignore the rest of the line.

Example
print("Hello, World!") #This is a comment

A comment does not have to be text that explains the code, it can also be used to prevent Python from
executing code.
Example
#print("Hello, World!")
print("Cheers, Mate!")

Multiline Comments
Python does not really have a syntax for multiline comments. To add a multiline comment, you could
insert a # for each line.

Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")

Or, not quite as intended, you can use a multiline string.


Since Python will ignore string literals that are not assigned to a variable, you can add a multiline string
(triple quotes) in your code, and place your comment inside it

Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

As long as the string is not assigned to a variable, Python will read the code, but then ignore it, and you
have made a multiline comment.

Assignment
Which character is used to define a Python comment?

PYTHON VARIABLES
Variables are containers for storing data values.

Creating Variables
Python has no command for declaring a variable. A variable is created the moment you first assign a
value to it.
Example
x=5
y = "John"
print(x)
print(y)

Variables do not need to be declared with any particular type, and can even change type after they have
been set.

Example
x=4 # x is of type int
x = "Sally" # x is now of type str
print(x)

Casting or Type Casting


If you want to specify the data type of a variable, this can be done with casting.

Example
x = str(3) # x will be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0

Get the Type


You can get the data type of a variable with the type() function.

Example
x=5
y = "John"
print(type(x))
print(type(y))

Single or Double Quotes


String variables can be declared either by using single or double quotes

Example
x = "John"
# is the same as
x = 'John'
Case-Sensitive
Variable names are case-sensitive.
Example
This will create two variables

a=4
A = "Sally"
#A will not overwrite a

Assignment
What is a correct way to declare a Python variable?
(a) var x = 5 (b) #x = 5 (c) $x = 5 (d) x = 5

PYTHON - VARIABLE NAMES


Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).

Rules for creating Python variables


1. A variable name must start with a letter or the underscore character
2. A variable name cannot start with a number
3. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _)
4. Variable names are case-sensitive (age, Age and AGE are three different variables)
5. A variable name cannot be any of the Python keywords.

Example
Legal variable names
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"

Example
Illegal variable names
2myvar = "John"
my-var = "John"
my var = "John"

Please note that variable names are case-sensitive


MULTI WORDS VARIABLE NAMES
Variable names with more than one word can be difficult to read. There are several techniques you can
use to make them more readable

Camel Case
Each word, except the first, starts with a capital letter
myVariableName = "John"

Pascal Case
Each word starts with a capital letter
MyVariableName = "John"

Snake Case
Each word is separated by an underscore character:
my_variable_name = "John"

Assignment
Which is NOT a legal variable name?
(a) my-var = 20 (b) my_var = 20 (c) Myvar = 20 (d)_myvar = 20

PYTHON VARIABLES - ASSIGN MULTIPLE VALUES


Many Values to Multiple Variables
Python allows you to assign values to multiple variables in one line.
Example
x, y, z = "Orange", "Banana", "Cherry"
print(x)
print(y)
print(z)
Note: Make sure the number of variables matches the number of values, or else you will get an error.

One Value to Multiple Variables


And you can assign the same value to multiple variables in one line.
Example
x = y = z = "Orange"
print(x)
print(y)
print(z)

Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values into variables.
This is called unpacking.
Example
Unpack a list

fruits = ["apple", "banana", "cherry"]


x, y, z = fruits
print(x)
print(y)
print(z)

Assignment
What is a correct syntax to add the value 'Hello World', to 3 variables in one statement?
(a) x, y, z = 'Hello World' (b) x = y = z = 'Hello World' (c) x|y|z = 'Hello World'

PYTHON - OUTPUT VARIABLES


Output Variables
The print() function is often used to output variables.

Example
x = "Python is awesome"
print(x)

In the print() function, you can output multiple variables, separated by a comma.

Example
x = "Python "
y = "is "
z = "awesome"
print(x, y, z)

You can also use the + operator to output multiple variables (Concatenation)

Example
x = "Python "
y = "is "
z = "awesome"
print(x + y + z)

Note: the space character after "Python " and "is ", without them the result would be
"Pythonisawesome".
For numbers, the + character works as a mathematical operator

Example
x=5
y = 10
print(x + y)

In the print() function, when you try to combine a string and a number with the + operator, Python will
give you an error

Example
x=5
y = "John"
print(x + y)

The best way to output multiple variables in the print() function is to separate them with commas, which
even support different data types:

Example
x=5
y = "John"
print(x, y)

Assignment
Consider the following code:
print('Hello', 'World')
What will be the printed result? (a)Hello, World (b)Hello World (c)HelloWorld

PYTHON - GLOBAL VARIABLES


Global Variables
Variables that are created outside of a function (as in all of the examples in the previous pages) are known
as global variables. Global variables can be used by everyone, both inside of functions and outside.

Example
Create a variable outside of a function, and use it inside the function
x = "awesome"

def myfunc():
print("Python is " + x)

myfunc()
If you create a variable with the same name inside a function, this variable will be local, and can only be
used inside the function. The global variable with the same name will remain as it was, global and with
the original value.
Example
Create a variable inside a function, with the same name as the global variable
x = "awesome"

def myfunc():
x = "fantastic"
print("Python is " + x)

myfunc()

print("Python is " + x)

The global Keyword


Normally, when you create a variable inside a function, that variable is local, and can only be used inside
that function. To create a global variable inside a function, you can use the global keyword.
Example
If you use the global keyword, the variable belongs to the global scope
def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)

Also, use the global keyword if you want to change a global variable inside a function.

Example
To change the value of a global variable inside a function, refer to the variable by using the global keyword
x = "awesome"

def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)
Assignment
Consider the following code:
x = 'awesome'
def myfunc():
x = 'fantastic'
myfunc()
print('Python is ' + x)
What will be the printed result?

(a)Python is awesome (b)Python is fantastic

Assignment

1. What is a correct way to declare a Python variable?


(a) var x = 5 (b) #x = 5 (c) $x = 5 (d)x = 5

2. You can declare string variables with single or double quotes.


x = "John"
# is the same as
x = 'John'
True or False

3. Variable names are not case-sensitive.


a=5
# is the same as
A=5
True or False

4. Write the correct functions to print the data type of a variable in the dashes below

_________(______(myvar))

5. Which is NOT a legal variable name?


(a)my-var = 20 (b)my_var = 20 (c)Myvar = 20 (d)_myvar = 20

6. Create a variable named carname and assign the value Volvo to it.

7. Create a variable named x and assign the value 50 to it.


8. What is a correct syntax to add the value 'Hello World', to 3 variables in one statement?
(a) x, y, z = 'Hello World' (b) x = y = z = 'Hello World' (c) x|y|z = 'Hello World'

9. Insert the correct syntax to assign values to multiple variables in one line:
x__ y __ z = "Orange", "Banana", "Cherry"

10. Consider the following code:


fruits = ['apple', 'banana', 'cherry']
a, b, c = fruits
print(a)
What will be the result of a
(a) Apple (b) banana (c)cherry

11. Consider the following code:


print('Hello', 'World')
What will be the printed result?
(a) Hello, World (b) Hello World (c) HelloWorld

12. Consider the following code:


print('Hello', 'World')
What will be the printed result?
(a) Hello, World (b) Hello World (c) HelloWorld

13. Consider the following code:


a = 'Hello'
b = 'World'
print(a + b)
What will be the printed result?
(a)a + b (b)Hello World (c)HelloWorld

14. Consider the following code:


a=4
b=5
print(a + b)
What will be the printed result?
(a)45 (b)9 (c)4 + 5

15. Consider the following code:


x = 'awesome'
def myfunc():
x = 'fantastic'
myfunc()
print('Python is ' + x)
What will be the printed result?
(a)Python is awesome (b)Python is fantastic

16. Insert the correct keyword to make the variable x belong to the global scope.
def myfunc():
______ x
x = "fantastic"
17. Consider the following code:
x = 'awesome'
def myfunc():
global x
x = 'fantastic'
myfunc()
print('Python is ' + x)
What will be the printed result?
(a)Python is awesome (b)Python is fantastic

18. If x = 5, what is a correct syntax for printing the data type of the variable x?
(a) print(dtype(x)) (b) print(type(x)) (c) print([Link]())

19. The following code example would print the data type of x, what data type would that be?
x=5
print(type(x))
___________

20. The following code example would print the data type of x, what data type would that be?
x = "Hello World"
print(type(x))
____________

21. The following code example would print the data type of x, what data type would that be?
x = 20.5
print(type(x))
_________

22. The following code example would print the data type of x, what data type would that be?
x = ["apple", "banana", "cherry"]
print(type(x))
_________

23. The following code example would print the data type of x, what data type would that be?
x = ("apple", "banana", "cherry")
print(type(x))
_____________
24. The following code example would print the data type of x, what data type would that be?

x = {"name" : "John", "age" : 36}


print(type(x))
___________
25. The following code example would print the data type of x, what data type would that be?
x = True
print(type(x))
____________

You might also like