0% found this document useful (0 votes)
5 views6 pages

Python Exercise Practice Handouts

The document provides a comprehensive guide on writing programs in Python, covering topics such as variables, comments, data types, type conversion, calculations, lists, conditions, loops, and functions. It includes examples and rules for each topic, demonstrating how to effectively use Python for programming tasks. Additionally, it emphasizes the importance of structure and organization in coding through the use of functions.

Uploaded by

Ibrahim Ibrahim
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
5 views6 pages

Python Exercise Practice Handouts

The document provides a comprehensive guide on writing programs in Python, covering topics such as variables, comments, data types, type conversion, calculations, lists, conditions, loops, and functions. It includes examples and rules for each topic, demonstrating how to effectively use Python for programming tasks. Additionally, it emphasizes the importance of structure and organization in coding through the use of functions.

Uploaded by

Ibrahim Ibrahim
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 6

Python Exercise Practice Handouts

Writing a Program in Python:

• Open File menu and select New File or press Ctrl+N.

• Type→ print ("My first program in Python")

• Open File menu and save the program or press Ctrl+S.

• Run the program from the Run menu or press Ctrl+F5.

Output

Python Variables: x = 15 15
In Python variables are created the moment we assign y = “The City School” The City School
Value to it: For output: >>>
A variable can have a short name (like x and y) or a more print(x)
descriptive name (age, carname, total volume). print(y)
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)

Comments:
x = 23 #This is an Integer value
Comments are just a dead piece of code which y = “Hello, 7T” #This is an string value
Can be used for our references only. Comments start with
a #, And Python will render the rest of the line as a comment: #This is a comment

Assign Value to Multiple Variables:

Python allows us to assign values to multiple variables in


one line, by using , between them.
Also Multiple values can be assigned to the same variable
in one line:

Output Variables: Output


x = “School” The City School
The Python print statement is often used to output variables. print(“The City” + x)
>>>
To combine both text and a variable, Python uses the +
character:
Output

x = “Our School” Our School The City School


Now use the + character to add a variable to another y = “The City School” >>>
variable: z=x+y
print(z)

For numbers, the + character works as a mathematical


operator:
If we try to combine a string and a number, Python
will give an error.

Python Numbers:
There are three numeric types in Python:
• int
• float
• complex
Variables of numeric types are created when
we assign a value to them:

To verify the type of any object in Python, use the


type() function:
• Int, or integer, is a whole number, positive or negative,
Without decimals, of unlimited length.
• Float, or "floating-point number" is a number, positive
or negative, containing one or more decimals.

Type Conversion of Variables:


We can convert from one type to another
with the int() and float() methods:
Calculations with Numbers: a=2
7
b=5
We can also use Python to do any kind of calculation: 3
print(a+b)
10
Addition, subtraction, multiplication, division, etc. print(a-b)
0.4
print(a*b)
>>>
print(a/b)

Let’s suppose that we want to display the term percentage of a student for a subject by using averages in exam marks
and course work.

For this example, we will also look into the user interaction using INPUT feature of python to take data from the user
end.

1. In this example, the first line is having a comment

2. In the 2nd line, we have declared a variable named Subject with user INPUT to take subject name form user.

3. In the 3rd line, we have declared a variable name Exam while setting its data type to float.

4. In the 3rd line, we have declared a variable for course work with the name of CW while setting its data type to float.

5. In the 5th line, we declare the variable name Percentage while setting its value to a Mathematical calculation of
Exam+CW divided by 2 to get the average percentage of the Subject.

6. In the 6th line, we have printed the string value along with the values of the Subject variable and percentage
variable. Perform the same exercise step by step for practice

LIST in Python:
An example of a list could be:
In Python, you can store your data into variables, but you can

also put them in lists. A list is just an ordered collection of items

which can be of any data type. Creating a list is as simple as putting

different comma-separated values between square brackets. Each

element of a list is assigned a value by using an index.

To call a list element is very easy by calling it’s inde x value:


Delete and Add List Elements:

Del command is used to delete a list element as mentioned in the example below:

To add an item to the end of the list, use the append() method.

Python Conditions and If Statements

These conditions can be used in several ways, most commonly in "if statements" and loops.

IF

An "if statement" is written by using the If keyword.

In this example, we use two variables, a and b, which are used as part of the if statement to test whether b is greater
than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we print to screen that "b is greater than a".
Indention is necessary. If we do not use the indention as mentioned in the example, python will give an error.

Elif for Multiple Conditions

The Elif keyword is python’s way of saying "if the previous conditions were not true, then try this condition".

In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we print to screen that
"a and b are equal".

Else

The else keyword catches anything which isn't caught by the preceding conditions

In this example a is greater than b, so the first condition is not true, also the Elif condition is not true, so we go to the
else condition and print to screen that "a is greater than b". We can also use the else without using Elif.
Conditional Operators & Logical Operators:

In Python, logical operators are used to


combine multiple conditions together and
evaluate them as a single boolean
A conditional statement as the name expression. There are three types of logical
suggests itself, is used to handle conditions operators in Python: `and`, `or`, and `not`.
in your program. These statements guide The `and` operator returns `True` if both
the program while making decisions based conditions it is evaluating are true,
on the conditions encountered by the otherwise it returns `False`
program.

Python “For” Loops

A for loop is used for repeating over a sequence (that is either a list or a string).

‘FOR’ keyword will be must use when we are working with a for loop.

For example, we have a list of students and we want to display the student with the highest marks without using the
max() function. We will use the following code:

1. In the 1st line of this code, we have created a list StdMrks with four values stored in it.

2. In the 2nd line, we have declared a variable name MaxMarks with an integer value of 0.

3. In the 3rd line, we use for loop while declaring another variable “i” with the range of four. This means this loop will
run 4 times. Every time FOR loop runs, it will increase the value of the “i” variable.

4. In the 4th line, we have set a condition to check that if StdMrks[i] variable is greater than MaxMrks (declared 0 in 2nd
line) variable then change the value of MaxMarks[i] to StdMrks value. (StdMrks[i] variable is going to change its value
every time the loop runs and change the index of StdMrks. This process is also known as unary increment). Using
indention is compulsory or python will not consider the For loop elements and give an error.

5. In the 5th line, MaxMrks is setting its value equal to the current value of StdMarks only if the condition in the previous
line is true.

6. In the 6th line, we have just printed the value of MaxMrks along with a string sentence.
Python Functions

In Python, a Function is a group of related statements that perform a specific task. Functions help break our program
into smaller and modular chunks. As our program grows larger and larger, functions make it more organized and
manageable.

Furthermore, it avoids repetition and makes code reusable. Function names cannot have spaces in between. Instead of
spaces use _ underscore to connect the words. In Python, a function is defined using the def keyword and for executing
the function we can use the function name along with parenthesis ().

Shown above is a function which consists of the following components.

• Keyword def marks the start of function header.


• A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in Python.
• Parameters (arguments) through which we pass values to a function. They are optional.
• A colon (:) to mark the end of function header.
• The last line executes the function, we can call or use the function in our code wherever it is needed.

Examples for practice:

In this example, the input function takes no parameters. So this


operation informs the computer to wait until you type your name and
press Enter. When you press Enter, the program reads what you have
typed and with the print function, it displays a new text string.

On the other hand, if our function uses an external value, we


have to put the values of the parameters in parentheses. For
example, type this code and enter Pakistan1248 as a password:

Converting code into a function:

We have already experienced this code earlier but now we have converted the same into a function and now it can be
recalled and reused whenever required in the program.

You might also like