Good day. I am a newbie in creating a python program. My program is to write code that prints Hello if 1 is stored in spam, prints Howdy if 2 is stored in spam, and prints Greetings! if anything else is stored in spam.
My problem is that I would like to repeat the process if the user will not input anything or an empty value. How will I convert '' to value 0. Thanks. Im sorry if my program is not that good.
while True:
print ('Enter value of spam')
spam = int(input())
if spam == 1:
print ('Hello')
continue
elif spam == 2:
print ('Howdy')
continue
elif spam != 0:
print ('Greeting')
continue
Try this.
print ('Enter value of spam')
spam = input()
while spam != "" or spam == 0:
if int(spam) == 1:
print ('Hello')
elif int(spam)== 2:
print ('Howdy')
elif int(spam)!= 0:
print ('Greeting')
print ('Enter value of spam')
spam = input()
You could use a try-except block to handle any situation where your user's input can't be understood as an integer:
while True:
print ('Enter value of spam')
try:
spam = int(input())
except ValueError:
spam = 0
if spam == 1:
print ('Hello')
continue
elif spam == 2:
print ('Howdy')
continue
elif spam != 0:
print ('Greeting')
continue
Related
I was given an encrypted copy of the study guide here, but how do you decrypt and read it???
In a file called pa11.py write a method called decode(inputfile,outputfile). Decode should take two parameters - both of which are strings. The first should be the name of an encoded file (either helloworld.txt or superdupertopsecretstudyguide.txt or yet another file that I might use to test your code). The second should be the name of a file that you will use as an output file.
Your method should read in the contents of the inputfile and, using the scheme described in the hints.txt file above, decode the hidden message, writing to the outputfile as it goes (or all at once when it is done depending on what you decide to use).
The penny math lecture is here.
"""
Program: pennyMath.py
Author: CS 1510
Description: Calculates the penny math value of a string.
"""
# Get the input string
original = input("Enter a string to get its cost in penny math: ")
cost = 0
Go through each character in the input string
for char in original:
value = ord(char) #ord() gives us the encoded number!
if char>="a" and char<="z":
cost = cost+(value-96) #offset the value of ord by 96
elif char>="A" and char<="Z":
cost = cost+(value-64) #offset the value of ord by 64
print("The cost of",original,"is",cost)
Another hint: Don't forget about while loops...
Another hint: After letters -
skip ahead by their pennymath value positions + 2
After numbers - skip ahead by their number + 7 positions
After anything else - just skip ahead by 1 position
The issue I'm having in that I cant seem to get the coding right to decode the file it comes out looking the same. This is the current code I have been using. But once I try to decrypt the message it stays the same.
def pennycost(c):
if c >="a" and c <="z":
return ord(c)-96
elif c>="A" and c<="Z":
return ord(c)-64
def decryption(inputfile,outputfile):
with open(inputfile) as f:
fo = open(outputfile,"w")
count = 0
while True:
c = f.read(1)
if not c:
break;
if count > 0:
count = count -1;
continue
elif c.isalpha():
count = pennycost(c)
fo.write(c)
elif c.isdigit():
count = int(c)
fo.write(c)
else:
count = 6
fo.write(c)
fo.close()
inputfile = input("Please enter the input file name: ")
outputfile = input("Plese enter the output file name(EXISTING FILE WILL BE OVER WRITTEN!): ")
decryption(inputfile,outputfile)
I make a code based on a table game. At the beginning of the code, it must ask the player the name of the player, and when the player inputs an "enter", my code shows an error. I want that when the player inputs an "enter", the program says something like "This name is invalid", ask repeat asking the name of the player. Here is a part of my code:
repeat{
if(r==1){
print("Name Player 1: ")
name1=scan(,what="character",1)
if(any(name1==gamers)){
r=readline(prompt = "This player is already in the file. Would you like to change the name? \n 1. Yes \n 2. No \n Select an option: ")
if(r==0){
r<-99
}
Instead of print(...); name1=scan(...), I'd use readline, as such:
while (!nzchar(name1 <- readline("Name Player 1: "))) TRUE
# Name Player 1: <-- me just hitting <enter>
# Name Player 1: <-- again
# Name Player 1: r2evans
name1
# [1] "r2evans"
You might prefer to allow a max number of failed attempts, though, instead of requiring the user interrupt the process with ctrl-c, so perhaps:
tries <- 3L
while (tries > 0 && !nzchar(name1 <- readline("Name Player 1: "))) tries <- tries - 1L
# Name Player 1:
# Name Player 1:
# Name Player 1:
And the loop just stopped/exited. You "know" that the user chose to quit because after the loop, tries == 0L and !nzchar(name1) both indicate the user's intent.
I am trying to make a program to prompt a user for input until they enter a number within a specific range.
What is the best approach to make sure the code does not error out when I enter a letter, a symbol, or a number outside of the specified range?
In alternative to parse, you can use tryparse:
tryparse(type, str; base)
Like parse, but returns either a value of the requested type, or
nothing if the string does not contain a valid number.
The advantage over parse is that you can have a cleaner error handling without resorting to try/catch, which would hide all exceptions raised within the block.
For example you can do:
while true
print("Please enter a whole number between 1 and 5: ")
input = readline(stdin)
value = tryparse(Int, input)
if value !== nothing && 1 <= value <= 5
println("You entered $(input)")
break
else
#warn "Enter a whole number between 1 and 5"
end
end
Sample run:
Please enter a whole number between 1 and 5: 42
┌ Warning: Enter a whole number between 1 and 5
└ # Main myscript.jl:9
Please enter a whole number between 1 and 5: abcde
┌ Warning: Enter a whole number between 1 and 5
└ # Main myscript.jl:9
Please enter a whole number between 1 and 5: 3
You entered 3
This is one possible way to achieve this sort of thing:
while true
print("Please enter a whole number between 1 and 5: ")
input = readline(stdin)
try
if parse(Int, input) <= 5 || parse(Int, input) >= 1
print("You entered $(input)")
break
end
catch
#warn "Enter a whole number between 1 and 5"
end
end
Sample Run:
Please enter a whole number between 1 and 5: 2
You entered 2
See this link for how to parse the user input into an int.
In a dataframe poll, statement 1 works but statement 2 does not. Any advise as why this is happening ? Error which is coming wrong.
Statement 1:
test = subset(poll, Internet.Use=="1" | Smartphone == "1")
Statement 2 :
limited = subset(po11, Internet.Use=="1" | Smartphone == "1")
Error in subset(po11, Internet.Use == "1" | Smartphone == "1") :
object 'po11' not found
In your second statement you are writing po11 (with two digits "1" instead of two characters "l").
Therefore R can´t find this object, because it doesn´t exist.
I am writing this code and have recently come across an error. I have no idea why this is happening. In theory, the english alphabet should be being printed. However, instead of the english alphabet, symbols are being printed instead.
I can not paste the symbols for some reason, but if you ran the code yourself, you'll understand what I mean.
My full code is posted below.
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFHIJKLMNOPQRSTUVWXYZ0123456789"
choice = input("Would you like to encrypt or decrypt? [e/d]: ")
if choice == "e":
message = input("Please insert the message you would like to use: ")
keyword = input("Please insert the keyword you would like to use: ")
ik = len(keyword)
i = 0
string = ''
for A in message:
message1 = (ord(A)) - 96
key1 = (ord(keyword[i])) - 96
addition = message1 + key1
string += (chr(addition))
if i >= ik:
i = 0
else:
i += 1
print (string)
You need to add back the 96 you originally took away :) Alternatively, use the Caesar cipher formula as adding back 96 will still result in symbols appearing (I did the ocr coursework already)
addition = message1 + key1 + 96
your code will not work if the keyword is shorter than the message, so use the modulo operator (%) on i with the length of the keyword inside the line:
key1 = (ord(keyword[i])) - 96