I wanted the code to print out certain strings.
The issue was the the output was not what I expected, since it would print out something like this:
BruhBruh
BruhBruh
I was hoping for this:
Bruh
Bruh
How do I fix it?
def repeate(c,rep):
c=input("what str")
rep=int(input("how many times?"))
for i in range(rep):
print(c*rep)
return i
repeat=repeate(0,0)
print(repeat)
Add a space to the user input.
Change your line:
c=input("what str") + “ “
Now if the user enters “Dude”, c will be “Dude “.
by calling print(c*rep) you are printing out a catenation of rep instances of string c
and this gets repeated in cycle for i in range(rep): for additional rep times
to get string repeated certain amount of times you may use function join on the array of strings, e.g.
print(" ".join(['Bruh']*3))
alternately use print with default (crlf) terminator replaced with space char:
for i in range(3):
print("Bruh", end=" ")
also, both args of this function are useless -- you just set them in function body via input
Related
I trying to make a password generator using python. Currently, I just want the program to print random characters from the ascii table. I will later introduce numbers and symbols. I used a for loop to print random character from a range that the user inputs. It works however, when I use the end='' to print the characters on the same line a % shows up. I think it is there to show that it printed a no character. I would like the program to not print the % because later I will add other numbers and symbols.
I tried subtracting 1 from the range of number. What resulted was the same string with a % but 1 less than intended. I also tried creating a while loop that would print while the variable was less than the password number. It also printed the %.
Here is the code:
import random
import string
letters=string.ascii_letters
passwordnumber=int(input("How many characters do you want your password to be? "))
for i in range(passwordnumber):
print(random.choice(letters), end='')
The % print by your shell (may be zsh), it means the string not end by "\n". It's just a reminder from the shell. There is nothing wrong with you. You can just add a print() in the end of your code to print a "\n", and % will not show again.
Try this
characters = list(string.ascii_letters + string.digits + "!##$%^&*()")
def generate_random_password():
## length of password from the user
length = 8
## shuffling the characters
random.shuffle(characters)
## picking random characters from the list
password = []
for i in range(length):
password.append(random.choice(characters))
## shuffling the resultant password
random.shuffle(password)
## converting the list to string
## printing the list
return "".join(password)
Your script works absolutly fine in my side. see this https://onlinegdb.com/9EagkKVW1
If you feel like it's issue with end you can simply concat outputs to string and print at once like so.
import random
import string
letters=string.ascii_letters
pas =''
passwordnumber=int(input("How many characters do you want your password to be? "))
for i in range(passwordnumber):
pas += random.choice(letters)
print(pas)
outputs #
How many characters do you want your password to be? 5
AvfYm
we can use the random .sample() method. it requires 2 arguments:
- iterable of elements to use
- number of elements to take
the result does not contain duplicates.
import random
import string
letters=string.ascii_letters
passwordnumber=int(input("How many characters do you want your password to be? "))
pas = ''.join(random.sample(letters, k=passwordnumber))
print(pas)
I'm very new to coding and im learning python and I have a certain problem.
I'm writing a program which requires the user to input an amount and I want the program to always
print out 15 zeros but I want the amount the user inputs to replace the zeros starting from the end.
For example, if the user enters 43525.
The program would print 000000000043525
Also for example if the user inputs 2570.20
The program would print 000000000257020 (removes dot automatically)
can anyone help me with how I should go about doing this?
you can use .replace() to remove any decimal point and .rjust() to add the right number of zeros
print(input('number: ').replace('.', '').rjust(15, '0'))
You can just use simple string manipulations to do this. For example:
k = 212.12
if '.' in str(k):
string = str(k).replace('.','')
print('0'*(15-len(string))+string)
else:
print('0'*(15-len(str(k)))+str(k))
You can use zfill for this:
print(''.join(input('Enter number: ').split('.')).zfill(15))
You can add leading 0s by using this string formatting while printing:
print("%015d" % (int(number),))
This means 0s will be added until 15 characters are printed.
For the removal of decimal dot you can use string replace method:
number = str(number).replace('.', '')
This should get you started.
Using list slicing
added_string = added_string.replace(".", "")
new_str = start_string[:len(start_string) - len(added_str)] + added_string
To do:
Convert python to ythonpay (i.e. pick up a first letter, put it in the end and add 'ay' and make sure the user has not entered in the word numbers or alphanumeric word )
def check(word):
if word.isalnum() or word.isdigit():
print ("Enter valid word!")
else:
print ("Thank You for Entering a valid word!")
first_letter = word[0]
new_word = word.strip(word[0])
PygLatin = new_word+first_letter+"ay"
print (PygLatin)
word= input("enter a word:").lower()
result = check(word)
result I got:
1>> enter a word -> python
2>> Enter valid word!
There are two fundamental issues with your code (and one stylistic issue).
Usually you want functions to return something. For example your intention is to take a word, move the first letter to the end of the word, and add "ay" ... in other words to render it in "Pig Latin."
But you're print-ing the results rather than return-ing them. You might think that using print returns a value (in the sense that it "returned" something to your screen or terminal). But that's not what "return" means in computer programming. The Python return statement is how your function returns a result to the rest of the program following any particular invocation of (or "call into") your function.
Here's the simplest function that would work:
def pigify(word):
return word[1:]+word[0].lower()+'ay'
... that will take a "slice" of the word from a one character offset into the string all the way to the end of the string. That's what [1:] means ... it describes a range of characters, how far to the start of the range and then how far to go to get up to (but not including) the end. Then it adds the first character (which is "zero characters" from the beginning of the string), converts that to lower case (which is harmless for all characters, and only affects capital letters) and then it adds the literal string "ay" ... and it takes all of that and returns it.
pig_latin = pigify("Python")
print(pig_latin)
# ---> prints "ythonpay"
The other issue with your code is that you're calling string methods in a confused way. word.alnum() will return True only if all the characters are alphanumeric and word.isdigit() will return True only if all of the characters are numeric. That's the same as just calling word.isdigit() since digits are a proper subset of the alphanumeric character set. In other words the only strings that will pass your code will be those which contain no letters (or other characters); clearly not what you intended.
You probably would prefer to check that the string consists entirely of alphabetic characters:
def pigify(word):
if word.isalpha():
return word[1:]+word[0].lower()+'ay'
# or else? ....
This leaves you with the question of what you should do with an invalid argument (value passed to your function's "word" parameter by the caller).
You could print an error message. But that's considered poor programming practice. You could return some special value such as Python's None value; but then code that calls your function must either check the results every time, or results can cause some other error far removed from where your function was called (where this non-string value was returned).
You can also raise an exception:
def pigify(word):
if word.isalpha():
return word[1:]+word[0].lower()+'ay'
raise ValueError("Invalid input for pigify()")
... note that I don't need to explicitly spell out else in this case; the control flow only reaches that statement if I didn't return a value, only when it's an error. Any other time the control flow returns to the calling code (the part of the program that called my pigify() function).
Another thing I could do is decide that pigify() simply returns anything that doesn't look like a "word" exactly as it was passed:
def pigify(word):
if word.isalpha():
return word[1:]+word[0].lower()+'ay'
else:
return word
... here I could just return word without the else: as it did before with the raise statement. But I personally think that looks wrong; so I've explicitly spelled out the else: clause purely for stylistic reasons.
Mostly you want your program to be composed of functions (or objects with methods) that work with (manipulate) the data, and then a smaller body of code (possibly functions or object and their methods) which then "render" the results of those manipulations. Any time you're writing a function which manipulations or transforms data and writes those results to the screen or into a web page, or out to a file or database, you should pause and reconsider your design. The transformative/manipulations and computations might be re-useable while the code which writes results is typically quite specific. So interleaving one with the other is usually a bad decision.
The str.isdigit() and str.isalnum() methods only return true if all of the characters match the criteria. Your test is written so that you want to detect whether any of the characters match the criteria:
>>> word = 'abc123'
>>> word.isdigit()
False
>>> any(map(str.isdigit, word))
True
So you can amend the code to start with something like this:
def check(word):
if not word.isalnum() or any(map(str.isdigit, word)):
print ("Enter valid word!")
else:
print ("Thank You for Entering a valid word!")
...
FWIW, str.isalpha() would be easier to use because digits are already excluded.
In your code, you have problem with isalnum() which returns true if string contains only alphabets, only numbers or contains both alphabets and numbers so you can try to match if string only contains alphabets and execute your code as follow:
def check(word):
if word.isalpha(): # process only if word contains only alphabets
print("Thank You for Entering a valid word : {}!".format(word))
print(word[1:] + word[0] + "ay") # slicing is better choice in your case
else:
print("Enter valid word!!!")
word = input("enter a word:")
result = check(word.lower())
Python provides a built-in function called len that returns the length of a string, so the value of len('allen') is 5. Write a function named right_justify that takes a string named s as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.
Author's solution:
def right_justify(s):
print (' '*(70-len(s))+s)
>>> right_justify('allen')
My solution:
def right_justify(s):
space_count=70-len(s)
for i in range(0,space_count,1):
print " ",
print s
strng=raw_input("Enter your desired string:")
print len(strng)
right_justify(strng)
The output of my code is different than the output of author's code: I am getting twice as many spaces, e.g. 130 instead of 65.
But it seems to me that the two pieces of code are logically equivalent. What am I overlooking?
The problem is with your print statement
print " ",
will print two spaces for each iteration of the loop. When terminating the print statement with a comma, subsequent calls will be delimited by a space.
On a side note, another way to define your right_justify function would be
def right_justify(s):
print '%70s' % s
The print " ", line actually prints two spaces (one from the " ", one from the ,). You could replace it with print "", to have your function work identically to the original.
Your code has 130 spaces, the author's code has 65 spaces. This is because
print " ",
...adds a space. What you want is:
print "",
I would prefer the function str.rjust(70," ") which does the trick, I think, like so:
strng.rjust(70," ")
I've got a two letter word that I'd like to attach to a double digit number. The word is an integer and the number is a string.
Say the name of the number is "number" and the name of the word is "word".
How would you make it print both of them together without spaces. When I try it right now it still has a space between them regardless of what I try.
Thanks !
'{}{}'.format(word, number)
For example,
In [19]: word='XY'
In [20]: number=123
In [21]: print('{}{}'.format(word, number))
XY123
The print function has a sep parameter that controls spacing between items:
print(number, word, sep="")
If you need a string, rather than printing, than unutbu's answer with string formatting is better, but this may get you to your desired results with fewer steps.
In python 3 the preferred way to construct strings is by using format
To print out a word and a number joined together you would use:
print("{}{}".format(word, number))