Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Python Basics

Uploaded by

waqarkhan03109
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)
9 views

Python Basics

Uploaded by

waqarkhan03109
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
You are on page 1/ 35

Python

Getting Started

Instructor:
Sayed Shahid Hussain
Research Associate,
AI in Healthcare, National Center of AI
UET Peshawar
Email: sayedshahid310@gmail.com
Install Python
Download Python for free from the following website:
https://www.python.org/

# Start
print("Hello World!")
Python Comments
Comments starts with a #, and Python will ignore them:

For a comment more then one lone, add a multiline string (triple quotes) in
your code, and place your comment inside it:

#This is a comment

"""
This is a comment
written in
more than just one line
"""
Print & Input
# Display something
print("Hello World!")

# Help: This is user Input


name = input('Enter your Name: ')
Variables
• 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.

• 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)
Variables
Exercise:

Create three variables named “age, Age and AGE” and assign the values
20,30,40 to the them. Print the variables.
Python Data Types
• Variables can store data of different types, and different types can do
different things.
• Python has the following data types built-in by default, in these categories:
• Numeric Types: int, float, complex
• Text Type: str
• Sequence Types: list, tuple, range
• Mapping Type: dict
• Set Types: set
• Boolean Type: bool
Python Numbers
• There are three numeric types in Python: int, float, complex
• 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.
• Complex numbers are written with a "j" as the imaginary part.

You can get the data type of a variable with the type() function.
String
• Strings in python are surrounded by either single quotation marks, or
double quotation marks.

• Multiline Strings
• You can assign a multiline string to a variable by using three quotes
String
Strings are Arrays

• Like many other popular programming languages, strings in Python are


arrays of bytes representing unicode characters.

• However, Python does not have a character data type, a single character is
simply a string with a length of 1.

• Square brackets can be used to access elements of the string.

To get the length of a string, use the len() function.


String
• Slicing String
• You can return a range of characters by using the slice syntax.
• Specify the start index and the end index, separated by a colon, to return a part of the
string.

• String Concatenation
• Use + to combine strings
String
• String Format
• Use the format() method to insert numbers into strings

• Exercise:
• Insert the correct syntax to join text and int,
• Print: My name is John, and I am 36

age = 36
txt = "My name is John, and I am "
String
String Methods

• The upper() method returns the string in upper case.

• The lower() method returns the string in lower case.

• The strip() method removes any whitespace from the beginning or the end.

• The split() method splits the string into substrings if it finds instances of the
separator.
String
• Exercise:
• Make a string with variable name txt, and then:
• Print the length of the string.
• Get the first character of the string
• Convert the value of txt to upper case.
Python Booleans
Booleans represent one of two values: True or False.

print(10 > 9) # true


print(10 == 9) # false
print(10 < 9) # false
Python Operators
Operators are used to perform operations on variables and values.

• Arithmetic Operators
• Arithmetic operators are used with numeric values to perform common mathematical operations.

• Assignment Operators
• Assignment operators are used to assign values to variables.

• Comparison Operators
• Comparison operators are used to compare two values.

• Logical Operators
• Logical operators are used to combine conditional statement.
Python Operators
Exercise:

Take two numbers from the user, store them in variables, and apply
Arithmetic operators. Print the result.
Python Lists
• Lists are used to store multiple items of any data type in a single variable.
• Lists are created using square brackets. It is also possible to use the list()
constructor when creating a new list.
• To determine how many items a list has, use the len() function:

• Access Items
• List items are indexed and you can access them by referring to the index number:
Python Lists
List Methods
• Add List Items, use append() method
• The insert() method inserts an item at the specified index
• To append elements from another list to the current list, use the extend()
method.
• remove() method removes List Items
• The pop() method removes the specified index.
• List objects have a sort() method that will sort the list alphanumerically,
ascending, by default
Python Lists
Exercise:

Take a list:
fruits = ["apple", "banana", "cherry"]
• Print the second item in the fruits list.
• Change the value from "apple" to "kiwi", in the fruits list.
• Add "orange" to the fruits list.
Python Tuple
• Tuples are used to store multiple items in a single variable.

• A tuple is a collection which is ordered and unchangeable. While A list is a


collection which is ordered and changeable.

• Tuples are written with round brackets.


Python Tuple
• Change Tuple Values

• Once a tuple is created, you cannot change its values. Tuples are unchangeable, or
immutable as it also is called.
• But there is a workaround. You can convert the tuple into a list, change the list, and
convert the list back into a tuple.
Python Sets
• Sets are used to store multiple items in a single variable.
• Set items are unordered, unchangeable, and do not allow duplicate values.
• Unordered means that the items in a set do not have a defined order. Set
items can appear in a different order every time you use them, and cannot
be referred to by index or key.
• Set items are unchangeable, meaning that we cannot change the items
after the set has been created.
• Sets cannot have two items with the same value. Duplicate values will be
ignored
Python Sets
• Python Collections (Arrays)
• List is a collection which is ordered and changeable. Allows duplicate members.
• Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
• Set is a collection which is unordered, unchangeable, and unindexed. No duplicate
members.
• Dictionary is a collection which is ordered and changeable. No duplicate members.

• You cannot access items in a set by referring to an index or a key.


• But you can loop through the set items using a for loop,
Dictionary
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection which is ordered, changeable and do not allow
duplicates.

thisdict = {
key1: Value1,
Key2: Value2,
Key2: Value3
}
Dictionary
• Accessing Items
• You can access the items of a dictionary by referring to its key name, inside square
brackets
• thisdict[key1]

• Change Values
• thisdict[key1] = New_Value

• Adding Items
• thisdict[Key4] = Value4

• Removing Items
• thisdict.pop(Key1)
Python Conditions
Python Conditions, If ... Else

• Exercise
• The task is to write code in Python that takes an age (years) as an input and then
check:
• If age is less than 18, print that you are not eligible to vote
• If age is greater than 18 and less than 35 print that you are eligible to vote in the youth
demographic
• Otherwise, print that you are eligible to vote but not in the youth demographic
Python loops
Python has two primitive loop commands:
• while loops
• for loops

• While loop
• With the while loop we can execute a set of statements as long as a condition is true.
• The while loop requires relevant variables to be ready, in this example we need to
define an indexing variable, i, which we set to 1.
• Remember to increment i, or else the loop will continue forever.
Python loops
• The break Statement
• With the break statement we can stop the loop even if the while condition is true

• The continue Statement


• With the continue statement we can stop the current iteration, and continue with the
next:
Python loops
• Python For Loops
• A 'for loop' is used for iterating over a sequence (that is either a list, a dictionary, a set,
or a string).
• With the for loop we can execute a set of statements, once for each item in a list, tuple,
set etc.

• The range() Function


• To loop through a set of code a specified number of times, we can use the range()
function,
• The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
Python loops
Exercise
• Take a List of numbers, call it main_list
• Create empty even and odd lists
• Check the even and odd numbers in the main_list
• Append even numbers in the even list
• Append odd numbers in the odd list
Python Functions
• Python Functions
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.

# Creating a Function
def my_function():
print("Hello from a function"

# Calling a Function
my_function()
Python Functions
Exercise
• Take a List of numbers, call it main_list
• Create empty even and odd lists
• Check the even and odd numbers in the main_list
• Append even numbers in the even list
• Append odd numbers in the odd list

Do this task again using a function


Python Exercise
Exercise
• Ask the user for a number. Depending on whether the number is even or odd, print out
an appropriate message to the user.

• Do this repeatedly and Check another number by checking a key y/n from user and
end the program by entering by user.
Python Exercise
Exercise
• Python Program to Print Table of a Given Number
• Take a number to print the table for
• Take the last limit of table
• print table e.g:
• 2*1=2

You might also like