Python for Beginners

Python For Beginners (with Beh)

FREE DOWNLOAD

Send download link to:

Here is the table of contents of this E-Book:

  • Intro – Where this book come from?
  • Best tools to run and test Python codes
  • Print() function
  • Variables in Python
  • String replication
  • Reading input
  • Data types in Python
  • Arithmetic Operators
  • Operator Precedence
  • Type casting
  • Simple Exception Handling
  • Decision Making
  • Built-in functions vs. user-defined functions
  • String built-in functions
  • Simple user-defined functions
  • User-Defined functions with parameter(s)

Python Exercises with Solution

Intro – Where this book come from?

This E-Book is a part of my Python course on Udemy. In this course we are going to dive deeply into the Python fundamentals, but with a lot of examples and challenges.

In this course, after completing each section, you will receive an exercise pack, contains real world challenges. So, you can check your learning progress along the way.

Python Exercises (with Beh)

FREE DOWNLOAD

Send download link to:

This E-Book contains these exercises:

  • Exercise #1- Date Format
  • Solution #1
  • Exercise #2 – Maximum Number
  • Solution #2
  • Exercise #3 – Odd or Even
  • Solution #3
  • Exercise #4 – Validate a Zip Code
  • Solution #4
  • Exercise #5 – Free Shipping
  • Solution #5
  • Exercise #6 – Simple Calculator
  • Solution #6
  • Exercise #7 – Palindrome
  • Solution #7
  • Exercise #8 – Case-insensitive Palindrome
  • Solution #8
  • Exercise #9 – Get the file extension
  • Solution #9
  • Exercise #10 – Secure credit card number
  • Solution #10
  • Exercise #11 – String Comparison
  • Solution #11
  • Exercise #12 – ATM PIN CODE validation
  • Solution #12
  • Exercise #13 – Draw a triangle
  • Solution #13
  • Exercise #14 – Draw a triangle by using a while loop – 1
  • Solution #14
  • Exercise #15 – Draw a triangle by using a while loop – 2
  • Solution #15
  • Exercise #16 – Divisible numbers by 5 (for loop)
  • Solution #16
  • Exercise #17 – Divisible numbers by 5 (while loop)
  • Solution #17
  • Exercise #18 – User defined divisible numbers (for loop)
  • Solution #18
  • Exercise #19 – User defined divisible numbers (while loop)
  • Solution #19
  • Exercise #20 – Check if a list is empty
  • Solution #20
  • Exercise #21 – Append a list to another one
  • Solution #21
  • Exercise #22 – Returning a random item from a list
  • Solution #22
  • Exercise #23 – Find common items
  • Solution #23
  • Exercise #24 – Find even items.
  • Solution #24

Python cheat sheet

Men cannot survive without cheating, it is in their nature!

This is a part of my Smart Cheat Sheet idea that is fully available at Udemy. I hope you enjoy it!

I will complete the list in the course of time

String Declaration

#Single Quotes(Used when you have double quote inside a string)
print('I am "Beh"')
#Double Quotes (Used when you have single quote inside a string)
print("I'm Beh")
#Triple Single Quotes (Used when you have both single and boule quotes inside a string)
print('''I'm "Beh"''')
#Triple Double Quotes (Used when you have both single and boule quotes inside a string)

Sequence Characters

#  \'  It prints a single quote
print("I\'m Beh")
#  \"  It prints a double quote
print("I'm \"Beh\"")
#  \t  It makes a horizontal tab space between two strings
print("Name\tAge\tGender")
#  \n  Includes a newline character in a string
print("Line1\nLine2\nLine3")

Variable Naming Rules

# 1. Variable names are case-sensitive.
# 2. Variable names should not start with a number.
# 3. Python Keywords are not allowed as variable names.

Keywords List

# and       del       from      not       while
# as        elif      global    or        with
# assert    else      if        pass      yield
# break     except    import    print	 None
# class     exec      in        raise
# continue  finally   is        return 
# def       for       lambda    try

Arithmetic Operators

# Operator					Shorthand form	What It Does
# --------------------------------------------------
# + 	Addition 			+=				Add two operands
# - 	Subtraction 		-=				Subtract right operand from the left 
# * 	Multiplication 		*=				Multiply two operands
# / 	Division 			/=				Divides the operand on left by the one on right.
# % 	Modulus 			%=				Divides the operand on left by the one on right and returns	remainder
# ** 	Exponent 			**=				left operand raised to the power of right
# // 	Floor division 		//=				Performs just like the / division operator, but truncates the result at the decimal point

Operator Precedence

#  Operator			          Description
#---------------------------------------------------------------------------
#  ()				          Parentheses	
#  **				          Exponent
#  * / % //			          Multiply, divide, modulus and floor division
#  + -				          Addition and subtraction
#  <= < > >=				  Comparison operators
#  <> == !=			          Equality operators
#  = %= /= //= -= += *= **=	  Assignment operators	

Exception Handling

try:
  # the code that might throw an exception
except:
  # the code handles the exception
else:
  # this code block executes if the try block does not raise an exception
finally:
  # the code runs anyway

if Statement

if condition:
  pass

if elif Statement

if condition:
  pass
elif condition:
  pass

if else Statement

if condition:
    pass
else:
    pass

if elif else Statement

if condition:
  pass
elif condition:
  pass
else:
  pass

Comparison Operators

#  Operator	Operator Name					Description
#----------------------------------------------------------
#  == 		Equal to						Returns true if values of both the operands are equal
#  != 		Not Equal to 					Returns true if values of both the operands are not equal
#  > 		Greater than 					Returns true if value of the left operand is greater than the right one
#  < 		Lesser than 					Returns true if value of the left operand is smaller than the right one
#  >= 		Greater than or equal to 		Returns true if value of the left operand is greater than or equal to the right one
#  <= 		Less than or equal to			Returns true if value of the left operand is smaller than or equal to the right one

Logical Operators

#  Operator	    Operator Name		Description
#-------------------------------------------------------------------------------------
#  and 		    Logical AND			Returns true when both operands are True
#  or 		    Logical OR 			Returns true when any one of both operand is True
#  not 		    Logical NOT 		Reverses the operand state
#-------------------------------------------------------------------------------------

String Methods

#   function name       description
#-------------------------------------------------------------------------------------------
#   len()               Returns the number of characters in a string
#   capitalize()        Converts the first character of a string to capital letter
#   count()             Returns the number of occurrences of a substring in the given string
#   lower()             Converts a string into lower case
#   upper()	            Converts a string into upper case
#   isspace()           Returns True if all characters in the string are whitespaces
#   replace()           Replaces all or part of a string with another string
#   isdigit()           Returns True if the string consists of digits only

List Methods

#  Function			Description
#--------------------------------------------------------------------------------------------------
#  all()            Returns True if all the Boolean values in the list are True, else returns False
#  any()			Returns True if any of the Boolean values in the list is True
#  append()         Adds an item to the end of the list
#  len()			Returns the numbers of items in a list
#  insert()         Inserts an item at a given position
#  pop([])          Removes the item at the given position in the list
#  clear()          Removes all items from the list.           
#  reverse()        Reverses the elements of the list
#  sort()			Sorts the elements of the list.
#  min()            Returns the smallest item in the list.
#  max()            Returns the largest item in the list.

3. Variables in Python

The most fundamental concept in programming is the concept of a variable.A variable is like a box in which you can store things like numbers and strings, for later use. We use variables to temporarily store data in a computer’s memory.

Here’s an example:

age = 24

when Python interpreter executes this code, it will allocate some memory, then it will store the number 24 in that memory, and finally it will attach this age label in that memory location. In other words, a variable is a name that refers to a value during program execution.

So, if I use the print function to print the value of the age variable, it will print 24, because age refers to 24.

age = 24
print(age)

So, the output of this program is 24.

The equals symbol (=) is called the assignment operator. The assignment operator means “Put this value in this variable”.

Note that the variable name is an arbitrary name that you select. A variable can have a short name (like a and b) or a more descriptive name (age, price, account_id). But there are rules for naming variables.

  • Variable names are case-sensitive
  • Variable names should not start with a number
  • Python Keywords are not allowed as variable names

Rule number 1: Python is case-sensitive

Rule number 1 says that “Variable names are case-sensitive”. Python is sensitive to capitalization of letters. For example, “Age” and “age” are two different variables because the “A” is uppercase in the first variable and lowercase in the second variable:

Age = 50
age = 24
print (Age)

So, if we run this code, the print function will print 50.

Rule number 2: variable names should not start with a number

OK, rule number two, variable names should not start with a number. For example, if you declare a variable like this:

1age = 24

And run the program, you will get an error message says:

Rule number 3: Python Keywords are not allowed

Another rule is that Python Keywords are not allowed as variable names. Keywords are a series of reserved words in Python. They have special meaning for Python.

Here is a complete list of python keywords:

anddelfromnotwhile
aselifglobalorwith
assertelseifpassyield
breakexceptimportprintNone
classexecinraisecontinue
finallyisreturndeffor
lambdatry

Updating a variable

And one last thing is about updating variables. You can update a variable after initializing it like this. For example, I can reassign the value of the age variable like this:

age = 24
age = 30
print(age)

If I run the code, the result will be 30.

2. Print() function

Let’s write our first Python program. Type print, all in lowercase, open and close parenthesis, and inside these parentheses, add double quotes or single quotes and then type whatever you want to print. In programming terms, we usually call text a string:

print("I am Beh from Dev Hive")

So, this is your first Python program. Now to run this program, just click on the green icon that is located on the upper right side.

As you see, my name and my Udemy account name, is printed here:

Now you know that we can enclose a text (or a string) in either single quotes (‘) or double quotes (“), but what’s the difference?

Note that we should use double quotes when we have single quote inside a string:

print("I'm Beh from Dev Hive")

And we should use single quotes, when we have double quote inside a string:

print('I am Beh from "Dev Hive"')

We can also use triple quotes like this:

print('''I'm Beh from "Dev Hive"''')

In this way, you can use double quote and single quote in your string at the same time.

Print a multi-line string

To print a multi-line string, we use triple quotes like this:

print('''
I'm Beh 
from "Dev Hive"
''')

The output of this program is this:

1. Best tools to run and test Python codes

You can use Visual Studio Code to run and test Python code. I will teach you further how to install and configure this tool, but before that, let me introduce you an online Python interpreter:

http://try-python.appspot.com/

In this online tool, all you need is to type your Python code and press the Enter key, so it will execute your code.

For example, in Python, there is a function named print() that prints your text. So, open this online tool and write this code:

print("Hello World!")

And then press the Enter key. It will print Hello World! in the next line.

Installing VS-Code

You can also use Visual Studio Code to run Python code. VS-Code is a free code editor that is available on your favorite platform – Windows, mac-OS, and Linux. 

Let me show you how to install Python and VS-Code on Windows. For installing Python, open python.org website. In the opened page and from downloads tab, click on [Python for Windows].

After download completed, run and install the downloaded file. To do so, click on Install Now button. After a few seconds, it will complete the Python installation.

Now we are ready to install Visual Studio Code. So, open up this https://code.visualstudio.com link.

In this page, there is a stable version of VS-Code for download.

So, download and then run the downloaded file. All you need is to click Next and accept default options. After a few seconds, your VS-Code is ready to use.

Visual Studio Code
VS-Code Editor

Create your first Python project in VS-Code

The next step is to create a new python project in Visual Studio Code.

1.  Create a new folder at any location you want and name it as you want.

2. Open this folder in VS Code from File > Open Folder.

3. Create a new file inside the folder. To do so, click on New File icon. 

Creating a new file in your folder

Name it test.py, py is the extension for Python scripts.

4. Now the VS-Code recommends this extension:

The extension makes VS-Code an excellent Python code editor

This extension is the official Python extension from Microsoft that makes VS Code an excellent Python code editor. So, click on the Install button to begin the installation.

Our VS-Code is ready to use. Let’s test it. So, type this code in your code editor:

print("Welcome to my course!")

and click on run button that is located on the upper right side.

By doing so, it will run your Python code and displays it in Terminal window:

Terminal window displays the result of your code

Beautify your VS-Code

Now let’s change font size. In Visual Studio Code, by pressing Ctrl + keys and Ctrl – keys you can change the overall font size. But you can also, click on the Gear icon , select settings, search for fonts and change 14 with for example 22:

You can also change vs code color theme by clicking on File > Preferences > Color Theme.

If you have any problem in this section, please don’t hesitate to contact me by codewithbeh@google.com.

Also, If you enjoy this post or know someone who might find it helpful, please share it with them!