Module 3 Chapter 7 User Input and While Loops

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

quit value syntax

'quit'

Clear Prompts

Be friendly to your user! Include a clear, easy-to-follow prompt Tell the user exactly what to do, what to enter

Using break to

Exit a Loop

Use continue in a

Loop

input()

Prompt the user for an input and then Pause the program and waits for the user to enter text Bring a string value into the program

Moving Items from One List to Another output

Verifying user: Carol Verifying user: Bob Verifying user: Alice The following users have been confirmed: Carol Bob Alice

Filling a Dictionary with User Input output example

What is your name? alice What grade do you expect in CSCI 1200? a Are there others to take the poll? yes What is your name? Bob What grade to you expect in CSCI 1200? B Are there others to take the poll? yes What is your name? carol What grade do you expect in CSCI 1200? c Are there others to take the poll? no --- CSCI 1200 Poll --- Alice expects to receive a grade of A Bob expects to receive a grade of B Carol expects to receive a grade of C

flag variable

active

flag variable

acts as a signal to a program

We can use a quit value to

allow a program to run as long as the user wants to Letting the User Choose

Pass the prompt variable as our

argument to the input() function

Using while loops with Lists and Dictionaries allows us to

collect, store, and organize input to examine and report on later

Gearing up for Infinity

continue statement used

int()

converts the string to an integer

continue statement example

current_number = 0 while current_number < 10: current_number += 1 if current_number % 2 == 0: continue print(current_number) ________________________

int() syntax

dict name=int(dict name)

•A continue statement

directs the flow of your program.

A break statement

directs the flow of your program. Works in for loops as well.

The modulo operator %

divides one number by another and returns the remainder.

= (operator)

example and equivalent to x = 5

We'll use a while loop to

fill a dictionary with user input

while loops

flag variable break statement continue statement

•Any problem with my rearrangement of this code? __________________________________________________ current_number = 0 while current_number < 10: if current_number % 2 == 0: continue current_number += 1 print(current_number)

if current_number % 2 == 0:- check if even or odd if even will be equal to zero *ask if divded by 2 from continous current print(current_number)- no results bur progress runs forever

Users provide

input to programs

We'll use a while loop to

move items from one list to another

Allows for

multi-line prompts

Removing All Instances of a value from a List syntax (USE REMOVE STATEMENT)

name of list.remove (list item) ex: pets.remove('cat')

While Loop Example

number = 1 while number <= 5: print(number) number += 1 __________________________________________________ ---------------------------------------------------------------------------------- 1 2 3 4 5 ----------------------------------------------------------------------------------

The Modulo Operator example

number = input('Enter a number: ') print(f"You entered {number}.") number = int(number) if number % 2 == 0: print(f"The number {str(number)} is divisible by 2.") else: print(f"The number {str(number)} is not divisible by 2.") __________________________________________________ ---------------------------------------------------------------------------------- Enter a number: 42 You entered 42. The number 42 is divisible by 2.

Removing All Instances of a value from a List example

pets = ['dog', 'cat', 'iguana', 'cat', 'dog', 'cat', 'python'] while 'cat' in pets: pets.remove('cat') print(pets) _________________________________________________ ------------------------------------------------------------------------------------------------ ['dog', 'iguana', 'dog', 'python']

Moving Items from One List to Another

pop() method

Programmers write code to have

programs interact with users

input and += (compound assignment operator) example

prompt = 'Tell us who you are, so we can personalize your messages.' prompt += '\nWhat is your name?' user_name = input(prompt) print(f"Hello, {user_name}!") __________________________________________________ ---------------------------------------------------------------------------------- Tell us who you are, so we can personalize your messages. What is your name? Steven Hello, Steven!

We'll use Python's input() function to

prompt a user for input and receive that input into the program

We'll use a while loop to

remove all instances of specific values from a list

pop()

removes the last item from a list

Filling a Dictionary with User Input example

responses = {} polling_active = True while polling_active: name = input('What is your name? ') response = input('What grade do you expect in CSCI 1200? ') responses[name] = response repeat = input('\nAre there others to take the poll? (yes / no) ') if repeat == 'no': polling_active = False print(f"\n --- CSCI 1200 Poll ---") for name, response in responses.items(): print(f"{name.title()} expects to receive a grade of {response.upper()}")

while loop

runs as long as, or while, a certain condition is true.

continue

skips the rest of the iteration and returns to the beginning

Most programs are written to

solve a user's requirement/problem

Once the program receives the input, it

stores it as a variable's value

for loop

takes a collection of terms and executes a block of code once for each item in the collection or values in a range

The input() function

takes one argument; the prompt, or instructions to present to the user

int()

tells Python to treat the argument as a numerical (integer) value

for vs while loop

the for is usually appropriate for loops in which the initialization and increment are single statements and logically related, since it is more compact than while and it keeps the loop control statements together in one place.

int() converts

the string to an integer

Moving Items from One List to Another example

unconfirmed_users = ['alice', 'bob', 'carol'] confirmed_users = [] while unconfirmed_users: current_user = unconfirmed_users.pop() print(f"Verifying user: {current_user.title()}") confirmed_users.append(current_user) print(f"\tThe following users have been confirmed:") for confirmed_user in confirmed_users: print(confirmed_user.title())

int() example

user_age = input('Enter your age: ') print(f"You indicated you are {user_age} years old.") user_age = int(user_age) print(user_age >= 21) __________________________________________________ ---------------------------------------------------------------------------------- Enter your age: 29 You indicated you are 29 years old. True

input () example

user_name = input('Please enter your name : ') __________________________________________________ ---------------------------------------------------------------------------------- Please enter your name: (cursor waits here till a response)

clear prompts example

user_name = input('Please enter your name: ') print(f"Hello, {user_name} !") __________________________________________________ ---------------------------------------------------------------------------------- Please enter your name: Steven Hello, Steven!

input() syntax

user_name = input('arugment to user : ')

flag example active is flag variable

user_sum = 0 prompt = 'Enter a number and I will add it to your total.' prompt += '\nType quit to exit the program.\n' active = True while active: user_input = input(prompt) if user_input == 'quit': active = False else: user_input = int(user_input) user_sum += user_input print(f"Your total is: {str(user_sum)} \n") print(f"\nYour final total was {str(user_sum)}.") __________________________________________________

quit example

user_sum = 0 prompt = 'Enter a number and I will add it to your total.' prompt += '\nType quit to exit the program.\n' user_input = input(prompt) while user_input != 'quit': user_input = int(user_input) user_sum = user_sum + user_input print(f"Your total is: {str(user_sum)} \n") user_input = input(prompt) print(f"\nYour final total was {str(user_sum)}.") 'quit' is my quit value

break statement example

user_sum = 0 prompt = 'Enter a number and I will add it to your total.' prompt += '\nType quit to exit the program.\n' while True: user_input = input(prompt) if user_input == 'quit': break else: user_input = int(user_input) user_sum = user_sum + user_input print(f"Your total is: {str(user_sum)} \n") print(f"\nYour final total was {str(user_sum)}") break exits the loop immediately

programs prompt

users for input

We can store our prompts as a

variable

%= (operator)

x %= 5 (example) x = x % 5 (equivalent)

**= (operator)

x **= 5 (example) x = x ** 5 (equivalent)

*= (operator)

x *= 5 (example) x = x * 5 (equivalent)

+= (operator)

x += 5 (example) x = x + 5 (equivalent)

-= (operator)

x -= 5 (example) x = x - 5 (equivalent)

//= (operator)

x //= 5 (example) x = x // 5 (equivalent)

/= (operator)

x /= 5 (example) x = x / 5 (equivalent)

avoiding infinite loops example

x = 1 while x <= 5: print(x) x += 1 eliminate x+=1 infinite loop gone

Avoiding Infinite Loops

•Easy to program •They're bad... •Every programmer accidentally codes infinite loops __________________________________________________


Set pelajaran terkait

Marketing: An Introduction - Chapter 5

View Set

Combo with "APUSH Chapter 9" and 6 others

View Set

How to read lit. like a professor Chapter 1-3 & Basics

View Set

Basic principles of life and health insurance

View Set