The document provides an introduction to C programming, covering topics such as what a program is, programming languages, the history of C, and the development stages of a C program. It discusses the key components of a C program including preprocessing directives, the main function, and program layout. Examples are provided to illustrate C code structure and the use of variables, keywords, operators, input/output functions, and formatting output with printf.
Strings in python are surrounded by either single quotation marks, or double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
ExampleGet your own Python Server
print("Hello")
print('Hello')
Quotes Inside Quotes
You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
Example
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
Assign String to a Variable
Assigning a string to a variable is done with the variable name followed by an equal sign and the string:
Example
a = "Hello"
print(a)
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
Or three single quotes:
Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Note: in the result, the line breaks are inserted at the same position as in the code.
ADVERTISEMENT
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.
Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])
Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with a for loop.
Example
Loop through the letters in the word "banana":
for x in "banana":
This document discusses functions in C programming. It defines functions as blocks of code that perform specific tasks. It explains the key components of functions - function declaration, definition, and call. It provides examples of defining, declaring, and calling functions. It also discusses recursion, system-defined library functions, and user-defined functions.
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxvrickens
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition pg. 25
An Introduction to
Computer Science with Java, Python and C++
Community College of Philadelphia edition
Copyright 2017 by C.W. Herbert, all rights reserved.
Last edited October 8, 28, 2019 by C. W. Herbert
This document is a draft of a chapter from An Introduction to Computer Science with Java, Python and C++, written by Charles Herbert. It is available free of charge for students in Computer Science courses at Community College of Philadelphia during the Fall 2019 semester. It may not be reproduced or distributed for any other purposes without proper prior permission.
Please report any typos, other errors, or suggestions for improving the text to [email protected]
Chapter 5 – Python Functions and Modular Programming
Contents
Lesson 5.1User Created Functions in Python2
Python Function Parameters2
Value returning functions3
Example – Methods and Parameter Passing5
9
Lesson 5.2Top-Down Design and Modular Development10
Chapter Exercises13
User Created Functions in Python
So far we have only created software with one continuous Python script. We have used functions from other python modules, such as the square root method from the math class math.sqrt(n). Now we will begin to create our own functions of our own.
A Python function is a block of code that can be used to perform a specific task within a larger computer program. It can be called as needed from other Python software. Most programming languages have similar features, such as methods in Java or subroutines in system software.
The code for user-defined functions in Python is contained in a function definition. A Python function definition is a software unit with a header and a block of Python statements. The header starts with the keyword def followed by the name of the function, then a set parenthesis with any parameters for the function. A colon is used after the parentheses to indicate a block of code follows, just as with the if and while statements. The block of code to be included within the function is indented.
Here is an example of a Python function:
# firstFunction.py
# first demonstration of the use of a function for CSCI 111
# last edited 10/08/2o19 by C. Herbert
function
definition
def myFunction():
print ( "This line being printed by the function MyFunction.\n")
# end myFunction()
### main program ###
function used by the main part of the script
print("Beginning\n")
myFunction()
print("End\n")
# end main program
Functions can used for code that will be repeated within a program, or for modular development, in which long programs are broken into parts and the parts are developed independently. The parts can be developed as Python functions, then integrated to work together by being called from other software.
Python Function Parameters
Data can be passed to a Python function as a parameter of the function. Function parameters are variables listed in parentheses foll ...
The document discusses pointers in C programming. It defines pointers as variables that store the memory addresses of other variables. It provides examples of declaring pointer variables and using dereference and reference operators. It also covers pointer arithmetic, pointers to pointers, pointers to arrays, pointers as function arguments, pointers to structures including self-referential structures, enumerations, and bitfields. Key concepts are illustrated with code examples and outputs.
This individual assignment submission contains code snippets and explanations for various Python programming concepts and techniques. It includes programs to prompt a user for input, calculate pay and grades, define functions, use data types like lists and dictionaries, and work with classes and objects. The submission also contains questions about Python concepts like loops, variables, modules, file handling, and database usage. Overall, the document demonstrates an understanding of core Python programming and problem-solving skills.
C++ is an object-oriented programming language that features better memory management using dynamic allocation, support for OOP concepts like inheritance and polymorphism, portability across operating systems, and simple syntax similar to C. A basic "Hello World" C++ program includes header files, namespaces, main and return functions, and output statements. Comments are used to explain code and provide information to other programmers. Key elements of C++ include variables to store values, basic and user-defined data types, operators to perform actions, and control flow statements.
Operators are symbols that perform operations on data in programming languages. They allow programmers to manipulate variables and values to solve problems efficiently. The main types of operators include arithmetic, comparison, logical, assignment, bitwise, ternary, and sizeof operators. Operators are essential for tasks like data manipulation, control flow, efficient coding, and expressing code concisely. They provide flexibility and improve code understandability.
This document discusses various topics related to processing and interactive input in C programming, including:
- Assignment statements and implicit/explicit type conversions
- Mathematical library functions like sqrt()
- Using scanf() for interactive input and ensuring valid user input
- Formatted output using printf() and format modifiers
- Common errors like failing to initialize variables or using incorrect data types.
The document discusses Python input and output functions. It describes how the input() function allows user input and converts the input to a string by default. The print() function outputs data to the screen and allows formatting of output. The document also discusses importing modules to reuse code and functions from other files.
The document discusses functions in C programming. It covers:
- Functions allow dividing programs into reusable blocks of code. They can be called multiple times.
- Advantages include avoiding duplicating code, calling functions from anywhere, and improving readability. However, function calls require overhead.
- There are three aspects of a function: declaration, call, and definition. Declaration specifies the name, parameters, and return type. Definition contains the code.
- Functions can return values or not. They can accept arguments or not. Library functions are predefined, while user-defined functions are created by the programmer.
Python is a general purpose programming language that can be used for both programming and scripting. It is an interpreted language, meaning code is executed line by line by the Python interpreter. Python code is written in plain text files with a .py extension. Key features of Python include being object-oriented, using indentation for code blocks rather than brackets, and having a large standard library. Python code can be used for tasks like system scripting, web development, data analysis, and more.
Java Foundations: Data Types and Type ConversionSvetlin Nakov
Learn how to use data types and variables in Java, how variables are stored in the memory and how to convert from one data type to another.
Watch the video lesson and access the hands-on exercises here: https://softuni.org/code-lessons/java-foundations-certification-data-types-and-variables
02 functions, variables, basic input and output of c++Manzoor ALam
This document discusses computer programming functions, variables, and basic input/output in C and C++. It covers:
- Defining and calling functions, function parameters and return values.
- Declaring and assigning values to variables of different data types like int, float, and double.
- Using basic input/output functions like cout and cin to display output and get user input.
- The scope of variables and how they work within and outside of functions.
The document discusses functions in C programming. It defines what a function is and explains the advantages of using functions, such as avoiding duplicate code and improving reusability. It describes the different parts of a function - declaration, definition, and call. It explains user-defined and standard library functions. It also covers parameter passing techniques (call by value and call by reference), recursion, and dynamic memory allocation using functions like malloc(), calloc(), realloc(), and free().
This document discusses various types of operators in C programming. It describes arithmetic, relational, logical, assignment, increment/decrement, conditional, bitwise, and special operators. Examples are provided for each type of operator to demonstrate their usage. The key types of operators covered are arithmetic (e.g. +, -, *, /), relational (e.g. <, >, ==), logical (e.g. &&, ||), assignment (=), increment/decrement (++, --), and conditional/ternary (?:) operators. Special operators like sizeof and comma operators are also briefly explained.
The document provides 20 programming problems and their solutions. Some of the key problems include: writing programs to calculate factorial using recursion, determine if a number is even or odd, swap two numbers using temporary/bitwise operators, find greatest of 3/10 numbers, check if a number is prime/palindromic, and check if a string is a palindrome. The solutions provide sample code snippets and explanations with examples to illustrate the logic.
FUNCTION
INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS (INCLUDING USING BUILT IN LIBRARIES), PARAMETER PASSING IN FUNCTIONS, CALL BY VALUE, PASSING ARRAYS TO FUNCTIONS: IDEA OF CALL BY REFERENCE
Problem solving using computers - Unit 1 - Study materialTo Sum It Up
Problem solving using computers involves transforming a problem description into a solution using problem-solving strategies, techniques, and tools. Programming is a problem-solving activity where instructions are written for a computer to solve something. The document then discusses the steps in problem solving like definition, analysis, approach, coding, testing etc. It provides examples of algorithms, flowcharts, pseudocode and discusses concepts like top-down design, time complexity, space complexity and ways to swap variables and count values.
Programming Fundamentals Functions in C and typesimtiazalijoono
Programming Fundamentals
Functions in C
Lecture Outline
• Functions
• Function declaration
• Function call
• Function definition
– Passing arguments to function
1) Passing constants
2) Passing variables
– Pass by value
– Returning values from functions
• Preprocessor directives
• Local and external variables
There are two ways to initialize a structure:
1. Initialize structure members individually when declaring structure variables:
struct point {
int x;
int y;
} p1 = {1, 2};
2. Initialize an anonymous structure and assign it to a variable:
struct point p2 = {3, 4};
Structures allow grouping of related data types together under one name. They are useful for representing records, objects, and other data aggregates. Structures can contain nested structures as members. Arrays of structures are also possible. Structures provide data abstraction by allowing access to their members using dot operator.
The document discusses functions in C++ and provides examples of defining and calling functions. It explains that a function allows structuring programs in a modular way and accessing structured programming capabilities. A function is defined with a return type, name, parameters, and body. Parameters allow passing arguments when calling the function. The function examples demonstrate defining an addition function, calling it from main to add two numbers and return the result. It also covers function scope, with local variables only accessible within the function and global variables accessible anywhere.
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...EduSkills OECD
Deborah Nusche, Senior Analyst, OECD presents at the OECD webinar 'Trends Spotting: Strategic foresight for tomorrow’s education systems' on 5 June 2025. You can check out the webinar on the website https://oecdedutoday.com/webinars/ Other speakers included: Deborah Nusche, Senior Analyst, OECD
Sophie Howe, Future Governance Adviser at the School of International Futures, first Future Generations Commissioner for Wales (2016-2023)
Davina Marie, Interdisciplinary Lead, Queens College London
Thomas Jørgensen, Director for Policy Coordination and Foresight at European University Association
Slides from a Capitol Technology University presentation covering doctoral programs offered by the university. All programs are online, and regionally accredited. The presentation covers degree program details, tuition, financial aid and the application process.
More Related Content
Similar to introduction to python programming course 2 (20)
Operators are symbols that perform operations on data in programming languages. They allow programmers to manipulate variables and values to solve problems efficiently. The main types of operators include arithmetic, comparison, logical, assignment, bitwise, ternary, and sizeof operators. Operators are essential for tasks like data manipulation, control flow, efficient coding, and expressing code concisely. They provide flexibility and improve code understandability.
This document discusses various topics related to processing and interactive input in C programming, including:
- Assignment statements and implicit/explicit type conversions
- Mathematical library functions like sqrt()
- Using scanf() for interactive input and ensuring valid user input
- Formatted output using printf() and format modifiers
- Common errors like failing to initialize variables or using incorrect data types.
The document discusses Python input and output functions. It describes how the input() function allows user input and converts the input to a string by default. The print() function outputs data to the screen and allows formatting of output. The document also discusses importing modules to reuse code and functions from other files.
The document discusses functions in C programming. It covers:
- Functions allow dividing programs into reusable blocks of code. They can be called multiple times.
- Advantages include avoiding duplicating code, calling functions from anywhere, and improving readability. However, function calls require overhead.
- There are three aspects of a function: declaration, call, and definition. Declaration specifies the name, parameters, and return type. Definition contains the code.
- Functions can return values or not. They can accept arguments or not. Library functions are predefined, while user-defined functions are created by the programmer.
Python is a general purpose programming language that can be used for both programming and scripting. It is an interpreted language, meaning code is executed line by line by the Python interpreter. Python code is written in plain text files with a .py extension. Key features of Python include being object-oriented, using indentation for code blocks rather than brackets, and having a large standard library. Python code can be used for tasks like system scripting, web development, data analysis, and more.
Java Foundations: Data Types and Type ConversionSvetlin Nakov
Learn how to use data types and variables in Java, how variables are stored in the memory and how to convert from one data type to another.
Watch the video lesson and access the hands-on exercises here: https://softuni.org/code-lessons/java-foundations-certification-data-types-and-variables
02 functions, variables, basic input and output of c++Manzoor ALam
This document discusses computer programming functions, variables, and basic input/output in C and C++. It covers:
- Defining and calling functions, function parameters and return values.
- Declaring and assigning values to variables of different data types like int, float, and double.
- Using basic input/output functions like cout and cin to display output and get user input.
- The scope of variables and how they work within and outside of functions.
The document discusses functions in C programming. It defines what a function is and explains the advantages of using functions, such as avoiding duplicate code and improving reusability. It describes the different parts of a function - declaration, definition, and call. It explains user-defined and standard library functions. It also covers parameter passing techniques (call by value and call by reference), recursion, and dynamic memory allocation using functions like malloc(), calloc(), realloc(), and free().
This document discusses various types of operators in C programming. It describes arithmetic, relational, logical, assignment, increment/decrement, conditional, bitwise, and special operators. Examples are provided for each type of operator to demonstrate their usage. The key types of operators covered are arithmetic (e.g. +, -, *, /), relational (e.g. <, >, ==), logical (e.g. &&, ||), assignment (=), increment/decrement (++, --), and conditional/ternary (?:) operators. Special operators like sizeof and comma operators are also briefly explained.
The document provides 20 programming problems and their solutions. Some of the key problems include: writing programs to calculate factorial using recursion, determine if a number is even or odd, swap two numbers using temporary/bitwise operators, find greatest of 3/10 numbers, check if a number is prime/palindromic, and check if a string is a palindrome. The solutions provide sample code snippets and explanations with examples to illustrate the logic.
FUNCTION
INTRODUCTION & WRITING FUNCTIONS, SCOPE OF VARIABLES FUNCTIONS (INCLUDING USING BUILT IN LIBRARIES), PARAMETER PASSING IN FUNCTIONS, CALL BY VALUE, PASSING ARRAYS TO FUNCTIONS: IDEA OF CALL BY REFERENCE
Problem solving using computers - Unit 1 - Study materialTo Sum It Up
Problem solving using computers involves transforming a problem description into a solution using problem-solving strategies, techniques, and tools. Programming is a problem-solving activity where instructions are written for a computer to solve something. The document then discusses the steps in problem solving like definition, analysis, approach, coding, testing etc. It provides examples of algorithms, flowcharts, pseudocode and discusses concepts like top-down design, time complexity, space complexity and ways to swap variables and count values.
Programming Fundamentals Functions in C and typesimtiazalijoono
Programming Fundamentals
Functions in C
Lecture Outline
• Functions
• Function declaration
• Function call
• Function definition
– Passing arguments to function
1) Passing constants
2) Passing variables
– Pass by value
– Returning values from functions
• Preprocessor directives
• Local and external variables
There are two ways to initialize a structure:
1. Initialize structure members individually when declaring structure variables:
struct point {
int x;
int y;
} p1 = {1, 2};
2. Initialize an anonymous structure and assign it to a variable:
struct point p2 = {3, 4};
Structures allow grouping of related data types together under one name. They are useful for representing records, objects, and other data aggregates. Structures can contain nested structures as members. Arrays of structures are also possible. Structures provide data abstraction by allowing access to their members using dot operator.
The document discusses functions in C++ and provides examples of defining and calling functions. It explains that a function allows structuring programs in a modular way and accessing structured programming capabilities. A function is defined with a return type, name, parameters, and body. Parameters allow passing arguments when calling the function. The function examples demonstrate defining an addition function, calling it from main to add two numbers and return the result. It also covers function scope, with local variables only accessible within the function and global variables accessible anywhere.
Trends Spotting Strategic foresight for tomorrow’s education systems - Debora...EduSkills OECD
Deborah Nusche, Senior Analyst, OECD presents at the OECD webinar 'Trends Spotting: Strategic foresight for tomorrow’s education systems' on 5 June 2025. You can check out the webinar on the website https://oecdedutoday.com/webinars/ Other speakers included: Deborah Nusche, Senior Analyst, OECD
Sophie Howe, Future Governance Adviser at the School of International Futures, first Future Generations Commissioner for Wales (2016-2023)
Davina Marie, Interdisciplinary Lead, Queens College London
Thomas Jørgensen, Director for Policy Coordination and Foresight at European University Association
Slides from a Capitol Technology University presentation covering doctoral programs offered by the university. All programs are online, and regionally accredited. The presentation covers degree program details, tuition, financial aid and the application process.
This presentation has been made keeping in mind the students of undergraduate and postgraduate level. To keep the facts in a natural form and to display the material in more detail, the help of various books, websites and online medium has been taken. Whatever medium the material or facts have been taken from, an attempt has been made by the presenter to give their reference at the end.
In the seventh century, the rule of Sindh state was in the hands of Rai dynasty. We know the names of five kings of this dynasty- Rai Divji, Rai Singhras, Rai Sahasi, Rai Sihras II and Rai Sahasi II. During the time of Rai Sihras II, Nimruz of Persia attacked Sindh and killed him. After the return of the Persians, Rai Sahasi II became the king. After killing him, one of his Brahmin ministers named Chach took over the throne. He married the widow of Rai Sahasi and became the ruler of entire Sindh by suppressing the rebellions of the governors.
Artificial intelligence Presented by JM.jmansha170
AI (Artificial Intelligence) :
"AI is the ability of machines to mimic human intelligence, such as learning, decision-making, and problem-solving."
Important Points about AI:
1. Learning – AI can learn from data (Machine Learning).
2. Automation – It helps automate repetitive tasks.
3. Decision Making – AI can analyze and make decisions faster than humans.
4. Natural Language Processing (NLP) – AI can understand and generate human language.
5. Vision & Recognition – AI can recognize images, faces, and patterns.
6. Used In – Healthcare, finance, robotics, education, and more.
Owner By:
Name : Junaid Mansha
Work : Web Developer and Graphics Designer
Contact us : +92 322 2291672
Email : [email protected]
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...parmarjuli1412
The document provides an overview of therapeutic communication, emphasizing its importance in nursing to address patient needs and establish effective relationships. THERAPEUTIC COMMUNICATION included some topics like introduction of COMMUNICATION, definition, types, process of communication, definition therapeutic communication, goal, techniques of therapeutic communication, non-therapeutic communication, few ways to improved therapeutic communication, characteristics of therapeutic communication, barrier of THERAPEUTIC RELATIONSHIP, introduction of interpersonal relationship, types of IPR, elements/ dynamics of IPR, introduction of therapeutic nurse patient relationship, definition, purpose, elements/characteristics , and phases of therapeutic communication, definition of Johari window, uses, what actually model represent and its areas, THERAPEUTIC IMPASSES and its management in 5th semester Bsc. nursing and 2nd GNM students
Ray Dalio How Countries go Broke the Big CycleDadang Solihin
A complete and practical understanding of the Big Debt Cycle. A much more practical understanding of how supply and demand really work compared to the conventional economic thinking. A complete and practical understanding of the Overall Big Cycle, which is driven by the Big Debt Cycle and the other major cycles, including the big political cycle within countries that changes political orders and the big geopolitical cycle that changes world orders.
HOW YOU DOIN'?
Cool, cool, cool...
Because that's what she said after THE QUIZ CLUB OF PSGCAS' TV SHOW quiz.
Grab your popcorn and be seated.
QM: THARUN S A
BCom Accounting and Finance (2023-26)
THE QUIZ CLUB OF PSGCAS.
This presentation was provided by Nicole 'Nici" Pfeiffer of the Center for Open Science (COS), during the first session of our 2025 NISO training series "Secrets to Changing Behavior in Scholarly Communications." Session One was held June 5, 2025.
A short update and next week. I am writing both Session 9 and Orientation S1.
As a Guest Student,
You are now upgraded to Grad Level.
See Uploads for “Student Checkin” & “S8”. Thx.
Thank you for attending our workshops.
If you are new, do welcome.
Grad Students: I am planning a Reiki-Yoga Master Course (As a package). I’m Fusing both together.
This will include the foundation of each practice. Our Free Workshops can be used with any Reiki Yoga training package. Traditional Reiki does host rules and ethics. Its silent and within the JP Culture/Area/Training/Word of Mouth. It allows remote healing but there’s limits As practitioners and masters. We are not allowed to share certain secrets/tools. Some content is designed only for “Masters”. Some yoga are similar like the Kriya Yoga-Church (Vowed Lessons). We will review both Reiki and Yoga (Master tools) in the Course upcoming.
Session Practice, For Reference:
Before starting a session, Make sure to check your environment. Nothing stressful. Later, You can decorate a space as well.
Check the comfort level, any needed resources (Yoga/Reiki/Spa Props), or Meditation Asst?
Props can be oils, sage, incense, candles, crystals, pillows, blankets, yoga mat, any theme applies.
Select your comfort Pose. This can be standing, sitting, laying down, or a combination.
Monitor your breath. You can add exercises.
Add any mantras or affirmations. This does aid mind and spirit. It helps you to focus.
Also you can set intentions using a candle.
The Yoga-key is balancing mind, body, and spirit.
Finally, The Duration can be long or short.
Its a good session base for any style.
Next Week’s Focus:
A continuation of Intuition Development. We will review the Chakra System - Our temple. A misguided, misused situation lol. This will also serve Attunement later.
For Sponsor,
General updates,
& Donations:
Please visit:
https://ldmchapels.weebly.com
How to Configure Vendor Management in Lunch App of Odoo 18Celine George
The Vendor management in the Lunch app of Odoo 18 is the central hub for managing all aspects of the restaurants or caterers that provide food for your employees.
How to Create an Event in Odoo 18 - Odoo 18 SlidesCeline George
Creating an event in Odoo 18 is a straightforward process that allows you to manage various aspects of your event efficiently.
Odoo 18 Events Module is a powerful tool for organizing and managing events of all sizes, from conferences and workshops to webinars and meetups.
How to Create Quotation Templates Sequence in Odoo 18 SalesCeline George
In this slide, we’ll discuss on how to create quotation templates sequence in Odoo 18 Sales. Odoo 18 Sales offers a variety of quotation templates that can be used to create different types of sales documents.
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecdrazelitouali
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Unit- 4 Biostatistics & Research Methodology.pdfKRUTIKA CHANNE
Blocking and confounding (when a third variable, or confounder, influences both the exposure and the outcome) system for Two-level factorials (a type of experimental design where each factor (independent variable) is investigated at only two levels, typically denoted as "high" and "low" or "+1" and "-1")
Regression modeling (statistical model that estimates the relationship between one dependent variable and one or more independent variables using a line): Hypothesis testing in Simple and Multiple regression models
Introduction to Practical components of Industrial and Clinical Trials Problems: Statistical Analysis Using Excel, SPSS, MINITAB®️, DESIGN OF EXPERIMENTS, R - Online Statistical Software to Industrial and Clinical trial approach
How to Manage Upselling of Subscriptions in Odoo 18Celine George
Subscriptions in Odoo 18 are designed to auto-renew indefinitely, ensuring continuous service for customers. However, businesses often need flexibility to adjust pricing or quantities based on evolving customer needs.
How to Manage Upselling of Subscriptions in Odoo 18Celine George
Ad
introduction to python programming course 2
1. Recap Python
programming of the
previous week
• Python script files rules: one statement per line,
each statement starting in the 1st column
• A simple program contains 3 steps: Input,
Processing, Output
• Input involves assigning values to variables. It can
be done with assignment lines (such as a = 12) or
by reading the values from the keyboard (such as a
= int(input(‘Enter the value of a:’)) ). Note that
int() and input() are Python functions.
• Processing involves operations with the variables
• Output to the black screen involves the use of the
print() function
Slides are adapted from prof Radu I Campeanu
3. Assignment statements
• In a program, a variable is a named item, such as a, used to hold a value.
• An assignment statement assigns a value to a variable, such as a = 4.
• ‘=‘ has nothing to do with mathematics. In computer programming it means
assignment, i.e. it gives the value 4 to the variable a.
• a = b means that the value of b is copied into a; as a result both variables a and
b have the same value.
• a = a+1 means that the value of a is incremented by 1. An alternative is to write
a +=1 (the meaning of ‘+=‘ is increment by the value on the right)
4. Objects
• Python variables are also called objects.
• Each Python object has three properties: value, type, and identity.
- Value: A value such as 4 or "abcdef".
- Type: The type of the object, such as integer or string.
- Identity: A unique identifier that describes the object
(i.e. its address in the principal memory).
a=4
print(a) # Output: 4
print(type(a)) # Output: <class ‘int’>
print(id(a)) # Output: 140728879073924
5. Floating-point numbers
• Floating-point numbers are real number, like 98.6 or 0.0001.
• The built-in function float() is used for these numbers, which have decimals.
#P1 calculate hours to cover the distance
miles = float(input('Enter a distance in miles: '))
hours_to_fly = miles / 500.0 #500 miles/hour is the speed to fly
hours_to_drive = miles / 60.0 #60 miles/hour is the speed to drive
print(miles, 'miles would take:')
print(hours_to_fly, 'hours to fly')
print(hours_to_drive, 'hours to drive’)
Input/Output:
Enter a distance in miles: 450
450.0 miles would take:
0.9 hours to fly
7.5 hours to drive
6. Scientific notation
• Scientific notation is useful for representing floating-point numbers that are much greater
than or much less than 0, such as 6.02x1023
• 6.02x1023 is written as 6.02e23
• Float-type objects can be stored on a 32 bits (or 4 bytes) computer if their values are
between 2.3x10-308 and 1.8x10308
• Outside this interval the float-type object produces underflow/overflow.
• Ex. print(2**1024) will produce an overflow error (‘2**1024’ means 2 to the
power 1024). Note that print() accepts mathematical expressions, which are executed before
the display of the result.
7. Formatting floating-point output
• Some floating-point numbers have many digits after the decimal point. Ex: Irrational numbers
such as the value of Pi = 3.14159265359…
• Python has the method format() which allows the reduction of the number of decimals
#P2
pi_v = 3.141592653589793
print('Default output of Pi:', pi_v)
print('Pi reduced to 4 digits after the decimal:', end=' ')
print('{:.4f}'.format(pi_v))
Output:
Default output of Pi: 3.141592653589793
Pi reduced to 4 digits after the decimal: 3.1416
8. Arithmetic Expressions
• An expression is a combination of items, like variables, operators, and parentheses, that evaluates
to a value. For example: 2 * (x + 1).
• A common place where expressions are used is on the right side of an assignment statement, as in
y = 2 * (x + 1).
• The arithmetic operators are: +, -, *, /, %, **
• % is the modulo operator producing the remainder of an int division
• ** is the exponent, or power operator
• In a long expression the following precedence rules will apply:
- operations inside parentheses are executed first
- unary minus and the exponent are executed next (ex. x* -2, 2 * x**2)
- next are *,/,% in the left-to-right order
- last are +, - in the left-to-right order
9. Examples
• total_cost = down_payment + payment_per_month * num_months
• 24 % 10 is 4. Reason: 24 / 10 is 2 with remainder 4.
• 50 % 50 is 0. Reason: 50 / 50 is 1 with remainder 0.
• 1 % 2 is 1. Reason: 1 / 2 is 0 with remainder 1.
• 20 / 10 is 2.0 (Division with ‘/’ produces a float)
• 50 / 50 is 1.0
• 5 / 10 is 0.5
• 20//10 is 2 (‘//’ is the floored division operator; produces an int)
• print(12 - 1 / 2 * 3 % 4 + 10 / 2 * 4) produces 30.5
10. Example 1 - money
The program shown below shows the calculation of the number of $5 bills for a certain integer
amount. What is the output if the input is 19?
#P3
amount_to_change = int(input())
num_fives = amount_to_change // 5
num_ones = amount_to_change % 5
print('Change for $', amount_to_change)
print(num_fives, 'five dollar bill(s) and', num_ones, 'one dollar coin(s)’)
Ans:
Change for $ 19
3 five dollar bill(s) and 4 one dollar coin(s)
11. Example 2 - time
The program shown below extracts the number of hours from an input of minutes. What will be
the output for 275 ?
#P4
minutes = int(input('Enter minutes:'))
hours = minutes // 60
minutes_remaining = minutes % 60
print(minutes, 'minutes is', end=' ')
print(hours, 'hours and', end=' ')
print(minutes_remaining, 'minutes.n', end=' ‘)
Input/Output
Enter minutes: 275
275 minutes is 4 hours and 35 minutes
12. Digits in an integer
The last digit in 23 is obtained by: 23%10
The last 3 digits in 1234 are obtained by:
1234%1000
The first digit in 23 is obtained by: 23//10
The first digit in 1234 is obtained by: 1234//1000
13. Example 3 - Telephone
number
#P5
nr = int(input('Enter a 10 digit integer:'))
tmp = nr // 10000 #tmp will have the value 103458
mid = tmp % 1000 #mid will have the value 458
first = nr // 10000000 #first will have the value 103
last = nr % 10000 #last will have the value 8231
print('(',first,') ',mid,'-',last) #notice the brackets and -
Input/Output:
Enter a 10 digit integer: 1034588231
( 103 ) 458 - 8231
14. Using modules
• Programmers often write code in more than just a single script file. Collections of logically
related code can be stored in separate files, and then imported for use into a script that
requires that code.
• A module is a file containing Python code that can be used by other modules or scripts.
• A module is made available for use via the import statement.
• Once a module is imported, any object defined in that module can be accessed using dot
notation.
• Python comes with a number of predefined modules, such as math and random.
15. Using the random module
• Python has a randrange() function as part of the module random. This function creates a
random integer between the function parameters.
import random
print(random.randrange(1,10)) # the dot notation
Output:
6 # a random number between 1 and 10
• An alternative is:
from random import randrange
print(randrange(1,10))
Output:
8 # another random number between 1 and 10
16. Equation Solutions using the
math module
The solutions for the equation ax2 + bx + c = 0 are:
𝑥1 =
−𝑏 + 𝑑
2𝑎
and 𝑥2 =
−𝑏 − 𝑑
2𝑎
, where d = b2 - 4ac
Write a Python program which enters from the keyboard the values of a, b, c (as integers) and then calculates and
shows x1 and x2.
#P6
import math
a = int(input('Enter the value of a:'))
b = int(input('Enter the value of b:'))
c = int(input('Enter the value of c:'))
d = b*b - 4*a*c;
x1 = (-b + math.sqrt(d))/2/a
x2 = (-b – math.sqrt(d))/2/a
print('x1=', x1)
print('x2=', x2)
17. Using the math module
Given three floating-point numbers x, y, and z, output x to the power of z, x to the power of (y to the power of z), the
absolute value of (x minus y), and the square root of (x to the power of z).
#P7
import math
x=float(input()) # enter 5.0
y=float(input()) # enter 1.5
z=float(input()) # enter 3.2
v1=x**z
v2=x**(y**z)
v3=math.fabs(x-y)
v4=math.sqrt(x**z)
print('{:.2f} {:.2f} {:.2f} {:.2f}'.format(v1,v2,v3,v4))
Output:
172.47 361.66 3.50 13.13
18. Using the random module
• Write a Python program which rolls two dice. This program should use the module random.
#P8
import random
a = random.randrange(1,6)
b = random.randrange(1,6)
print(‘the sum is ‘, a+b)
Possible Output:
the sum is 10
19. Using Constants in Python
• Constants are variables which have values that cannot be changed during the execution of the program
• In other programming languages such as C constants are written in capital letters. In Java one uses the reserved
word final in front of the constant to ensure that its value cannot be changed.
• Python does not have a way to enforce that the value of a constant is not changed. A good method to signal that
certain variables are constants is to create a constants module.
20. Creating and using the constants module
The time of a free falling object from a certain height is given by the following
formula: time = (2 ∗ height / g), where g is the gravitational constant.
In this program let us compare the times for falls on Earth and Mars.
constants.py # user defined module
# Gravitational constants for various planets
earth_g = 9.81 # m/s**2
mars_g = 3.71
========================================================
fall_time.py
#P9
# Find seconds to drop from a height on some planets.
import constants
import math # module available in Python
height = int(input('Height in meters: ')) # Meters from planet
print('Earth:', math.sqrt(2 * height / constants.earth_g), 'seconds')
print('Mars:', math.sqrt(2 * height / constants.mars_g), 'seconds’)
# notice the dot notation for functions and constants
21. Class exercise - Distance
between two points
The distance between point (x1, y1) and point (x2, y2) is given by the formula:
(x2 − x1)∗∗2 + (y2 − y1)∗∗2 .
All these variables have floating - point numbers.
Write a Python program which reads the coordinates of the 2 points and shows the value of
the distance, shown as a floating – point number with 3 decimals.
For example if the 4 numbers entered are 1.1, 2.2, 4.4 and 5.5
The output should be: Points distance: 4.667