0% found this document useful (0 votes)
18 views10 pages

Revision

The document provides a comprehensive guide on writing Python programs, covering variables, data types, type conversion, input/output statements, operators, control statements, loops, and functions. It explains the usage of different data types such as numeric, string, and boolean, along with examples of how to declare and manipulate them. Additionally, it discusses control flow structures like if statements and loops, as well as the definition and calling of functions in Python.

Uploaded by

Ahmed Hamrosh
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)
18 views10 pages

Revision

The document provides a comprehensive guide on writing Python programs, covering variables, data types, type conversion, input/output statements, operators, control statements, loops, and functions. It explains the usage of different data types such as numeric, string, and boolean, along with examples of how to declare and manipulate them. Additionally, it discusses control flow structures like if statements and loops, as well as the definition and calling of functions in Python.

Uploaded by

Ahmed Hamrosh
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

Content:

Skelton of Python Program (How to write a Python program)


Variables and Data Types
Variable is a location in the memory that hold a value can be changed.
There is no special declaration for the variable, it is declared and created at the
moment it is assigned a value.
Ex: x = “Aly” treat x as string, we use ‘ ‘ or “ “
You also can change the variable type after it has been set by assigning a new
value from another data type.
Ex: x = 5 change and treat x as integer
To specify a data type for the variable it is done by casting.
Ex: x = str(3) will treat ‘3’ as string
y = float(3) will treat as 3.0
Variable names:
Name is a set of character and number and _ only
Must start with letter or _, CAN’T start with number
Name are case sensitive
Data Types:
Python have some built in data type:
 Numeric:
o int: is a number, positive or negative, without decimals, of unlimited
length.
 X=5
 Y = -325684123665
Number above is written in a decimal form, while there are other
numbering system can be used to:
 Binary: 0b10 OR 0B10 2
 Octal: 0o10 OR 0O10 8
 Hexa: 0x10 OR 0X10  16
o float: is a number positive or negative contains decimal point
 x = 1.1
 y = -3.45
It can be expressed in a scientific form with (e) which indicates the
power of 10
 -87.9 e5  -8790000
o Complex: is a number contains 2 parts, the real part and imaginary
part denoted by j.
 X = 3 + 5j
 Y = - 7j
 String (str)
Is an array of byte (each byte represents a character). The string is
written between single quote, double quote, or triple quote.
Note, in python there is no character data type, character act as a string
with 1 character
 Name = ‘Aly’
 Message = “Welcome to Python”
 S1 = “’ Triple Quote
Allows
Multi-Line String’”
To access an individual element in the string, we use the index. There are
2 types of index can be used
0 1 2 3 4 5 6
-7 -6 -5 -4 -3 -2 -1
W e l c o m e
Ex: Greeting = “Welcome”
Greeting[0]  W first element
Greeting[-1] e last element
 Boolean
Is a built-in data type that can hold a vlue either true or false
X = true
Type Conversion:
You can convert from a data type to another using the data type name:
1) Convert from Numbers to string:
Ex: a = 10
s = str(a)
b = oct(45)  b = ‘0o55’  number in octal format
c = hex(45)  c = ‘0x2d’  number in hexa format
d = bin(45_  d = ‘0b101101’  number in binary format
2) Convert from string to number
Ex: s = ‘50’
a = int(s)
3) Convert between Numerical type
Ex: int(97.5)  97
float(567)  567.0
Complex(34)  34 + 0j
Note:
To get the data-type of any variable use type() function
Ex: name = input("Enter name : ")
print(type(name)) //Display <class ‘str’>
Input / Output statement
 Input statement:
Is a way to let the end user to input a value. The input data must be stored in
a variable.
The input statement:
input(prompt) Note: prompt is a message to be displayed on the
screen directing the end user what to input
Ex: name = input(“Enter your name”)
At the runtime, it will display “Enter your name” on the screen, and wait the
end user to input name
Input more than one variable at the same time:
x, y, z = input("Enter three values: ").split()
OR
x, y, z = [int(x) for x in input("Enter three values: ").split()]
Input multiple value in a list:
x = [int(x) for x in input("Enter multiple values: ").split()]
 Output statement:
Is a way to print a message in the screen to the end user
The output statement:
print(value(s), sep= ' ', end = '\n')
where:
o value(s): any value as many as you need, all values will be converted
to string before printing
o sep = ‘separator’: specify the separator between objects
o end = ‘end’: specify what to print at the end (default : ‘\n’)
Operators
 Arithmatic Operator:
+, -, *, /, **(exponent), % (modulus), // (Floor Division)
Ex : 32 / 8  4.0 (division always return a float value)
3 ** 4  81 (3 to the power 4)
33 % 7  5 (33 divide 7 equal 4 and remain 5’modulus’)
5.0 // 3  1 (5 / 3 = 1.6 floord to 1)
 Relational (Comparison) Operator:
<, >, <=, >=, ==, !=
Assignment operator always has a value of type boolean
Ex: 25 >= (30 * 2) the operation value is False
 Assignment Operator:
=, +=, -=, *=, /=, %=, //=
Ex: x=2*4
a, b, c = 10, 30.5, 15 (a = 10, b = 30.5, c = 15)
a = b = c = 70
x += 5 (x = x + 5)
 Logical Operator:
and, or, not
and a and b  operation is True, when a and b are True
or a or b  operation is False, when a and b are False
not not a  reverse the meaning of a
Control statement
Conditional statement
 if statement
if(condition):
statement to be executed when condition is True
this is used to check for a condition if it is True, then perform some
operation, otherwise do nothing
Example: Write a program that read a number, if the number is odd
increase it by 1, and finally print the number
Solution:
Num = input (“Enter a number”)
if((Num %2) != 0):
Num *= 2
print(“Value = ”, Num)
 if .. else statement
if(condition):
statement to be executed when condition is True
else:
statement to be executed when condition is False
Example: Write a program that read a grade, if the grade greater than
or equal 60, print “Pass”, otherwise print “Fail”
Solution:
Grade = input(“Enter Grade: “)
if(Grade >= 60):
print(“Pass”)
else:
print(“Fail”)
 elif statement
This is used if you have more than one condition
if(condition):
……
elif(condition):
……
else
……
Example: Write a program that read a grade, if the grade greater than
or equal 90, print “A”, if the grade greater than or equal 80, print “B”,
if the grade greater than or equal 60, print “C”, otherwise print “Fail”
Solution:
Grade = input(“Enter Grade : “)
if(Grade >= 90):
print(“A”)
elif(Grade >= 80):
print(“B”)
elif(Grade >= 60):
print(“C”)
else:
print(“Fail”);
Python support nested if, where another if statement is written in if..else statement
Iteration statement
This allows more than one statement to be repeated (executed more than one time)
 for loop
this is used to iterate over a sequence (list, tuple, dictionary, set or string)
for iterator_variable in sequence:
statement to be executed
Ex: fruits = [“apple”, “banana”, “cherry”]
for x in fruits :
print(x)
Ex: for x in "banana":
print(x)
We can add an else statement after the loop that will execute 1 time after
the loop fail.
Ex: for x in range(6):
print(x)
else:
print(“Value greater than 6”)
the for loop can’t be empty, but if for any reason you want it empty, write
pass in it
 while loop
it executes a group of statements as long as a condition is True
while condition :
statement to be repeated when condition is true
Ex: i=1
while i < 6:
print (i)
i += 1
We can add an else statement after the loop that will execute 1 time after
the loop fail.
Ex: i=1
while i < 6:
print (i)
i += 1
else:
print(“Value greater than 6”)
Functions
Function is a block of code that perform a specific task.
The function is declared using def keyword followed by the function name
def Function_Name():
Function implementations (Function code)
We can pass values to a function, this is done by using parameters which are
variable prepared to receive the data when function called
The function can also return a value
Example 1:
Write a function that print “Welcome from Python”
Solution:
def PrintMsg():
print(“Welcome from Python”)
Calling function:
PrintMsg()
Example 2:
Write a function that print the sum of 2 numbers
Solution:
def PrintSum(num1, num2):
S = num1 + num2
print(“The Sum = “, S)
Calling function:
PrintSum(5, 8)
Example 3:
Write a function that calculate the sum of 2 numbers
Solution:
def Sum(num1, num2):
S = num1 + num2
return S
Calling function:
X = Sum(7, 8)
Note:
 You can assign a default argument value to a parameter, in case if the value
isn’t sent when calling, it will receive the default value assigned
Ex: def my_function(country = "Egypt"):
print("I am from " + country)
Call: my_function(“USA”)  print  “I am from USA
Call: my_function()  print  “I am from Egypt”
 When calling the function, you can assign a value to the parameter by its
name. Then the order of arguments has no effect
Ex: def my_function(child3, child2, child1):
print("The youngest child is " + child3)
Call: my_function(child1 = "Aly", child2 = "Ahmed", child3 = "Amr")
 Arbitrary Arguments *args
If the number of arguments is unknown, add * before the parameter name,
this transform the parameter to act as tuple
Ex: def my_function(*kids):
print("The youngest child is " + kids[2])
Call: my_function("Aly", "Ahmed", "Amr")  Amr
 Arbitrary Arguments **kwargs
If the number of arguments is unknown, add * before the parameter name,
this transform the parameter to act as dictionary
Ex: def my_function(**kid):
print("His last name is " + kid["lname"])
Call: my_function(fname = "Ahmed", lname = "Aly")

You might also like