COMPSCI 101 Principles of Programming Lecture 6 – Getting user input, converting between types, generating random numbers.

Slides:



Advertisements
Similar presentations
COMPSCI 101 Principles of Programming Lecture 5 – Manipulating strings, String functions, dot notation.
Advertisements

Python November 14, Unit 7. Python Hello world, in class.
1 September 6, 2005CS150 Introduction to Computer Science I What Actions Do We Have Part 1 CS150 Introduction to Computer Science I.
Introduction to Python
CS 1 with Robots Variables, Data Types & Math Institute for Personal Robots in Education (IPRE)‏
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Lecture 11 – if … else, if... elif statements, nested ifs COMPSCI 1 1 Principles of Programming.
Lecture 13 – range function, for…in loops COMPSCI 1 1 Principles of Programming.
COMPSCI 101 Principles of Programming
Input/Output  Input/Output operations are performed using input/output functions  Common input/output functions are provided as part of C’s standard.
Lecture 2 - Variables, program execution, calculations, print() COMPSCI 101 Principles of Programming.
INLS 560 – V ARIABLES, E XPRESSIONS, AND S TATEMENTS Instructor: Jason Carter.
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #002 (January 17, 2015)
FUNCTIONS. Function call: >>> type(32) The name of the function is type. The expression in parentheses is called the argument of the function. Built-in.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
PYTHON. Python is a high-level, interpreted, interactive and object- oriented scripting language. Python was designed to be highly readable which uses.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Computer Science 111 Fundamentals of Programming I Basic Program Elements.
Data Types Integer 15 StringHelloThere! Float/Real BooleanYes / No CharP.
Lecture 20 – Test revision COMPSCI 101 Principles of Programming.
Chapter 3 Processing and Interactive Input. 2 Assignment  The general syntax for an assignment statement is variable = operand; The operand to the right.
CNG 140 C Programming Lecture Notes 2 Processing and Interactive Input Spring 2007.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Input, Output, and Processing
Lecture 10 – Boolean expressions, if statements COMPSCI 101 Principles of Programming.
COMPSCI 101 Principles of Programming Lecture 4 –The type() function, the string type, the len() function, string slices.
COMPSCI 101 Principles of Programming Lecture 25 – Nested loops, passing mutable objects as parameters.
Lecture 2: Introduction to C Programming. OBJECTIVES In this lecture you will learn:  To use simple input and output statements.  The fundamental data.
1 while loops. 2 Definite loops definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. We.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
COMP 171: Data Types John Barr. Review - What is Computer Science? Problem Solving  Recognizing Patterns  If you can find a pattern in the way you solve.
Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.
Variables, Expressions and Statements
Python Conditionals chapter 5
Variables and Assignment CSIS 1595: Fundamentals of Programming and Problem Solving 1.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Debugging, Escape Command, More Math. It’s your birthday!  Write a program that asks the user for their name and their age.  Figure out what their birth.
COP 2510 Chapter 6 - Functions. Random function (randint) #import the desired function import random #integer random number in the range of 1 through.
Variables, Types, Expressions Intro2CS – week 1b 1.
Data Types and Conversions, Input from the Keyboard If you can't write it down in English, you can't code it. -- Peter Halpern If you lie to the computer,
29 January 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
Introduction to Programming Python Lab 5: Strings and Output 05 February PythonLab5 lecture slides.ppt Ping Brennan
5 February 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems.
COMPUTER PROGRAMMING Year 9 – lesson 1. Objective and Outcome Teaching Objective We are going to look at how to construct a computer program. We will.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Introduction to Python Lesson 2a Print and Types.
Input, Output and Variables GCSE Computer Science – Python.
Introduction to Programming
Fundamentals of Programming I Overview of Programming
Topics Designing a Program Input, Processing, and Output
Topic: Python’s building blocks -> Statements
Intro to CS Nov 2, 2015.
Data Types and Conversions, Input from the Keyboard
COMPSCI 107 Computer Science Fundamentals
CMPT 120 Topic: Python strings.
Variables, Expressions, and IO
Introduction to Programming
OUTPUT STATEMENTS GC 201.
INPUT & OUTPUT scanf & printf.
Introduction to C++ Programming
Introduction to Programming
Introduction to Programming
Variables, Data Types & Math
Variables, Data Types & Math
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Terminal-Based Programs
COMPUTER PROGRAMMING SKILLS
CISC101 Reminders Assignment 3 due today.
Presentation transcript:

COMPSCI 101 Principles of Programming Lecture 6 – Getting user input, converting between types, generating random numbers

Exercise  What is the output after executing the following code? CompSci 1012 greeting = "Hello World" greeting = greeting.strip() position1 = greeting.find("o") position2 = greeting.rfind("o") position3 = greeting.find("Z") position4 = greeting.rfind("o W") greeting_lower = greeting.lower() greeting_upper = greeting.upper() print(greeting) print(position1, position2, position3, position4) print(greeting_lower) print(greeting_upper) greeting = "Hello World" greeting = greeting.strip() position1 = greeting.find("o") position2 = greeting.rfind("o") position3 = greeting.find("Z") position4 = greeting.rfind("o W") greeting_lower = greeting.lower() greeting_upper = greeting.upper() print(greeting) print(position1, position2, position3, position4) print(greeting_lower) print(greeting_upper)

Exercise  What is the output after executing the following code? CompSci 1013 smallest = min(32.7, 56.4, 3, -1.1, 56.99, -1.2) largest = max(32.7, 56.4, 3, -1.1, 56.99, -1.2) print(smallest, largest) num1 = print(round(num1)) print(round(num1, 2)) smallest = min(32.7, 56.4, 3, -1.1, 56.99, -1.2) largest = max(32.7, 56.4, 3, -1.1, 56.99, -1.2) print(smallest, largest) num1 = print(round(num1)) print(round(num1, 2))

Learning outcomes  At the end of this lecture, students should be able to:  get user input from the keyboard  generate a random number  convert between types CompSci 1014

Getting input from the user  The input() function is used to get information from the user.  This function displays the prompt, waits for the user to type their information and, as soon as the user presses the 'Enter' key, the input() function returns the information typed by the user (to the variable on the left of the assignment operator). CompSci 1015 user_name = input("Enter name: ") colour = input("Enter colour: ") user_word = input("Enter word: ") print(user_name, "entered", colour, "and the word", user_word) user_name = input("Enter name: ") colour = input("Enter colour: ") user_word = input("Enter word: ") print(user_name, "entered", colour, "and the word", user_word) Enter name: Adriana Enter colour: magenta Enter word: parola Adriana entered magenta and the word parola The user input is shown in bold in a pink colour DEMO Example01.py

Getting input from the user  The input() function can be used with no argument (nothing inside the round brackets) in which case there is no prompt printed.  For example: CompSci 1016 user_number = input("Enter number: ") user_input = input() print("The user entered", user_number, "and then", user_input) user_number = input("Enter number: ") user_input = input() print("The user entered", user_number, "and then", user_input) Enter number: 98 ??? #user enters stuff here The user entered 98 and then ??? Not recommended! The user input is shown in bold in a pink colour

Getting input from the user  The input() function always returns a string. The end of line character is not returned as part of the returned string.  For example CompSci 1017 user_number = input("Enter number: ") value = "hello" print(value + user_number ) user_number = input("Enter number: ") value = "hello" print(value + user_number ) Enter number: 1 hello1 Concatenating two strings together DEMO Example03.py

Exercise 1  Complete the output if the user enters the number 54 when prompted: CompSci 1018 user_number = input("Enter number: ") print(user_number * 2, user_number * 3, user_number * 4) user_number = input("Enter number: ") print(user_number * 2, user_number * 3, user_number * 4) Enter number: 54

Random numbers  Quite often, in our programs, we need a random number, e.g., for games and simulations.  The random module contains a function, randrange(), which can be used to generate a random number.  In order to use this function we need to import the random module into our program (just as we did when we wanted to use the functions of the math class – math.sin(), math.cos(), …).  Whenever we need to get a random number in a program, the first line will be the following import statement: CompSci 1019 import random

Random numbers  The randrange() function returns a random integer between start (inclusive) and stop (exclusive) using the syntax:  For example:  randrange(5, 10) has an equal chance of generating 5, 6, 7, 8 or 9. CompSci import random number = random.randrange(5, 10) import random number = random.randrange(5, 10) randrange(start, stop) import random dice1 = random.randrange(1, 7) dice2 = random.randrange(1, 7) print("You threw", dice1, "and a", dice2) import random dice1 = random.randrange(1, 7) dice2 = random.randrange(1, 7) print("You threw", dice1, "and a", dice2) You threw 4 and a 1 DEMO Example04.py

Random numbers  The randrange() function has an optional step argument:  The step argument dictates which random numbers are generated within the range (the amount to add to the starting number), e.g., CompSci random.randrange(1, 7, 2) #generates either 1, 3 or 5 random.randrange(1, 7, 3) #generates either 1 or 4 random.randrange(1, 7, 2) #generates either 1, 3 or 5 random.randrange(1, 7, 3) #generates either 1 or 4 randrange(start, stop, step) The default step when the step argument is omitted is 1. random.randrange(-30, 100, 30) #generates either -30, 0, 30, 60, or 90.

Exercise 2  Give the smallest and the largest possible random number which can be generated by the following four statements: CompSci import random print(random.randrange(4, 17, 3)) print(random.randrange(-1, 7, 2)) print(random.randrange(100, 700, 2)) print(random.randrange(50, 100, 10)) import random print(random.randrange(4, 17, 3)) print(random.randrange(-1, 7, 2)) print(random.randrange(100, 700, 2)) print(random.randrange(50, 100, 10))

Exercise 3  Complete the following program so that it prompts the user for their full name (assumes a single space between the first name and the second name).  The program removes a random letter from the first name and a random letter from the surname and prints the resulting name. CompSci Enter name: Adriana Ferraro Adriaa Frraro import random full_name = input("Enter your full name: ") print(full_name) import random full_name = input("Enter your full name: ") print(full_name)

Algorithm Prompt the user for their full nameFind the blank space position Get the surname, first_name first_name: 0 to blank_pos surname: blank_pos + 1 to the end Generate two random numbers A random number within 0 to len(first_name) A random number within 0 to len(surname) CompSci blank_pos

Ooops!  The following code causes an error:  What does this error message mean?  The subtraction operator (-) has no meaning if one of the operands is a string. We want to find a way of converting a string containing digits into a number. CompSci age = input("Enter age: ") years_to_go = age print("Big birthday coming up in ", years_to_go, "years!") age = input("Enter age: ") years_to_go = age print("Big birthday coming up in ", years_to_go, "years!") Enter age: 54 … years_to_go = age TypeError: unsupported operand type(s) for -: 'int' and 'str' “54” It is a 'TypeError', where you tried to subtract incompatible variables. DEMO Example05.py

Converting between types  The int() function converts a string containing characters which are digits into the corresponding integer value.  The float(x) function returns a floating point number constructed from a number or string x CompSci age = int(input("Enter age: ")) years_to_go = age print("Big birthday coming up in ", years_to_go, "years!") age = int(input("Enter age: ")) years_to_go = age print("Big birthday coming up in ", years_to_go, "years!") Enter age: 54 Big birthday coming up in 46 years! Enter cost $ Final price $ cost = input("Enter cost $") cost = float(cost) final_price = cost * 0.92 print("Final price $", final_price, sep="") cost = input("Enter cost $") cost = float(cost) final_price = cost * 0.92 print("Final price $", final_price, sep="")

Converting between types  The str() function returns a string version of object  Note: String concatenation requires the two operands to be strings:  For examples: CompSci You threw 3 and a 5 print("You threw", dice1, "and a", dice2) print("You threw" + dice1 + "and a" + dice2) TypeError: Can't convert 'int' object to str implicitly print("You threw " + str(dice1) + " and a " + str(dice2)) You threw 3 and a 5 convert it to a string object need to add a space

Converting between types  The conversion has to be legal. Below are two illegal attempts to convert:  Note that converting a string which has no decimal point into a float is fine: CompSci number = int("12 34") ValueError: invalid literal for int() with base 10: '12 34' number = int("12.34") ValueError: invalid literal for int() with base 10: '12.34' should not have a space in between It is not an integer! number = float("12") print(number) number = float("12") print(number) 12.0

The backslash character  The backslash character at the end of a line of code in the program indicates that the statement continues onto the next line, e.g., CompSci user_dice = input("Enter dice throw: ") comp_dice = random.randrange(1, 7) message = "Your dice: " + user_dice + ", computer dice: " \ + str(comp_dice) print(message) user_dice = input("Enter dice throw: ") comp_dice = random.randrange(1, 7) message = "Your dice: " + user_dice + ", computer dice: " \ + str(comp_dice) print(message) Note that the backslash is the last character in the line of code and is not inside a string (i.e., outside the quotes).

Exercise 4  MCQ:  The expression "Good " evaluates to ________.  A. Good123  B. Good6  C. Good 123  D. TypeError: Can't convert 'int' object to str implicitly CompSci 10120

Exercise 5  Complete the following program which prompts the user for a total of 4 dice throws, the programs calculates the sum of four random dice throws, and outputs the difference between the user guess and the sum of the dice throwing simulation: CompSci dice_sum = 0 print("Your total:", ) print("You are out by:", ) dice_sum = 0 print("Your total:", ) print("You are out by:", ) Enter sum (4 dice): 12 Your total: 12 Dice total: 20 You are out by: 8 Enter sum (4 dice): 15 Your total: 15 Dice total: 11 You are out by: 4 Enter sum (4 dice): 12 Your total: 12 Dice total: 12 You are out by: 0

Algorithm CompSci Prompt the user for the totalCreate a variable dice_sum Repeat the following steps x 4 times Generate a new random number Add the value to the dice_sum Calculate the difference between the dice_sum and the total Print the result

Summary  In a Python program:  the input() function is used to get user input from the keyboard  a random number can be generated using random.randrange(…)  we can convert between types using str(), int(), float() CompSci 10123