46 simple python exercises: 6-10!

--Originally published at Home Page

6.-Define a function sum() and a function multiply() that sums and multiplies (respectively) all the numbers in a list of numbers. For example, sum([1, 2, 3, 4]) should return 10, and multiply([1, 2, 3, 4]) should return 24.

EJ6

7.- Define a function reverse() that computes the reversal of a string. For example, reverse(“I am testing”) should return the string “gnitset ma I”.EJ7

8.-Define a function is_palindrome() that recognizes palindromes (i.e. words that look the same written backwards). For example, is_palindrome(“radar”) should return True.EJ8

9.-Write a function is_member() that takes a value (i.e. a number, string, etc) x and a list of values a, and returns True if x is a member of a, False otherwise. (Note that this is exactly what the in operator does, but for the sake of the exercise you should pretend Python did not have this operator.)EJ9

10.-Define a function overlapping() that takes two lists and returns True if they have at least one member in common, False otherwise. You may use your is_member() function, or the in operator, but for the sake of the exercise, you should (also) write it using two nested for-loops.

EJ10

Quiz Week 3

--Originally published at Home Page

 

Functions!!!

For this quiz I want you to (in class) create a program with two functions:

  • def square_root(x):  // returns the square root of x (float)
  • def cube_root(x): // returns the cube root of x (float)

What to Do

You implement this function in your own program in a file quiz3.py.

You should make a main routine that asks the user for a number and then calls your functions to calculate the square and cube roots of that number and prints them out.

What should you do if the user enters a negative number?

Publish your code on your own blog today (during class time is best) and use the tag #Quiz03 so it shows up nicely in our tag cloud.

Solution:

They ask us for 2 functions, so let’s do it!Quiz3-arreglado

In this program, we define two functions, that receive a value “x”, and return, a square and cube root respectively .

In python 3, you can use the operator “**”. to multiply the number n times you want, for example: if you want to multiply 10 times the number 2, you write 2**10.

But, in this case, we express the root as a fractional number in the exponent.

You can read in this page: http://www.purplemath.com/modules/exponent5.htm for more information.

So, that’s what we do with both functions, and don’t forget to add the return value.

Then, in the main program we ask the user for a float number, because, if we try to convert the value into int type, and the user inputs 2.4 for example, the program will show us an error, and, we can calculate the roots for decimal numbers.

Then , we check if the value asked is positive (if is bigger than 0), if it’s negative, we print the message (“There’s no square root

Continue reading "Quiz Week 3"

WSQ06-Calculadora Factorial

--Originally published at Home Page

What to do?

Create a program that asks the user for a non-negative integer (let’s call that number n) and display for them the value of n! (n factorial).

After showing them the answer, ask them if they would like to try another number (with a simple y/n response) and either ask again (for y) or quit the program and wish them a nice day (if they answered n).

Solucion.-

Debemos hacer un programa que pida un valor positivo al usuario (n) y devuelva el factorial de ese número (n!), después debemos preguntarle si desea introducir otro número, en caso que no desee, desearle un buen día.

WSQ06-1

Podemos observar en la línea uno del programa, un comentario, éstos se realizan para poder describir qué hace cada parte del código, para que alguien más lo lea (O incluso nosotros en un futuro), y sepa bien de qué trata el programa, o qué estamos haciendo exactamente.

Para hacer un comentario en python 3, como observamos, debemos poner un “#” antes de lo que deseemos escribir

Como está en el programa, comenzamos con un loop, que servirá para preguntarle al usuario si desea introducir otro número, en este caso es True, porque no sabemos cuándo querrá dejar de escribir números.

Después, le pedimos que ingrese un número, y vemos que dentro tenemos otro ciclo, sin embargo este no es infinito, resultado va a ser una variable acumuladora, y x es un contador, para así poder manera el loop de una mejor manera.

Dentro de este loop, multiplicamos resultado por el contador, que irá aumentando hasta que sea igual al número ingresado por el usuario, ésto calculará el factorial (Por ejemplo: 5, 1*2*3*4*5=120)

Después, FUERA del segundo loop, imprimimos el resultado, y preguntamos si desea introducir otro número, si el usuario responde

WSQ06-cyg
Continue reading "WSQ06-Calculadora Factorial"

WSQ05-On to Functions-Funciones

--Originally published at Home Page

What to do?

You will go back and do WSQ01 – Fun with Numbers again.

But this time, write a function for each calculation. Each function should define two parameters (in this example of type int) and return the correct value as an integer as well.

You main program needs to ask the user for the input and then call each function to calculate the answer for each of the parts.

Solution.-

Esta vez el blog será en español, veremos las funciones en Python3!

Muy bien! Primero debemos comprender qué son funciones, en Matemáticas, las funciones son operaciones o procesos que se realizan a uno o más parámetros.

En computación es prácticamente lo mismo, definimos funciones que toman parámetros y hacen operaciones o procesos con éstos.

Se escribe:

def funcion(parametros):

Código…

Si establecemos más de un parámetro, debemos separarlos con una “,”.

Después, simplemente debemos llamar estas funciones e insertar los datos o variables que queremos que tome como parámetros.

WSQ05

Como vemos, podemos nombrar de cualquier manera a nuestras funciones, y debemos establecer los parámetros al definirla.

Básicamente esto servirá para saber cuántos parámetros va a tomar, y para poder “nombrarlos” al momento de operar con ellos, es decir, first y second pueden ser cambiados por cualquier otro nombre como a,b; c,d; o lo que sea, siempre y cuando dentro de la función también cambiemos los nombres. (Ejemplo: Si cambiamos first y second por a y b respectivamente, dentro de la función debemos cambiar igual a+b.)

No debemos olvidar los espacios pertinentes, esto es necesario para saber qué operaciones va dentro de cada función, e igual distinguir funciones.

Cada función tiene la palabra return, que es el valor o dato que esta variable regresa al ser llamada.

Después hacemos el programa normal, parecido al primer WSQ, pero al

WSQ05-cyg
Continue reading "WSQ05-On to Functions-Funciones"

WSQ04- Sum of Numbers

--Originally published at Home Page

WHAT TO DO?

Write a program that asks for a range of integers and then prints the sum of the numbers in that range (inclusive).

You can use a formula to calculate this of course but what we want you to do here is practice using a loop to do repetitive work.

For example, the sum from 6 to 10 would be 0 + 6 + 7 + 8 + 9 + 10.

Notice our sum starts with zero (why?) and then we add each number in the range provided by the user. Just for fun, what is the mathematical formula to do this calculation?

Solution.-

WSQ04As in the previous blog, we use the while statement, in this case we write a condition, so the program will sum the numbers between the values given by the user.

Also, we write an if statement before, with this we are checking that, the user don’t give invalid numbers (for example 10 as the lower bound and 2 as the bigger one)

In this case identation is very important, that’s the reason why the program prints the result after the loop ends.

WSQ04-Cyg

As always, we save the program with the .py extension, and then we run in Cygwin.

It works!!

 

 


WSQ03 – Pick a Number

--Originally published at Home Page

Write a program that picks a random integer in the range of 1 to 100.

There are different ways to make that happen, you choose which one works best for you.

It then prompts the user for a guess of the value, with hints of ’too high’ or ’too low’ from the program.

The program continues to run until the user guesses the integer. You could do something extra here including telling there user how many guesses they had to make to get the right answer.

You might want to check that your program doesn’t always use the same random number is chosen and you should also split your problem solving into parts. Perhaps only generate the random number and print that as a first step.

Solve:WSQ03In this case, we will use libraries.

As you can see, we import random library, in order to make this program

Then we will use random.randint(1,100), that generates a random value between the 2 numbers you give.

Then, you see the while statement, this will do what you want to, until the condition stablished is not true, in this case, we use While True, that is an infinite loop.
and, intento+=1 is equal to intento=intento+1, this is in the program in order to print the times the user tries to guess the number.

Then, the break statement, is used to get out, in this case, of the infinite loop.

Let’s see the program running

WSQ03_cyg

As you see, the program works correctly!

 


WSQ02.- Temperature

--Originally published at Home Page

Write a program that will prompt the user for a temperature in Fahrenheit and then convert it to Celsius. You may recall that the formula is C = 5 ∗ (F − 32)/9.

Modify the program to state whether or not water would boil at the temperature given. Your output might look like the following

Example Run

What is the temperature in Fahrenheit? 100

A temperature of 100 degrees Fahrenheit is 37 in Celsius

Water does not boil at this temperature (under typical conditions).

 

Time to solve!

WSQ02

As you see, in this case we ask for a float number, because the temperature can be a decimal value.

Then we see something new, the if statement, the correct way to write if is:

if expression:

statements

Don’t forget the identation, otherwise it won’t work.

else:

statements

So, in this case if the temperature in Celcius Degrees is lower than 100 (water boils at 100), we print that message, otherwise, we print the second.

Then, as always, we run the program in cygwin.

WSQ02-cyg


WSQ01! Fun with Numbers!

--Originally published at Home Page

What to Do

  • The sum of the two numbers.
  • The difference of the two numbers.
  • The product of the two numbers.
  • The integer based division of the two numbers (so no decimal point). First divided by second.
  • The remainder of integer division of the two numbers.

 

Solved:

Now , we’ll solve this problem and learn some operators in python 3

You have the solved program:

WSQ01

As you can see, first we ask the user for the numbers, then, we declare the operations.

In Line 7, we convert Div into an int value, otherwise, the result will be a float number

We use % operator, to get the Remainder as the result

Now, let’s Try it!

WSQ01_cyg

Here, i tried with 10 and 3, and it worked! You can try with any other number you want.


Basic Input and operations

--Originally published at Home Page

You can ask the user for a word, a number, etc.
To make this possible, we use the word input, as you can see in the example below :

Input

To print the value, you can do it writing the name of that value.

In Python 3, every input is automatically interpreted as String, so, if you want to make an operation, you should convert it to a numerical value, by using int for integer numbers or float for decimal numbers.

Nums

In this example, we use the word int before the input, and then we write the next in parenthesis

Then, you have a sum, as you see, you should declare your variable first and then the operation, otherwise, it’s a wrong syntaxis

And this is the complete program, now, we can try to run it in Cygwin, and see if it works!

Complete input Inp_cyg

And that’s it! The program works!!

 

 


Comencemos!

--Originally published at Home Page

¡Hola! Bienvenido al primer blog de Python3.
Empezaremos con Impresión básica de datos.
Primero, abriremos Atom, nuestro editor de texto.
Podremos apreciar la página de bienvenida, para iniciar un nuevo proyecto, debemos ir a File, seguido de New File, o simplemente usar el shortcut Ctrl + N, en el teclado.
Seguido de esto, procederemos a guardar el archivo con el nombre HolaMundo.py
Para imprimir un mensaje en pantalla, tenemos print(), si queremos escribir un mensaje, debemos poner entre comillas lo que deseamos imprimir.

First

 

Ahora, abriremos nuestro Terminal (Cygwin, en este caso), y escribiremos la ruta a la carpeta donde guardamos el programa, finalmente, escribimos python3 y el nombre de nuestro programa.

cyg

Quedaría así: