Print a message onto the screen:
The print() function prints the specified message to the screen, or other
standard output device.
The message can be a string, or any other object, the object will be converted
into a string before being written to the screen.
print("Hello world!")
Hello world!
print('Hello world!')
Hello world!
Single and duble quotes do the same job but in case you are printing a string
with upstroph you should use the duble quotes like the code below
print("let’s start!.")
If you want to print a long string (in multiple lines) you should use the triple
quotes
print('''
Hello world!
My name is ali
I am a python developer''')
Output
Hello world!
My name is ali
I am a python developer
2
Variables and Simple Data Types
Variables are containers for storing data values, Python has no command for
declaring a variable, a variable is created the moment you first assign a value to it.
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.
x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x)
Variable Names
A variable can have a short name (like x and y) or a more descriptive name
(age, carname, total_volume).
Rules for Python variables:
● A variable name must start with a letter or the underscore character
● A variable name cannot start with a number
● A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
● Variable names are case-sensitive (age, Age and AGE are three different
variables)
3
Legal variable names:
myvar = "Ahmed"
my_var = "Ahmed"
_my_var = "Ahmed"
myVar = "Ahmed"
MYVAR = "Ahmed"
myvar2 = "Ahmed"
Illegal variable names:
2myvar = "Ahmed"
my-var = "Ahmed"
my var = "Ahmed"
Avoiding Name Errors When Using Variables
You should write the variable name without any mistakes
message = "Hello Python"
print(messag)
If you forget the “e” letter this error will rise NameError: name 'messag' is not defined
4
Data Types
Strings
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
name = "Ali"
Changing Case in a String with Methods
print([Link]()) this prints >> ALI
print([Link]()) this prints >> ali
You can print the variables values with print
first_name = "Mahmoud"
last_name = "Ali"
print(first_name, last_name )
Output
Mahmoud Ali
To add a tab to your text, use the character combination \t as shown
print("\tPython")
Output
Python
\n means new line
print("Languages:\nPython\nC\nJavaScript")
Output
5
Languages:
Python
C
JavaScript
String concatenation
print('mahmoud'+ 'hassan')
Output
mahmoudhassan
Fstring
first_name = "mahmoud"
last_name = "hassan"
full_name = f"{first_name} {last_name}"
print(full_name)
Output
mahmoud hassan
Numbers
Integers
Number = 100
You can use some basic mathematical operations with print()
6
print(2 + 3)
5
print(2 * 3)
6
print(2 ** 3)
8
print(2 / 3)
0.66666
print((1+2)*4)
12
Try It Yourself
Write addition, subtraction, multiplication, and division operations that each result in the number
8. Be sure to enclose your operations in print() calls to see the results. You should create four
lines that look like this: print(5+3)
Floats
Python calls any number with a decimal point a float
print(0.1 + 0.5)
0.6
________
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
________
1 + 2.0 ⇒ 3.0
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
7
this technique most often when initializing a set of numbers. For example,
here’s how you can initialize the variables x, y, and z
x, y, z = 0, 1, 2
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
When you want to treat a variable as a constant in your code, make the
name of the variable all capital letters.
Comments
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.
# Say hello to everyone.
print("Hello Python people!")
You can write long comments by using triple quotes
'''
My name is mahmoud ali
Age : 14
Address : Egypt
'''
List
You can make a list that includes the letters of the alphabet, the digits from
0–9, or the names of all the people in your family. You can put anything you
8
want into a list, the items in your list don’t have to be related in any
particular way. Because a list usually contains more than one element, it’s a
good idea to make the name of your list plural, such as letters, digits, or
names.
names = ['mahmoud', 'ali', 'ahmed', 'mohamed']
my_list = ['mahmoud',20, 'ahmed', '300']
Accessing Elements in a List
NOTE: Index Positions Start at 0, Not 1
names = ['mahmoud', 'ali', 'ahmed', 'mohamed']
print(names[0])
Output
'mahmoud'
the last element in your list will have the index of -1
print(names[-1])
Output
'mohamed'
Changing, Adding, and Removing Elements
Modifying Elements in a List
names = ['mahmoud', 'ali', 'ahmed', 'mohamed']
print(names)
Output
['mahmoud', 'ali', 'ahmed', 'mohamed']
names[0] = 'Max'
print(names)
Output
9
['Max', 'ali', 'ahmed', 'mohamed']
Adding Elements to a List
[Link]('Basma')
You can append (add) any items to your empty list like:
names = []
[Link]('Basma')
[Link]('Ali')
[Link]('samer')
print(names)
Output
['Basma', 'Ali', 'samer']
extend takes a list as an argument and appends all of the elements:
t1 = ['a', 'b', 'c']
t2 = ['d', 'e']
[Link](t2)
print( t1)
Output
['a', 'b', 'c', 'd', 'e']
Inserting Elements into a List
You can add a new element at any position in your list by using the insert() method.
You do this by specifying the index of the new element and the value of the new
item.
motorcycles = ['honda', 'yamaha', 'suzuki']
[Link](0, 'ducati')
print(motorcycles)
Output
['ducati', 'honda', 'yamaha', 'suzuki']
10
Removing an Item Using the del Statement
If you know the position of the item you want to remove from a list, you can use the del
statement.
motorcycles = ['honda', 'yamaha', 'suzuki']
del motorcycles[0]
print(motorcycles)
Output
[ 'yamaha', 'suzuki']
Removing an Item Using the pop() Method
Sometimes you’ll want to use the value of an item after you remove it from a list. For example,
you might want to get the x and y position of an alien that was just shot down, so you can draw
an explosion at that position.
In a web application, you might want to remove a user from a list of active members and then
add that user to a list of inactive members.
The pop() method removes the last item in a list, but it lets you work with that item after
removing it. The term pop comes from thinking of a list as a stack of items and popping one item
off the top of the stack. In this analogy, the top of a stack corresponds to the end of a list.
Let’s pop a motorcycle from the list of motorcycles:
popped_name = [Link]()
print(popped_name)
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
popped_motorcycle = [Link]()
print(motorcycles)
print(popped_motorcycle)
Output
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
suzuki
11
Popping Items from any Position in a List You can use pop() to remove an item from any
position in a list by including the index of the item you want to remove in parentheses.
motorcycles = ['honda', 'yamaha', 'suzuki']
popped_motorcycle = [Link](0)
Output
honda
Removing an Item by Value
Sometimes you won’t know the position of the value you want to remove from a list.
names = ['mahmoud', 'ali', 'ahmed', 'mohamed']
[Link]('ali')
The remove() method deletes only the first occurrence of the value you
specify. If there’s a possibility the value appears more than once in the list, you’ll
need to use a loop to make sure all occurrences of the value are removed.
Organizing a List
Your lists will be created in an unpredictable order, because you can’t always
control the order in which your users provide their data. Although this is
unavoidable in most circumstances, you’ll frequently want to present your
information in a particular order. Sometimes you’ll want to preserve the
original order of your list, and other times you’ll want to change the original
order. Python provides a number of different ways to organize your lists,
depending on the situation.
Sorting a List
numbers = [5, 3, 1, 4,2]
[Link]()
[Link]()
print(numbers)
Output
[1, 2, 3, 4, 5]
[Link]()
Output
[5, 4, 3, 2, 1]
Notice that reverse() doesn’t sort backward.
12
Sorting a list of strings
names = ['mahmoud', 'ali', 'ahmed', 'mohamed']
[Link]()
print(names)
Output
['ahmed', 'ali', 'mahmoud', 'mohamed']
Finding the Length of a List
You can quickly find the length of a list by using the len() function. The list in
this example has four items, so its length is 4:
names = ['mahmoud', 'ali', 'ahmed', 'mohamed']
print(len(names))
4
Avoiding Index Errors When Working with Lists
Let’s say you have a list with three items, and you ask for the fourth item:
names = ['mahmoud', 'ali', 'ahmed', 'mohamed']
print(names[4])
Output
IndexError: list index out of range
Python attempts to give you the item at index 3. But when it searches the list, no item in names
has an index of 3.
Because of the off-by-one nature of indexing in lists, this error is typical. People think the third
item is item number 3, because they start counting at 1. But in Python the third item is number
2, because it starts indexing at 0.
An index error means Python can’t find an item at the index you requested. If an index error
occurs in your program, try adjusting the index you’re asking for by one. Then run the program
again to see if the results are correct.
Keep in mind that whenever you want to access the last item in a list you use the index -1
This will always work, even if your list has changed size since the last time you accessed it
13
Looping Through an Entire List
Let’s say we have a list of names, and we want to print out each name in the
list
names = ['mahmoud', 'ali', 'ahmed', 'mohamed']
for name in names:
print(name)
Output
mahmoud
ali
ahmed
mohamed
Doing Something After a for Loop
What happens once a for loop has finished executing? Usually, you’ll want to
summarize a block of output or move on to other work that your program
must accomplish. Any lines of code after the for loop that are not indented
are executed once without repetition.
we place the end message after the for loop without indentation:
names = ['mahmoud', 'ali', 'ahmed', 'mohamed']
for name in names:
print(name)
print('the end')
Output
mahmoud
ali
ahmed
mohamed
the end
Making Numerical Lists
Many reasons exist to store a set of numbers. For example, you’ll need to
keep track of the positions of each character in a game, and you might want
to keep track of a player’s high scores as well.
14
In data visualizations, you’ll almost always work with sets of numbers, such
as temperatures, distances, population sizes, or latitude and longitude
values, among other types of numerical sets. Lists are ideal for storing sets
of numbers, and Python provides a variety of tools to help you work
efficiently with lists of numbers.
Once you understand how to use these tools effectively, your code will work
well even when your lists contain millions of items.
numbers = list(range(1, 6))
print(numbers)
Output
[1, 2, 3, 4, 5]
even_numbers = list(range(2, 11, 2))
print(even_numbers)
In this example, the range() function starts with the value 2 and then adds 2 to that value. It
adds 2 repeatedly until it reaches or passes the end value, 11, and produces this result:
Output
[2, 4, 6, 8, 10]
squares = []
for value in range(1, 11):
square = value ** 2
[Link](square)
print(squares)
15
Simple Statistics with a List of Numbers
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits))
0
print(max(digits))
9
print(sum(digits))
45
List Comprehensions
squares = [value**2 for value in range(1, 11)]
print(squares)
Output
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
16
Try It Yourself
3.1 Guest List: If you could invite anyone, living or deceased, to dinner, who would you
invite?
Make a list that includes at least three people you’d like to invite to dinner. Then use
your list to print a message to each person, inviting them to dinner.
3.2 Changing Guest List: You just heard that one of your guests can’t make the dinner,
so you need to send out a new set of invitations. You’ll have to think of someone else to
invite.
● Start with your program from Exercise 3.1. Add a print() call at the end of your
program stating the name of the guest who can’t make it.
● Modify your list, replacing the name of the guest who can’t make it with the name
of the new person you are inviting.
● Print a second set of invitation messages, one for each person who is still in your
list.
3.3 More Guests: You just found a bigger dinner table, so now more space is available.
Think of three more guests to invite to dinner.
● Start with your program from Exercise 3.1 or Exercise 3.2. Add a print() call to
the end of your program informing people that you found a bigger dinner table.
● Use insert() to add one new guest to the beginning of your list.
● Use insert() to add one new guest to the middle of your list.
● Use append() to add one new guest to the end of your list.
● Print a new set of invitation messages, one for each person in your list
17